Integration Examples

Complete integration examples

JavaScript/Node.js

Complete integration example using Express:

const express = require('express');
const crypto = require('crypto');
const axios = require('axios');

const app = express();
const PORT = process.env.PORT || 3000;

// Joy API client setup
const joyApi = axios.create({
  baseURL: 'https://joy.avada.io/app/api/v1',
  headers: {
    'X-Joy-Loyalty-App-Key': process.env.JOY_APP_KEY,
    'X-Joy-Loyalty-Secret-Key': process.env.JOY_SECRET_KEY
  }
});

// HMAC verification middleware
function verifyWebhook(req, res, next) {
  const hmac = req.get('X-Joy-Loyalty-Hmac-Sha256');
  const calculatedHmac = crypto
    .createHmac('sha256', process.env.JOY_SECRET_KEY)
    .update(req.rawBody, 'utf8')
    .digest('base64');

  if (!crypto.timingSafeEqual(Buffer.from(calculatedHmac), Buffer.from(hmac))) {
    return res.status(401).send('Invalid signature');
  }
  
  next();
}

// Raw body parser for HMAC verification
app.use('/webhook', express.raw({type: 'application/json'}), (req, res, next) => {
  req.rawBody = req.body;
  req.body = JSON.parse(req.body);
  next();
});

// Webhook handlers
app.post('/webhook/points-earned', verifyWebhook, (req, res) => {
  const {customer, oldPoint, newPoint} = req.body;
  console.log(`Customer ${customer.email} earned ${newPoint - oldPoint} points`);
  
  // Your business logic here
  
  res.status(200).send('OK');
});

app.post('/webhook/tier-upgraded', verifyWebhook, (req, res) => {
  const {customer, oldTierName, newTierName} = req.body;
  console.log(`Customer ${customer.email} upgraded from ${oldTierName} to ${newTierName}`);
  
  // Your business logic here
  
  res.status(200).send('OK');
});

// API management functions
async function createWebhook(topic, url) {
  try {
    const response = await joyApi.post('/webhooks', {topic, url});
    return response.data;
  } catch (error) {
    console.error('Failed to create webhook:', error.response?.data || error.message);
    throw error;
  }
}

async function listWebhooks() {
  try {
    const response = await joyApi.get('/webhooks');
    return response.data.webhooks;
  } catch (error) {
    console.error('Failed to list webhooks:', error.response?.data || error.message);
    throw error;
  }
}

app.listen(PORT, () => {
  console.log(`Webhook server running on port ${PORT}`);
});

Python

Complete integration example using Flask:

PHP

Complete integration example:

Last updated