You added Stripe to your app, dropped in a /webhooks/stripe route, and it works: a test payment comes in, the handler marks the order paid. Ship it, right?
Not yet. That route is a public URL on the internet, and right now it probably believes anything that POSTs to it. Someone who guesses the path can send a fake checkout.session.completed and get a paid plan for free. A flaky network can deliver the same real event twice and double-charge or double-provision. Both are common, both are avoidable, and both are the kind of thing an AI assistant will happily leave out unless you ask.
This guide shows exactly what Stripe signs, how to verify it (we’ll build the check from scratch in Node so you understand what the SDK does), and the two operational rules the Stripe docs stress. Everything here is testable offline — no Stripe account, no keys, no network.
Prerequisites
- Node.js ≥ 18 (we use the built-in
node:crypto). - A rough idea of what an HTTP POST body is.
- If you have a Stripe integration already, your endpoint’s signing secret (
whsec_...) — but you won’t need it to follow along.
What Stripe actually signs
When Stripe sends an event, it includes a Stripe-Signature header that looks like this (as of 2026-08, per Stripe’s webhook documentation):
Stripe-Signature: t=1722700000,v1=5257a869e7ec…,v0=6ffbb59b23…
t=is a Unix timestamp.v1=is the signature you should verify. (v0is a fake scheme used only for test events — ignore it in production.)
Stripe computes v1 by building a signed payload string and hashing it:
signed_payload = t + "." + <the raw request body>
signature = HMAC_SHA256(key = your_signing_secret, message = signed_payload)
Two details do all the damage when people get them wrong:
- It’s the raw body. The signature is over the exact bytes Stripe sent. If your framework parses the JSON and you re-
JSON.stringify()it, the bytes change (key order, whitespace) and verification fails — or worse, people “fix” it by skipping verification. Capture the raw body. - The secret is a shared key, not a password you look up. Only you and Stripe know it, so a correct HMAC proves the message came from Stripe and wasn’t altered.
Verify it (from scratch, in Node)
Here’s the core. It parses the header, recomputes the HMAC over the raw body, and compares in constant time. The full file with tests is in the example directory.
import crypto from 'node:crypto';
export function computeSignature(rawBody, timestamp, secret) {
const signedPayload = `${timestamp}.${rawBody}`;
return crypto.createHmac('sha256', secret).update(signedPayload, 'utf8').digest('hex');
}
export function verifyWebhook(rawBody, header, secret, toleranceSeconds = 300,
nowSeconds = Math.floor(Date.now() / 1000)) {
// Parse "t=...,v1=...,v1=..." (there can be more than one v1 during key rotation).
const parts = { v1: [] };
for (const item of header.split(',')) {
const [k, v] = item.split('=');
if (k === 't') parts.t = Number(v);
else if (k === 'v1') parts.v1.push(v);
}
if (!parts.t || parts.v1.length === 0) throw new Error('malformed Stripe-Signature header');
const expected = computeSignature(rawBody, parts.t, secret);
const ok = parts.v1.some((sig) =>
sig.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex')));
if (!ok) throw new Error('signature mismatch');
// Replay protection. Stripe's libraries default to a 5-minute tolerance.
if (toleranceSeconds > 0 && Math.abs(nowSeconds - parts.t) > toleranceSeconds) {
throw new Error('timestamp outside tolerance');
}
return true;
}
Three things earn their keep here:
- Constant-time comparison (
crypto.timingSafeEqual). A normal===on strings can leak, byte by byte, how much of a guess is correct via timing. Stripe’s docs call for a constant-time compare; use it. - The tolerance check rejects an old, replayed event. The Stripe docs are explicit: the libraries default to 5 minutes, and you should never use a tolerance of 0 — that disables the recency check entirely.
- Multiple
v1values are handled, because Stripe can send more than one during a signing-secret rotation.
The two rules the docs won’t let you skip
Verifying the signature proves the event is genuine. It does not make your handler safe on its own. Two more rules, straight from Stripe’s guidance:
1. Be idempotent
The same event can arrive more than once (retries, network hiccups). If “order paid” runs twice, you might grant two subscriptions or email the customer twice. Stripe’s fix: log the event id you’ve processed and skip anything you’ve already seen.
if (await alreadyProcessed(event.id)) return respond(200); // no-op on duplicates
await markProcessed(event.id);
// …do the work exactly once…
Make “mark processed” and “do the work” resilient to a crash in between — a unique constraint on event.id, or a transaction, both work.
2. Return 2xx fast, then do the heavy work
Stripe expects a quick 2xx. If your handler does slow work (charging an invoice in your accounting system, calling other APIs) before responding, it can time out — and Stripe will retry, compounding the duplicate problem. Acknowledge first, process after (inline if it’s fast, or on a queue if it isn’t).
In production, use the official library
You don’t have to hand-roll this. Stripe’s libraries expose a one-liner — stripe.webhooks.constructEvent(rawBody, signatureHeader, endpointSecret) — that does the parse, HMAC, constant-time compare, and tolerance check for you, and throws on failure. Prefer it. The from-scratch version above exists so you know what that one line is actually checking — and so you can spot when an AI-generated handler quietly skipped it.
Hand-verification like this is still useful when you’re in an environment without the SDK, debugging a mismatch, or writing tests.
Test it offline
The accompanying example signs a payload exactly the way Stripe does, then checks that the verifier accepts a valid event and rejects a tampered body, a forged secret, a replayed (old) timestamp, and a malformed header. Run it:
bash verify.sh # or: node verify-signature.test.mjs
Output:
All 6 webhook-verification checks passed.
No network, no keys — so you can wire this into CI and keep it green.
Limitations & failure cases
- This verifies authenticity and recency, not business rules. You still must confirm the event type you expect and that amounts/prices match what you set server-side — never trust amounts a client could influence.
- Raw-body capture is framework-specific (Express needs
express.raw, Next.js route handlers give youawait req.text()). Parse the JSON only after verifying. - A signing secret in your repo or logs defeats all of this. Keep it in an env var; never log it. This topic is security-sensitive — treat changes carefully.
- Handling refunds, disputes, and failed payments is beyond this guide; verification and idempotency are the prerequisites for handling any of them safely.
Next step
Signature verification and idempotency are two lines on the production checklist — and two of the most common gaps in AI-built payment flows. If money already flows through your app and you want an outside read on the whole money path (and the rest of the checklist), the AI-Built App Readiness Audit scores it and hands you a prioritised fix plan.