const crypto = require('crypto');
function verifySignature(payload, signature, secret) {
const hmac = crypto.createHmac('sha256', secret);
const calculatedSignature = hmac.update(payload).digest('hex');
return crypto.timingSafeEqual(
Buffer.from(calculatedSignature, 'hex'),
Buffer.from(signature, 'hex'),
);
}
// Express example
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
if (
!verifySignature(
req.body.toString(),
req.headers['x-caret-signature'],
process.env.WEBHOOK_SECRET,
)
) {
return res.status(401).send('Invalid signature');
}
const data = JSON.parse(req.body.toString());
// Process webhook...
res.status(200).send('Webhook received');
});