Stripe Webhook Signature Verification & Event Dispatcher

'use strict'; const crypto = require('crypto'); /** * Securely verify Stripe webhook signature without external heavy dependencies * @param {string|Buffer} payload - Raw HTTP request body buffer * @param {string} sigHeader - 'stripe-signature' HTTP header * @param {string} secret - Webhook endpoint signing secret (whsec_...) * @param {number} toleranceSec - Signature freshness tolerance in seconds */ function verifyStripeWebhookSignature(payload, sigHeader, secret, toleranceSec = 300) { if (!sigHeader || !secret) { throw new Error('Missing signature header or signing secret'); } const parts = sigHeader.split(',').reduce((acc, item) => { const [k, v] = item.trim().split('='); if (k === 't') acc.timestamp = parseInt(v, 10); if (k === 'v1') acc.signatures.push(v); return acc; }, { timestamp: 0, signatures: [] }); const now = Math.floor(Date.now() / 1000); if (Math.abs(now - parts.timestamp) > toleranceSec) { throw new Error('Webhook timestamp exceeds tolerance'); } const signedPayload = `${parts.timestamp}.${payload.toString('utf8')}`; const expectedSignature = crypto .createHmac('sha256', secret) .update(signedPayload, 'utf8') .digest('hex'); const isValid = parts.signatures.some(sig => { try { return crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expectedSignature, 'hex')); } catch { return false; } }); if (!isValid) { throw new Error('Invalid webhook signature'); } return JSON.parse(payload.toString('utf8')); } module.exports = { verifyStripeWebhookSignature };
Stripe Webhook Signature Verification & Event Dispatcher
Note
Notification