Verify Stripe webhook signature
Verify a Stripe webhook signature with stripe.webhooks.constructEvent, passing the raw request body and the Stripe-Signature header.
Stripe signs every webhook, and its library checks the signature and the timestamp for you. It needs the raw bytes of the body, so do not run express.json() on that route.
import Stripe from 'stripe';
import express from 'express';
const stripe = new Stripe('sk_test_placeholder');
const secret = 'whsec_test_secret';
const app = express();
app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
try {
const event = stripe.webhooks.constructEvent(req.body, req.get('stripe-signature'), secret);
console.log(event.type);
res.sendStatus(200);
} catch (err) {
res.status(400).send('Invalid signature');
}
});
const payload = JSON.stringify({ id: 'evt_1', object: 'event', type: 'ping' });
const header = stripe.webhooks.generateTestHeaderString({ payload, secret });
console.log(stripe.webhooks.constructEvent(payload, header, secret).id);
try {
stripe.webhooks.constructEvent(payload + ' ', header, secret);
} catch (err) {
console.log(err.type);
}evt_1
StripeSignatureVerificationErrorThe helper generateTestHeaderString builds a valid header for the demo; in the route, the header comes from the request. Changing one byte of the payload makes the check fail with a StripeSignatureVerificationError, so the route answers 400.
express.raw() keeps the body as a Buffer. If another middleware parses the JSON first, the bytes differ from what Stripe signed and every event fails. The default tolerance is five minutes. See Stripe's webhook signature guide.