Verifying Webhook Requests
const crypto = require('crypto');
const webhookSecret = "your-shared-secret";
const verifyOrderWebhook = (req, res, next) => {
const signature = req.headers['x-signature'];
const timestamp = parseInt(req.headers['x-timestamp'], 10);
const orderId = req.body.orderId;
const currentTimestamp = Math.floor(Date.now() / 1000);
if (Math.abs(currentTimestamp - timestamp) > 300) {
return res.status(401).json({ error: 'Webhook request is too old' });
}
const payload = orderId + '.' + timestamp;
const hmac = crypto.createHmac('sha256', webhookSecret);
hmac.update(payload);
const computedSignature = hmac.digest('hex');
if (computedSignature !== signature) {
return res.status(401).json({ error: 'Invalid signature' });
}
next();
};
const verifyWebhook = (req, res, next) => {
const signature = req.headers['x-signature'];
const timestamp = parseInt(req.headers['x-timestamp'], 10);
const currentTimestamp = Math.floor(Date.now() / 1000);
if (Math.abs(currentTimestamp - timestamp) > 300) {
return res.status(401).json({ error: 'Webhook request is too old' });
}
const payload = timestamp;
const hmac = crypto.createHmac('sha256', webhookSecret);
hmac.update(payload);
const computedSignature = hmac.digest('hex');
if (computedSignature !== signature) {
return res.status(401).json({ error: 'Invalid signature' });
}
next();
};Last updated