When a payment is successfully made using the LemonSqueezy API, a webhook sends a payload. However, I am encountering an issue with verifying the signature. For more information, you can refer to this documentation:
Below is my TypeScript code for a post request:
import express, { Request, Response } from 'express';
import * as crypto from 'crypto';
import bodyParser from 'body-parser';
const webhook = express.Router();
let secret = "secretkey"
webhook.use(bodyParser.json())
webhook.post('/webhooks', async (req: Request, res: Response) => {
try {
if (!req.body) {
throw new Error('Missing request body');
}
// Create HMAC signature
const hmac = crypto.createHmac('sha256', secret);
const digest = Buffer.from(hmac.update(JSON.stringify(req.body)).digest('hex'), 'utf8');
// Retrieve and validate X-Signature header
const signature = Buffer.from(req.get('X-Signature') || '', 'utf8');
if (!crypto.timingSafeEqual(digest, signature)) {
throw new Error('Invalid signature');
}
const payload = req.body;
console.log('Received valid webhook:', payload);
return res.status(200).send({'Webhook received': payload});
} catch (err) {
console.error(err);
return res.status(400).send(err);
}
});
export default webhook