Next.js

import crypto from 'crypto';
import { NextApiRequest, NextApiResponse } from 'next';
import getRawBody from 'raw-body';

// Raw body is required for signature verification
export const config = {
  api: {
    bodyParser: false
  }
}

async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const SECRET_KEY = process.env.SECRET_KEY;

    if (typeof SECRET_KEY !== 'string') {
      throw new Error('No secret key found');
    }

    // Get the raw body of the request
    const rawBody = await getRawBody(req);

    // Generate HMAC-SHA256 signature of the raw body using the secret key
    const signature = hmacSha256(rawBody, SECRET_KEY);

    // Compare the generated signature with the 'x-lynn-hmac-sha256' header
    if (signature !== req.headers['x-lynn-hmac-sha256']) {
      return res.status(400).json({ message: "Signature didn't match" });
    }

    // If the signature matches, parse the JSON body
    const receivedJson = JSON.parse(rawBody.toString());
    console.log('Received:', receivedJson);

    // Respond with a 200 OK status
    res.status(200).end('OK');
  } else {
    // If the request method is not POST, return 405 Method Not Allowed
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

// Function to generate HMAC-SHA256 signature
function hmacSha256(data: Buffer, secret: string): string {
  return crypto.createHmac('sha256', secret).update(data).digest('hex');
}

export default webhookHandler;

Was this helpful?