Stripe webhook security: signatures, replays, duplicates and rolled secrets
How Stripe signs the events it sends, what your handler has to check before it trusts one, and how to cope with stale, repeated and out-of-order deliveries.
With a fixture table, an endpoint register to fill in for your own account, and a local lab of invented test-mode events.
In this guide
Stripe webhook fixture table, endpoint register and local lab
Part A is a fixture table covering valid, repeated, stale, altered, wrongly signed, unsigned, re-serialised, out-of-order, retried and rolled-secret deliveries, each with what Stripe's documentation says and what the lab did. Part B is an endpoint register to copy once per endpoint, Part C plans a secret roll without performing it, and Part D is the local lab of invented test-mode events with its captured output.
How to use itHide the instructions
Part B reads settings, files and lists, Parts B and C record secrets by name only, and Part D sends requests only to 127.0.0.1 or localhost.
stripe-webhook-security.txt
Introduction16 lines
Part A: Fixture table69 lines
Part B: Endpoint register105 lines
Part C: Secret-roll plan13 lines
Part D: Local lab547 lines
Whole template774 lines
HOW TO USE THIS SHEET
Part A is the fixture table: one block per kind of delivery a handler has to cope with, giving what the fixture sends, what Stripe's documentation says, what the lab receiver in Part D did with it, and a line for your own copy. Part B is the endpoint register: copy it once for every webhook endpoint, in each sandbox and in live mode, and fill it from the screens and files each row names. Part C is the plan to have in writing before anyone rolls an endpoint secret. Part D is the lab itself.
Rules for every part:
1. Names, never values. Never write an endpoint secret, an API key or a real event payload into this sheet. Record which variable holds a secret, where it is set and whether it is present.
2. Do not press "Reveal secret", "Click to reveal", "Roll secret" or "Resend" to fill this sheet. Stripe's pages describe each of them: the first two show a secret, rolling changes the endpoint's signing secret, and Resend delivers an event to your handler again.
3. Part B reads settings, files and lists, and Part C is lines to fill in. The only requests in this sheet are Part A's six S fixtures and the lab's RUN 1, and the sender in Part D refuses any address other than 127.0.0.1 or localhost.
4. Before you send the S fixtures to your own code, read the limits at the top of Part A. They go only to a local copy of your handler, started with the lab's invented secret and sandbox API keys, never live keys.
"Source" names the page each line relies on. Stripe's pages were read on 15 November 2026 and WooCommerce's webhook page on 14 November 2026; where your integration uses an older library or a different event format, check the page again. "Lab" lines quote the captured output in Part D, which is an illustration and holds no code from Stripe's libraries.
What is here:
Part A Fixture table: blocks A1 to A11, matched to steps F1 to F13, R1 to R4 and S1 to S6 of the lab's RUN 1.
Part B Endpoint register: rows B1 to B12, one copy per endpoint.
Part C Secret-roll plan: what Stripe describes, then lines C1 to C6 to fill in.
Part D Lab: four files, two runs and their captured output.
================================================================
PART A: FIXTURE TABLE
================================================================
Each block has four lines under its heading. "Sends" is what the lab fixture sends. "Stripe says" is from the source named. "Lab" is copied from RUN 1 in Part D. "Your copy" is either a result from sending the S fixture to a local copy of your own handler, or, where no S fixture exists, what to read in your code.
Limits for the S fixtures: run node sender.mjs only against a copy of your handler running on your own computer at 127.0.0.1 or localhost, started with LAB_SECRET from fixtures.mjs as its endpoint secret and with sandbox API keys only. Stripe's sandboxes page says a sandbox is an isolated test environment for testing Stripe functionality without affecting your live integration. Its later steps must send nothing to customers: any email or text message it sends goes to an address or number you control. The sender sends six requests, one per fixture, one after another. The S fixtures use an invented event type, lab.fixture.signature_check, so a handler that acts only on the event types it lists should verify each one and do nothing more.
A1. A VALID EVENT
Sends: An invented checkout.session.completed event, signed with the endpoint secret at the moment of sending.
Stripe says: Set up the handler so that it verifies the request using the payload, the Stripe-Signature header and the whsec_ signing secret, and quickly returns a 2xx before any complex logic that might cause a timeout. Source: Receive Stripe events in your webhook endpoint.
Lab: F1 200, "order fulfilled for lab-checkout-session-1". S1 200, "event type not handled; acknowledged".
Your copy: S1 status and body, from a local copy of your handler started with LAB_SECRET and sandbox keys (limits above): ____________________
A2. THE SAME EVENT DELIVERED AGAIN
Sends: F1's event a second time, with a fresh timestamp and signature.
Stripe says: Endpoints might occasionally receive the same event more than once; log the event IDs you've processed and don't process already-logged events. In its section on processing undelivered events, Stripe says to verify the signature before checking whether you've already processed an event, and if you have, to skip it and return a 200 to stop further retries. Sources: Receive Stripe events; Manage webhook endpoints.
Lab: F2 200, "duplicate of an event already processed; not processed again".
Your copy: No S fixture. In your code, record where the ledger check sits relative to signature verification and what status a duplicate gets: ____________________
A3. A SECOND EVENT OBJECT FOR THE SAME CHECKOUT SESSION
Sends: A new event id, lab-evt-0002, announcing the Checkout Session F1 already announced.
Stripe says: In some cases two separate Event objects are generated and sent; to identify these duplicates, use the ID of the object in data.object along with the event type. Stripe's fulfilment guide says the fulfilment function might be called multiple times, possibly concurrently, for the same Checkout Session. Sources: Receive Stripe events; Stripe's fulfilment guide for Checkout.
Lab: F3 200, "Checkout Session already fulfilled; not fulfilled again".
Your copy: No S fixture. Record what your fulfilment step keys on (event id, object id and type, Checkout Session id): ____________________
A4. A STALE TIMESTAMP
Sends: A correctly signed event whose signed timestamp is 600 seconds behind the sender's clock.
Stripe says: The timestamp is part of the signed payload, so it can't be changed without invalidating the signature, and if the signature is valid but the timestamp is too old, you can have your application reject the payload. Stripe's libraries have a default tolerance of 5 minutes, and a tolerance of 0 disables the recency check entirely. Source: Receive Stripe events.
Lab: F4 400 and S2 400, "timestamp outside the 300-second tolerance".
Your copy: S2 status and body, from a local copy of your handler started with LAB_SECRET and sandbox keys (limits above): ____________________ Tolerance your code passes: ________ (or "library default")
A5. A BODY CHANGED AFTER SIGNING
Sends: An event signed as written, then sent with amount_total changed from 4900 to 1 (S3 changes an object id instead).
Stripe says: Verifying the signature confirms that the event wasn't sent or modified by a third party. Source: Receive Stripe events.
Lab: F5 400 and S3 400, "no v1 signature matches the payload".
Your copy: S3 status and body, from a local copy of your handler started with LAB_SECRET and sandbox keys (limits above): ____________________
A6. SIGNED WITH THE WRONG SECRET
Sends: An event signed with a secret the receiver does not hold.
Stripe says: The most common cause of a signature verification error is using the wrong endpoint secret, and the secret for a CLI-forwarded endpoint is different from the secret for a Dashboard-managed endpoint. If one endpoint is used with both test and live API keys, its secret is different for each. Sources: Manage webhook endpoints; Receive Stripe events.
Lab: F6 400 and S4 400, "no v1 signature matches the payload".
Your copy: S4 status and body, from a local copy of your handler started with LAB_SECRET and sandbox keys (limits above): ____________________
A7. NO STRIPE-SIGNATURE HEADER
Sends: An event with no Stripe-Signature header at all.
Stripe says: If the header doesn't contain t and at least one v1 entry, check how your code extracts the Stripe-Signature header value. Source: Manage webhook endpoints.
Lab: F7 400 and S5 400, "missing Stripe-Signature header".
Your copy: S5 status and body, from a local copy of your handler started with LAB_SECRET and sandbox keys (limits above): ____________________
A8. THE RAW BODY AND A PARSED BODY
Sends: One genuine, correctly signed event, first to a route that parses the JSON and verifies a re-serialised copy, then to a route that verifies the bytes it received.
Stripe says: Stripe requires the raw body of the request to perform signature verification, and any manipulation of it causes verification to fail. Some frameworks parse or mutate the body by reordering keys, stripping whitespace, converting to JSON or changing encoding. With stripe-node and Express, app.use(express.json()) must appear after the webhook route. Sources: Receive Stripe events; Manage webhook endpoints.
Lab: F8 400 on /stripe/webhook-parsed-first, "no v1 signature matches the payload". F9 200 on /stripe/webhook, "order fulfilled for lab-checkout-session-2".
Your copy: No S fixture, because S1 already shows whether your copy verifies a genuine event. Record how your webhook route reads the body (see B3): ____________________
A9. EVENTS OUT OF ORDER
Sends: Two customer.subscription.updated events for one invented subscription: the snapshot saying active first, then one saying past_due, standing for an earlier change that arrived late.
Stripe says: Stripe doesn't guarantee delivery in the order events are generated. Snapshot events record created in seconds, so distinct events can share a timestamp; don't use created to determine event order or whether you've already processed an event. You can use the API to retrieve any missing objects. Source: Receive Stripe events.
Lab: F10 200 and F11 200. Both outcomes read "subscription read from the lab object store: active", and F11 adds "(event snapshot said past_due)".
Your copy: No S fixture. For each event type your handler acts on, record whether it writes the snapshot's fields or reads the current object (see B7): ____________________
A10. A RETRY AFTER A FAILED DELIVERY
Sends: One invoice.paid event twice. On the first delivery the receiver's invented downstream step fails.
Stripe says: In live mode Stripe attempts delivery for up to three days with an exponential back off, and sandbox deliveries are retried three times over a few hours. A retried event gets a new signature and timestamp. Stripe also says to return a 2xx quickly before complex logic and to process events with an asynchronous queue. Source: Receive Stripe events.
Lab: F12 500, "invented downstream step unavailable". F13 200, "invoice marked paid", processed rather than answered as a duplicate, because the lab writes its ledger entry only after the business step succeeds. The lab processes each event before it answers, to stay short.
Your copy: No S fixture. Record when your ledger entry is written relative to the work, and what clears an entry marked as processing whose work failed: ____________________
A11. A ROLLED SECRET: THE OVERLAP AND THE EXPIRY
Sends: An event carrying a v1 signature for the lab secret and one for the next secret, then an event signed with the next secret only.
Stripe says: When you roll a secret and delay the old one's expiry, for up to 7 days, multiple secrets are active and Stripe generates one signature per secret until expiration. Verify that at least one v1 entry is valid. Source: Receive Stripe events.
Lab: R1 200 (receiver A, lab secret only) and R2 200 (receiver B, next secret only) for the overlap event. R3 400 on receiver A, "no v1 signature matches the payload", and R4 200 on receiver B for the next-secret-only event. S6 200.
Your copy: S6 status and body, from a local copy of your handler started with LAB_SECRET and sandbox keys (limits above): ____________________ Does your code try every v1 entry, or only the first? ________
================================================================
PART B: ENDPOINT REGISTER
================================================================
ENDPOINT HEADER (one per endpoint)
Stripe account or sandbox: ____________________ Live or sandbox: ________
Endpoint (path only, no secret, no query string with a token): ____________________
Handler: repository and file ____________________ Date checked: ____________
B1. ENDPOINT, PAYLOAD FORMAT AND EVENT TYPES
Check: Which events Stripe sends to this endpoint, and which of them the handler uses.
Where to look: The Webhooks tab in Workbench, which Stripe's page says lists your endpoints, and the handler's code. Do not press "Reveal secret" or "Click to reveal".
Source: Stripe, Receive Stripe events in your webhook endpoint; WooCommerce, Setting up webhooks.
Record: Payload format chosen when the destination was created: Thin or Snapshot. For Snapshot, the API version selected.
Each event type the endpoint is subscribed to, and each one the handler acts on.
Subscribed types the handler ignores. Stripe advises receiving only the event types your integration requires.
Endpoints in the list that nobody on the team recognises. For a WooCommerce store, WooCommerce's page says: "Note that our Stripe extension only uses webhook endpoints in the following format: https://www.example.com/?wc-api=wc_stripe", and "Any other endpoints you see in the Stripe dashboard likely come from other payment gateways or third-party services that integrate with Stripe."
B2. WHERE THE SIGNING SECRET IS SET (NAMES ONLY)
Check: Which secret each deployment verifies with, without displaying it.
Where to look: The names in your deployment's list of environment variables, read without opening or revealing any value, and the handler's code. Not the "Reveal secret" button.
Source: Stripe, Receive Stripe events; Stripe, Manage webhook endpoints.
Record: The variable name the handler reads (Stripe's example uses STRIPE_WEBHOOK_SECRET).
Each environment where it is set: present yes or no.
Whether the live and sandbox deployments read secrets from different places. Stripe's page says one endpoint used with both test and live API keys has a different secret for each.
Whether any deployed configuration was set from a secret printed by stripe listen: yes, no or unknown, judged from how it was set, never by comparing values.
Whether a secret appears in source code, a committed configuration file, a ticket or a log: present yes or no, never the value.
Note: Stripe's page on managing webhook endpoints suggests printing the endpointSecret value your code uses and comparing it. This sheet does not, because a printed secret can stay in terminal history or a log (this page's advice). Failed deliveries with a 400 in B8 can point to a mismatch without showing the secret.
B3. THE RAW BODY
Check: Whether the handler verifies the exact bytes Stripe sent.
Where to look: The webhook route, the middleware it passes through, and any proxy, gateway or serverless layer in front of it.
Source: Stripe, Receive Stripe events; Stripe, Manage webhook endpoints.
Record: Framework and version. How the route reads the body: raw bytes, a raw string, or an already parsed object.
For stripe-node with Express: whether express.json() is registered before the webhook route. Stripe's page says it must come after.
Any layer that rewrites or re-encodes the body before your code sees it.
B4. THE VERIFICATION CALL AND ITS TOLERANCE
Check: How the handler verifies, and what it does when verification fails.
Where to look: The handler's code.
Source: Stripe, Receive Stripe events; Stripe, Manage webhook endpoints.
Record: The call used: constructEvent() for snapshot events, parseEventNotification() for thin events, another official library call, or your own code.
The tolerance argument: its value, or "library default". A value of 0 is a finding, because Stripe says it disables the recency check.
For your own code, each of Stripe's steps: only t and v1 entries used; every v1 entry tried; v0 and the secret, destination and payload entries ignored; a constant-time comparison; the tolerance checked once a signature matches.
On failure: the status returned, and whether the handler stops before any business step.
B5. THE SERVER CLOCK
Check: Whether the machines that run the handler keep accurate time.
Where to look: The host's time synchronisation settings, or your hosting provider's documentation for a managed platform.
Source: Stripe, Receive Stripe events (Network Time Protocol).
Record: Time synchronisation configured: yes, no or unknown, and how you confirmed it.
B6. THE EVENT-ID LEDGER
Check: How the handler knows it has already processed an event.
Where to look: The handler's code and the table or store it writes to.
Source: Stripe, Receive Stripe events; Stripe, Manage webhook endpoints; Stripe's fulfilment guide for Checkout.
Record: Where processed event IDs are kept, and for how long.
Whether the check runs after signature verification, and the status a duplicate receives.
Whether the store refuses a second copy of the same event ID by itself, such as with a unique constraint. This is this page's advice. Stripe's fulfilment guide says the fulfilment function might be called multiple times, possibly concurrently, for the same Checkout Session. Two deliveries that both check before either writes can both pass (this page's reading).
When the entry is written: before the work, after it, or both as processing and processed.
What clears a processing mark whose work failed.
What fulfilment keys on for the separate Event objects Stripe describes: the data.object ID with the event type, or the Checkout Session ID.
B7. EVENT ORDER
Check: Whether any handler depends on events arriving in order.
Where to look: The code for each event type the handler acts on.
Source: Stripe, Receive Stripe events.
Record: Per event type: writes the snapshot's fields, or retrieves the current object from Stripe's API.
Any use of created to order events or to decide whether an event was processed. Stripe says not to use it for either.
B8. RESPONSE TIME AND DELIVERY HISTORY
Check: What Stripe records about deliveries to this endpoint.
Where to look: Open Workbench, select the endpoint under Webhooks, then select the "Event deliveries" tab. Clicking an event shows the HTTP status code of the delivery attempt. For the last line, the handler's code.
Source: Stripe, Receive Stripe events.
Record: The number of events shown as Failed and as Pending, and their status codes.
Any 3xx. Stripe considers redirect responses failures.
Any Timed out. Stripe's fix is to defer complex logic and return a successful response immediately.
Whether the handler answers before slow work, or hands events to a queue.
Note: Read only. Do not press "Resend" or "Reveal secret" for this sheet.
B9. RECOVERING MISSED EVENTS
Check: What happens after an outage longer than Stripe's retries.
Where to look: Your runbook and any recovery script.
Source: Stripe, Manage webhook endpoints.
Record: Whether a recovery script exists. Stripe's page describes listing events with delivery_success set to false and says Stripe only returns events created in the last 30 days.
Whether the script uses the same ledger as the handler. Stripe's page says a recovery script might run more than once and automatic retries might deliver some events while it runs.
B10. HTTPS, IP ADDRESSES AND CSRF
Check: What stands in front of the route besides the signature.
Where to look: The endpoint URL; the web server, load balancer or firewall rules for the route; the framework's CSRF settings.
Source: Stripe, Receive Stripe events; Stripe, Domains and IP addresses.
Record: HTTPS: yes or no. Stripe's page says HTTPS is required in live mode and that its webhooks support only TLS v1.2 and v1.3.
A rule that accepts webhook requests only from Stripe's webhook IP addresses: yes or no, where it is set, and who updates it. Stripe's IP addresses page says Stripe provides seven days' notice through its API announce mailing list before changing them.
CSRF: whether the exemption covers only the webhook route. Stripe says you might need to exempt the webhooks route, and its Rails example exempts the webhook action alone.
B11. WHO CAN CHANGE ENDPOINTS
Check: Which keys can create or change webhook destinations.
Where to look: The restricted keys in your Stripe account and the permissions each holds: names and permissions only, with every key value left hidden.
Source: Stripe, Manage webhook endpoints.
Record: Each restricted key that holds "Webhook Endpoints, Event Destinations: Write", by name only, and the integration that needs it.
Note: Stripe's page says this permission can create or change destinations that subscribe to any event available on the account, and allows read access to any event notification payload and Event object. It recommends configuring destinations in the Dashboard where possible and, where an integration needs the permission, a dedicated restricted key protected as an administrative credential.
B12. WHAT THE HANDLER LOGS
Check: Whether logs explain each delivery without holding a secret.
Where to look: The handler's log statements and a sample of its log output from a sandbox.
Source: Stripe, The Event object; Stripe, Receive Stripe events.
Record: Whether each log line carries the event ID, the type, livemode (true for live mode, false for test mode, per the Event object reference), the verification result and the status returned.
Whether any log line holds the endpoint secret, an API key or the whole Stripe-Signature header: present yes or no, never the value.
Note: Stripe says the header's optional secret entry is a redacted representation of the endpoint's newest active signing secret. Logging only the result of verification avoids the question (this page's advice).
================================================================
PART C: SECRET-ROLL PLAN
================================================================
WHAT STRIPE DESCRIBES (Receive Stripe events in your webhook endpoint, read 15 November 2026)
- The secret used for verifying that events come from Stripe is modifiable in the Webhooks tab in Workbench. Stripe recommends rolling it periodically, or when you suspect a compromised secret.
- To roll it, you click the endpoint in the Workbench Webhooks tab, open the overflow menu and click "Roll secret".
- You can expire the current secret immediately, or delay its expiration for up to 7 days to allow time to update the verification code on your server. During that time multiple secrets are active for the endpoint, and Stripe generates one signature per secret until expiration.
Rolling a secret changes the endpoint's signing secret, so this sheet does not ask you to do it. Fill in the lines below first, and keep them with the endpoint register.
C1. Endpoint and environment to be rolled: ____________________
C2. Every deployment that verifies this endpoint, and the variable each reads (from B2): ____________________
C3. How the new value will reach each deployment without passing through chat, email or a ticket (this page's advice): ____________________
C4. Expiry of the old secret: immediately / delayed by ________ (Stripe allows up to 7 days). In the lab, receiver A still held the old secret when only the next secret signed (R3), and it refused a genuine event with 400.
C5. Who reads the "Event deliveries" tab after the switch, and when: ____________________
C6. If the roll follows a suspected leak: who decides between immediate expiry and a delay, and where the decision is recorded. A delay keeps the old secret valid for the period chosen (this page's reading of Stripe's description). ____________________
================================================================
PART D: LOCAL LAB
================================================================
ILLUSTRATION ONLY. The receivers below are invented for this page. They are not Stripe and hold no code from Stripe's libraries; they check the Stripe-Signature header the way Stripe's documentation describes the scheme. Their status codes and messages are their own. The endpoint secrets are invented and deliberately not in the format of a real Stripe secret, and every event is an invented test-mode event with livemode set to false. Amounts are integers in cents, the smallest currency unit. Nothing is sent to Stripe.
What it is: four files. Besides one another, they import node:http and node:crypto and nothing else, and nothing needs installing. Each receiver asks for port 0 on 127.0.0.1, so the operating system picks the port (Node.js net documentation), and keeps everything in memory.
Receiver A holds LAB_SECRET, the lab's current endpoint secret.
Receiver B holds only LAB_NEXT_SECRET, as a handler would once its configuration moved to a rolled secret.
/stripe/webhook verifies the raw bytes it received
/stripe/webhook-parsed-first parses the JSON first and verifies a re-serialised copy: the mistake A8 describes
The lab's tolerance is 300 seconds, and it also refuses a timestamp more than 300 seconds ahead of its clock. Both are this lab's choices. Its subscription handler reads the current state from LAB_CURRENT_OBJECTS, an in-memory stand-in for retrieving the object from Stripe's API, and its ledger entry is written only after the business step succeeds.
The sender signs each fixture at the moment of sending and refuses any host other than 127.0.0.1 and localhost.
Node.js version: v26.0.0. The lab has been run on no other version, and a script pasted each output below from the captured files.
To run it, save the four files under the names shown in a new, empty folder, then run node run-lab.mjs from a terminal opened in that folder. To send the six S fixtures to a local copy of your own handler, read the limits at the top of Part A first, then run node sender.mjs followed by your copy's local URL.
================================================================
FILE 1 OF 4: fixtures.mjs
================================================================
// fixtures.mjs: the invented values the sender and the receiver share.
// Nothing here is a real Stripe value. The three endpoint secrets are
// made-up strings, deliberately not in the format of a real Stripe secret,
// and every event is an invented test-mode event (livemode is false).
// Never put a real endpoint secret or a real customer's event in this file.
export const SIGNATURE_HEADER = 'stripe-signature'
// The lab's tolerance between the signed timestamp and the receiver's clock,
// in seconds.
export const TOLERANCE_SECONDS = 300
export const LAB_SECRET = 'invented-endpoint-secret-for-this-lab-only'
export const LAB_NEXT_SECRET = 'invented-next-endpoint-secret-for-this-lab'
export const WRONG_SECRET = 'a-guess-that-is-not-the-endpoint-secret'
export function nowInSeconds() {
return Math.floor(Date.now() / 1000)
}
// Builds one invented event. Amounts are invented integers in cents, the
// smallest unit of the currency.
export function buildEvent(id, type, dataObject) {
return {
id: id,
object: 'event',
type: type,
created: nowInSeconds(),
livemode: false,
data: { object: dataObject },
}
}
const SESSION_ONE = { id: 'lab-checkout-session-1', object: 'checkout.session', amount_total: 4900, currency: 'aud', payment_status: 'paid' }
const SESSION_TWO = { id: 'lab-checkout-session-2', object: 'checkout.session', amount_total: 2500, currency: 'aud', payment_status: 'paid' }
const SESSION_THREE = { id: 'lab-checkout-session-3', object: 'checkout.session', amount_total: 4900, currency: 'aud', payment_status: 'paid' }
export const EVENTS = {
sessionOnePaid: buildEvent('lab-evt-0001', 'checkout.session.completed', SESSION_ONE),
sessionOnePaidAgain: buildEvent('lab-evt-0002', 'checkout.session.completed', SESSION_ONE),
sessionThreePaid: buildEvent('lab-evt-0003', 'checkout.session.completed', SESSION_THREE),
sessionTwoPaid: buildEvent('lab-evt-0004', 'checkout.session.completed', SESSION_TWO),
subscriptionPastDue: buildEvent('lab-evt-0005', 'customer.subscription.updated', { id: 'lab-subscription-1', object: 'subscription', status: 'past_due' }),
subscriptionActive: buildEvent('lab-evt-0006', 'customer.subscription.updated', { id: 'lab-subscription-1', object: 'subscription', status: 'active' }),
invoicePaid: buildEvent('lab-evt-0007', 'invoice.paid', { id: 'lab-invoice-1', object: 'invoice', amount_paid: 4900, currency: 'aud' }),
duringRoll: buildEvent('lab-evt-0008', 'invoice.paid', { id: 'lab-invoice-2', object: 'invoice', amount_paid: 2500, currency: 'aud' }),
afterRoll: buildEvent('lab-evt-0009', 'invoice.paid', { id: 'lab-invoice-3', object: 'invoice', amount_paid: 2500, currency: 'aud' }),
}
// Stands in for retrieving the current object from Stripe's API. The lab
// makes no network call; this is an invented, in-memory copy.
export const LAB_CURRENT_OBJECTS = {
'lab-subscription-1': { id: 'lab-subscription-1', object: 'subscription', status: 'active' },
}
================================================================
FILE 2 OF 4: receiver.mjs
================================================================
// receiver.mjs: an invented webhook endpoint written for this page. It is not
// Stripe's code and holds no code from Stripe's libraries. It checks the
// Stripe-Signature header the way Stripe's documentation describes the
// scheme, then keeps an event-id ledger and invented orders, subscriptions
// and invoices in memory.
// It listens on 127.0.0.1 only, on a port the operating system picks.
//
// POST /stripe/webhook verifies the raw bytes it received
// POST /stripe/webhook-parsed-first the mistake: parses the JSON first and
// verifies a re-serialised copy
import http from 'node:http'
import crypto from 'node:crypto'
import { SIGNATURE_HEADER, TOLERANCE_SECONDS, LAB_CURRENT_OBJECTS, nowInSeconds } from './fixtures.mjs'
// Splits "t=...,v1=...,v1=..." into the timestamp and every v1 signature.
// Any other scheme in the header is ignored.
function parseSignatureHeader(header) {
const parsed = { timestamp: undefined, signatures: [] }
for (const part of header.split(',')) {
const separator = part.indexOf('=')
if (separator === -1) continue
const key = part.slice(0, separator).trim()
const value = part.slice(separator + 1).trim()
if (key === 't') parsed.timestamp = Number(value)
if (key === 'v1') parsed.signatures.push(value)
}
return parsed
}
// HMAC-SHA256 of the timestamp, a full stop and the payload bytes.
function computeSignature(timestamp, payloadBytes, secret) {
const hmac = crypto.createHmac('sha256', secret)
hmac.update(String(timestamp) + '.')
hmac.update(payloadBytes)
return hmac.digest('hex')
}
// Constant-time comparison of two hex strings. timingSafeEqual needs two
// buffers of the same length, so a length mismatch is a plain false.
function isSameSignature(receivedHex, expectedHex) {
const received = Buffer.from(receivedHex, 'hex')
const expected = Buffer.from(expectedHex, 'hex')
if (received.length !== expected.length) return false
return crypto.timingSafeEqual(received, expected)
}
function hasMatchingSignature(parsed, payloadBytes, secrets) {
for (const secret of secrets) {
const expected = computeSignature(parsed.timestamp, payloadBytes, secret)
for (const signature of parsed.signatures) {
if (isSameSignature(signature, expected)) return true
}
}
return false
}
// Returns undefined when the header, signature and timestamp all pass, or
// the reason the request is refused.
function findVerificationProblem(header, payloadBytes, secrets) {
if (header === undefined) return 'missing Stripe-Signature header'
const parsed = parseSignatureHeader(header)
if (!Number.isInteger(parsed.timestamp) || parsed.signatures.length === 0) return 'header has no timestamp or no v1 signature'
if (!hasMatchingSignature(parsed, payloadBytes, secrets)) return 'no v1 signature matches the payload'
// Checked only once a signature matches. The lab also refuses a timestamp
// more than the tolerance ahead of its clock.
const ageInSeconds = nowInSeconds() - parsed.timestamp
if (Math.abs(ageInSeconds) > TOLERANCE_SECONDS) return 'timestamp outside the ' + TOLERANCE_SECONDS + '-second tolerance'
return undefined
}
function sendJson(response, status, payload) {
response.writeHead(status, { 'content-type': 'application/json' })
response.end(JSON.stringify(payload))
}
// The invented business state the events change.
function createState() {
return { ledger: new Map(), fulfilledSessions: [], subscriptions: new Map(), paidInvoices: [], failuresLeft: new Map() }
}
// Fulfils once per Checkout Session, whichever event announces it.
function fulfilSession(state, session) {
if (state.fulfilledSessions.includes(session.id)) return 'Checkout Session already fulfilled; not fulfilled again'
state.fulfilledSessions.push(session.id)
return 'order fulfilled for ' + session.id
}
// Ignores the snapshot's place in the delivery order and reads the current
// object instead, from the in-memory stand-in for Stripe's API.
function refreshSubscription(state, event) {
const snapshot = event.data.object
const current = LAB_CURRENT_OBJECTS[snapshot.id]
state.subscriptions.set(current.id, current.status)
return 'subscription read from the lab object store: ' + current.status + ' (event snapshot said ' + snapshot.status + ')'
}
// Runs the business step for one event. Throws when the invented downstream
// step is set to fail, so the event is not marked as processed.
function processEvent(state, event) {
const failuresLeft = state.failuresLeft.get(event.id) || 0
if (failuresLeft > 0) {
state.failuresLeft.set(event.id, failuresLeft - 1)
throw new Error('invented downstream step unavailable')
}
if (event.type === 'checkout.session.completed') return fulfilSession(state, event.data.object)
if (event.type === 'customer.subscription.updated') return refreshSubscription(state, event)
if (event.type === 'invoice.paid') {
state.paidInvoices.push(event.data.object.id)
return 'invoice marked paid'
}
return 'event type not handled; acknowledged'
}
function handleEvent(state, response, event) {
if (state.ledger.has(event.id)) return sendJson(response, 200, { received: true, outcome: 'duplicate of an event already processed; not processed again' })
let outcome
try {
outcome = processEvent(state, event)
} catch (error) {
return sendJson(response, 500, { received: false, reason: error.message })
}
// The ledger entry is written only after the business step succeeds.
state.ledger.set(event.id, { type: event.type, outcome: outcome })
sendJson(response, 200, { received: true, outcome: outcome })
}
function payloadToVerify(path, rawBytes) {
if (path === '/stripe/webhook') return rawBytes
// The mistake: a body parser turned the bytes into an object, and the
// handler verifies a fresh serialisation of that object instead.
return Buffer.from(JSON.stringify(JSON.parse(rawBytes.toString('utf8'))), 'utf8')
}
function handleRequest(state, secrets, request, response, rawBytes) {
const isKnownPath = request.url === '/stripe/webhook' || request.url === '/stripe/webhook-parsed-first'
if (!isKnownPath) return sendJson(response, 404, { received: false, reason: 'no such endpoint' })
if (request.method !== 'POST') return sendJson(response, 405, { received: false, reason: 'only POST is accepted' })
const problem = findVerificationProblem(request.headers[SIGNATURE_HEADER], payloadToVerify(request.url, rawBytes), secrets)
if (problem !== undefined) return sendJson(response, 400, { received: false, reason: problem })
handleEvent(state, response, JSON.parse(rawBytes.toString('utf8')))
}
// options.secrets: the endpoint secrets this receiver accepts.
// options.failOnceFor: event ids whose business step fails on first delivery.
export function startReceiver(options) {
const state = createState()
for (const eventId of options.failOnceFor || []) state.failuresLeft.set(eventId, 1)
const server = http.createServer((request, response) => {
const chunks = []
request.on('data', (chunk) => chunks.push(chunk))
request.on('end', () => handleRequest(state, options.secrets, request, response, Buffer.concat(chunks)))
})
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => {
resolve({
baseUrl: 'http://127.0.0.1:' + server.address().port,
state: state,
stop: () => new Promise((done) => server.close(done)),
})
})
})
}
================================================================
FILE 3 OF 4: sender.mjs
================================================================
// sender.mjs: signs invented events and sends each one, once, to a webhook
// endpoint on this computer. It refuses any address other than 127.0.0.1 or
// localhost, so it sends nothing to Stripe or to any other host.
//
// Used two ways:
// by run-lab.mjs, against the invented receiver in receiver.mjs
// on its own: node sender.mjs <your local endpoint URL on 127.0.0.1 or localhost>
// which sends the six signature fixtures in SIGNATURE_FIXTURES,
// one request each, and prints each status and response body.
import http from 'node:http'
import crypto from 'node:crypto'
import {
SIGNATURE_HEADER,
LAB_SECRET,
LAB_NEXT_SECRET,
WRONG_SECRET,
buildEvent,
nowInSeconds,
} from './fixtures.mjs'
const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost']
// Each event is written with two-space indentation, and these exact bytes
// are what gets signed and sent.
export function serialise(event) {
return JSON.stringify(event, null, 2)
}
function computeSignature(timestamp, payloadText, secret) {
return crypto.createHmac('sha256', secret).update(String(timestamp) + '.' + payloadText).digest('hex')
}
// One v1 signature per secret, all over the same timestamp and payload.
export function buildSignatureHeader(payloadText, secrets, timestamp) {
const parts = ['t=' + timestamp]
for (const secret of secrets) parts.push('v1=' + computeSignature(timestamp, payloadText, secret))
return parts.join(',')
}
// A fixture is { name, body, signedBody, secrets, secondsAgo }.
// signedBody is what the signature covers; body is what is sent. They differ
// only in the altered-body fixture. secrets is empty when no header is sent.
export function makeFixture(name, event, options) {
const body = serialise(event)
return {
name: name,
body: options.changeAfterSigning ? body.replace(options.changeAfterSigning.from, options.changeAfterSigning.to) : body,
signedBody: body,
secrets: options.secrets,
secondsAgo: options.secondsAgo || 0,
}
}
function assertLoopback(url) {
const hostname = new URL(url).hostname
if (!LOOPBACK_HOSTS.includes(hostname)) {
throw new Error('Refusing ' + hostname + ': the sender only talks to 127.0.0.1 or localhost.')
}
}
// The timestamp and signature are made at the moment of sending, so a
// repeated fixture carries a fresh timestamp and a fresh signature.
export function sendFixture(url, fixture) {
assertLoopback(url)
const headers = { 'content-type': 'application/json' }
if (fixture.secrets.length > 0) {
headers[SIGNATURE_HEADER] = buildSignatureHeader(fixture.signedBody, fixture.secrets, nowInSeconds() - fixture.secondsAgo)
}
return new Promise((resolve, reject) => {
const request = http.request(url, { method: 'POST', headers: headers }, (response) => {
const chunks = []
response.on('data', (chunk) => chunks.push(chunk))
response.on('end', () => resolve({ status: response.statusCode, body: Buffer.concat(chunks).toString('utf8') }))
})
request.on('error', reject)
request.end(fixture.body)
})
}
// The six fixtures for a local copy of your own handler, started with
// LAB_SECRET as its endpoint secret. The event type is invented, so a handler
// that acts only on the event types it lists should verify the signature and
// then do nothing more with the event.
function signatureCheckEvent(number) {
return buildEvent('lab-evt-010' + number, 'lab.fixture.signature_check', { id: 'lab-object-1', object: 'lab_fixture' })
}
export const SIGNATURE_FIXTURES = [
makeFixture('signed now with the lab secret', signatureCheckEvent(1), { secrets: [LAB_SECRET] }),
makeFixture('signed 600 seconds ago', signatureCheckEvent(2), { secrets: [LAB_SECRET], secondsAgo: 600 }),
makeFixture('body changed after signing', signatureCheckEvent(3), { secrets: [LAB_SECRET], changeAfterSigning: { from: 'lab-object-1', to: 'lab-object-2' } }),
makeFixture('signed with a wrong secret', signatureCheckEvent(4), { secrets: [WRONG_SECRET] }),
makeFixture('no Stripe-Signature header', signatureCheckEvent(5), { secrets: [] }),
makeFixture('two v1 signatures, lab and next', signatureCheckEvent(6), { secrets: [LAB_SECRET, LAB_NEXT_SECRET] }),
]
async function sendFromCommandLine() {
const url = process.argv[2]
if (url === undefined) throw new Error('Usage: node sender.mjs <your local endpoint URL on 127.0.0.1 or localhost>')
assertLoopback(url)
for (const fixture of SIGNATURE_FIXTURES) {
const result = await sendFixture(url, fixture)
console.log(fixture.name.padEnd(34) + ' ' + result.status + ' ' + result.body)
}
}
if (process.argv[1] && process.argv[1].endsWith('sender.mjs')) {
sendFromCommandLine().catch((error) => {
console.error(error.message)
process.exitCode = 1
})
}
================================================================
FILE 4 OF 4: run-lab.mjs
================================================================
// run-lab.mjs: starts two invented receivers on 127.0.0.1, sends each step
// of the plan below once, prints every response, both ledgers and receiver
// A's final state, then stops both receivers. Run it with: node run-lab.mjs
import { startReceiver } from './receiver.mjs'
import { makeFixture, sendFixture, SIGNATURE_FIXTURES } from './sender.mjs'
import { EVENTS, LAB_SECRET, LAB_NEXT_SECRET, WRONG_SECRET } from './fixtures.mjs'
const RAW = '/stripe/webhook'
const PARSED_FIRST = '/stripe/webhook-parsed-first'
const SIGNED_NOW = { secrets: [LAB_SECRET] }
const OVERLAP = { secrets: [LAB_SECRET, LAB_NEXT_SECRET] }
const NEXT_ONLY = { secrets: [LAB_NEXT_SECRET] }
function step(label, receiver, path, name, event, options) {
return { label: label, receiver: receiver, path: path, fixture: makeFixture(name, event, options) }
}
// Receiver A is configured with the lab secret. Receiver B is configured with
// only the next secret, as an endpoint's handler would be once its
// configuration moved to the rolled secret. R1 to R4 stand for deliveries
// while both secrets are active, and after the old one has expired.
function buildPlan() {
return [
step('F1', 'A', RAW, 'valid event', EVENTS.sessionOnePaid, SIGNED_NOW),
step('F2', 'A', RAW, 'F1 delivered again, freshly signed', EVENTS.sessionOnePaid, SIGNED_NOW),
step('F3', 'A', RAW, 'new event id, same Checkout Session', EVENTS.sessionOnePaidAgain, SIGNED_NOW),
step('F4', 'A', RAW, 'stale: signed 600 seconds ago', EVENTS.sessionThreePaid, { secrets: [LAB_SECRET], secondsAgo: 600 }),
step('F5', 'A', RAW, 'altered: amount changed after signing', EVENTS.sessionThreePaid, { secrets: [LAB_SECRET], changeAfterSigning: { from: '"amount_total": 4900', to: '"amount_total": 1' } }),
step('F6', 'A', RAW, 'signed with a wrong secret', EVENTS.sessionThreePaid, { secrets: [WRONG_SECRET] }),
step('F7', 'A', RAW, 'no Stripe-Signature header', EVENTS.sessionThreePaid, { secrets: [] }),
step('F8', 'A', PARSED_FIRST, 'valid event, parsed before verifying', EVENTS.sessionTwoPaid, SIGNED_NOW),
step('F9', 'A', RAW, 'same event, raw bytes verified', EVENTS.sessionTwoPaid, SIGNED_NOW),
step('F10', 'A', RAW, 'out of order: active snapshot first', EVENTS.subscriptionActive, SIGNED_NOW),
step('F11', 'A', RAW, 'out of order: past_due snapshot second', EVENTS.subscriptionPastDue, SIGNED_NOW),
step('F12', 'A', RAW, 'retry: first delivery, step fails', EVENTS.invoicePaid, SIGNED_NOW),
step('F13', 'A', RAW, 'retry: second delivery', EVENTS.invoicePaid, SIGNED_NOW),
step('R1', 'A', RAW, 'roll: v1 for both secrets', EVENTS.duringRoll, OVERLAP),
step('R2', 'B', RAW, 'roll: v1 for both secrets', EVENTS.duringRoll, OVERLAP),
step('R3', 'A', RAW, 'roll: old secret expired, next only', EVENTS.afterRoll, NEXT_ONLY),
step('R4', 'B', RAW, 'roll: old secret expired, next only', EVENTS.afterRoll, NEXT_ONLY),
]
}
// The six fixtures sender.mjs sends on its own, sent here to receiver A so
// there is a result to compare a local copy of your own handler with.
function buildSignaturePlan() {
return SIGNATURE_FIXTURES.map((fixture, index) => ({ label: 'S' + (index + 1), receiver: 'A', path: RAW, fixture: fixture }))
}
function printLedger(name, state) {
console.log('Receiver ' + name + ' ledger (event id, type, outcome):')
for (const entry of state.ledger.entries()) {
console.log(' ' + entry[0].padEnd(14) + entry[1].type.padEnd(31) + entry[1].outcome)
}
}
function printState(state) {
console.log('Receiver A Checkout Sessions fulfilled: ' + state.fulfilledSessions.join(', '))
for (const entry of state.subscriptions.entries()) console.log('Receiver A ' + entry[0] + ' status: ' + entry[1])
console.log('Receiver A invoices marked paid: ' + state.paidInvoices.join(', '))
}
async function runLab() {
console.log('Node.js ' + process.version)
const receivers = {
A: await startReceiver({ secrets: [LAB_SECRET], failOnceFor: [EVENTS.invoicePaid.id] }),
B: await startReceiver({ secrets: [LAB_NEXT_SECRET] }),
}
console.log('Receivers A and B listening on 127.0.0.1, on ports the operating system picked')
console.log('')
const plan = buildPlan().concat(buildSignaturePlan())
for (const item of plan) {
const result = await sendFixture(receivers[item.receiver].baseUrl + item.path, item.fixture)
console.log(item.label.padEnd(4) + item.receiver + ' ' + item.path.padEnd(30) + item.fixture.name.padEnd(39) + result.status)
console.log(' response: ' + result.body)
}
console.log('')
printLedger('A', receivers.A.state)
printLedger('B', receivers.B.state)
console.log('')
printState(receivers.A.state)
await receivers.A.stop()
await receivers.B.stop()
console.log('')
console.log('Receivers stopped. Requests sent: ' + plan.length + '.')
}
runLab().catch((error) => {
console.error(error.message)
process.exitCode = 1
})
================================================================
RUN 1: node run-lab.mjs
================================================================
Node.js v26.0.0
Receivers A and B listening on 127.0.0.1, on ports the operating system picked
F1 A /stripe/webhook valid event 200
response: {"received":true,"outcome":"order fulfilled for lab-checkout-session-1"}
F2 A /stripe/webhook F1 delivered again, freshly signed 200
response: {"received":true,"outcome":"duplicate of an event already processed; not processed again"}
F3 A /stripe/webhook new event id, same Checkout Session 200
response: {"received":true,"outcome":"Checkout Session already fulfilled; not fulfilled again"}
F4 A /stripe/webhook stale: signed 600 seconds ago 400
response: {"received":false,"reason":"timestamp outside the 300-second tolerance"}
F5 A /stripe/webhook altered: amount changed after signing 400
response: {"received":false,"reason":"no v1 signature matches the payload"}
F6 A /stripe/webhook signed with a wrong secret 400
response: {"received":false,"reason":"no v1 signature matches the payload"}
F7 A /stripe/webhook no Stripe-Signature header 400
response: {"received":false,"reason":"missing Stripe-Signature header"}
F8 A /stripe/webhook-parsed-first valid event, parsed before verifying 400
response: {"received":false,"reason":"no v1 signature matches the payload"}
F9 A /stripe/webhook same event, raw bytes verified 200
response: {"received":true,"outcome":"order fulfilled for lab-checkout-session-2"}
F10 A /stripe/webhook out of order: active snapshot first 200
response: {"received":true,"outcome":"subscription read from the lab object store: active (event snapshot said active)"}
F11 A /stripe/webhook out of order: past_due snapshot second 200
response: {"received":true,"outcome":"subscription read from the lab object store: active (event snapshot said past_due)"}
F12 A /stripe/webhook retry: first delivery, step fails 500
response: {"received":false,"reason":"invented downstream step unavailable"}
F13 A /stripe/webhook retry: second delivery 200
response: {"received":true,"outcome":"invoice marked paid"}
R1 A /stripe/webhook roll: v1 for both secrets 200
response: {"received":true,"outcome":"invoice marked paid"}
R2 B /stripe/webhook roll: v1 for both secrets 200
response: {"received":true,"outcome":"invoice marked paid"}
R3 A /stripe/webhook roll: old secret expired, next only 400
response: {"received":false,"reason":"no v1 signature matches the payload"}
R4 B /stripe/webhook roll: old secret expired, next only 200
response: {"received":true,"outcome":"invoice marked paid"}
S1 A /stripe/webhook signed now with the lab secret 200
response: {"received":true,"outcome":"event type not handled; acknowledged"}
S2 A /stripe/webhook signed 600 seconds ago 400
response: {"received":false,"reason":"timestamp outside the 300-second tolerance"}
S3 A /stripe/webhook body changed after signing 400
response: {"received":false,"reason":"no v1 signature matches the payload"}
S4 A /stripe/webhook signed with a wrong secret 400
response: {"received":false,"reason":"no v1 signature matches the payload"}
S5 A /stripe/webhook no Stripe-Signature header 400
response: {"received":false,"reason":"missing Stripe-Signature header"}
S6 A /stripe/webhook two v1 signatures, lab and next 200
response: {"received":true,"outcome":"event type not handled; acknowledged"}
Receiver A ledger (event id, type, outcome):
lab-evt-0001 checkout.session.completed order fulfilled for lab-checkout-session-1
lab-evt-0002 checkout.session.completed Checkout Session already fulfilled; not fulfilled again
lab-evt-0004 checkout.session.completed order fulfilled for lab-checkout-session-2
lab-evt-0006 customer.subscription.updated subscription read from the lab object store: active (event snapshot said active)
lab-evt-0005 customer.subscription.updated subscription read from the lab object store: active (event snapshot said past_due)
lab-evt-0007 invoice.paid invoice marked paid
lab-evt-0008 invoice.paid invoice marked paid
lab-evt-0101 lab.fixture.signature_check event type not handled; acknowledged
lab-evt-0106 lab.fixture.signature_check event type not handled; acknowledged
Receiver B ledger (event id, type, outcome):
lab-evt-0008 invoice.paid invoice marked paid
lab-evt-0009 invoice.paid invoice marked paid
Receiver A Checkout Sessions fulfilled: lab-checkout-session-1, lab-checkout-session-2
Receiver A lab-subscription-1 status: active
Receiver A invoices marked paid: lab-invoice-1, lab-invoice-2
Receivers stopped. Requests sent: 23.
(exit code 0)
================================================================
RUN 2: node sender.mjs http://203.0.113.10/stripe/webhook
================================================================
Refusing 203.0.113.10: the sender only talks to 127.0.0.1 or localhost.
(exit code 1)
Reading the output:
- F1 to F3: the valid event was processed once. Its second delivery was answered 200 as a duplicate, and a new event id for the same Checkout Session was answered 200 without a second fulfilment.
- F4 to F7: a stale timestamp, a changed body, a wrong secret and a missing header were each refused with 400 before any business step ran.
- F8 and F9: the same genuine event was refused by the route that verified a re-serialised copy and accepted by the route that verified the raw bytes.
- F10 and F11: the past_due snapshot, standing for an earlier change, arrived last, and the subscription stayed active because the receiver read the current object instead of the snapshot.
- F12 and F13: the failed first delivery returned 500 and wrote no ledger entry, so the second delivery was processed.
- R1 to R4: while both secrets signed, both receivers accepted. Once only the next secret signed, receiver A, still on the old secret, refused with 400 and receiver B accepted.
- S1 to S6: the six fixtures sender.mjs sends on its own, as receiver A answered them. Compare a local copy of your handler with these lines.
- RUN 2: the sender refused 203.0.113.10 before sending anything, because it is not 127.0.0.1 or localhost.What a Stripe webhook endpoint is, and who can reach it
Stripe's documentation describes a webhook endpoint as a URL you register so that Stripe pushes real-time data to it when events happen in your Stripe account, and says it uses HTTPS to send webhook events to your app as a JSON payload.
Stripe gives examples of what this is for: responding when a customer's bank confirms a payment, when a customer disputes a charge, or when a recurring payment succeeds.
Stripe also says registered webhook endpoints must be publicly accessible HTTPS URLs. On this page's reading, that makes the route reachable by anyone who learns its address, not only by Stripe. Stripe's own warning is that, without verification, an attacker could send fake webhook events to your endpoint to trigger actions like fulfilling orders, granting account access, or modifying records.
For a Stripe Checkout integration, Stripe's fulfilment guide says webhooks are required for fulfilment: triggering it only from the checkout landing page is not enough, because customers are not guaranteed to visit that page. Stripe says you must use webhooks to make sure fulfilment happens for every payment, so the webhook handler is the code that triggers it.
This guide covers that handler: how it proves an event came from Stripe, refuses a stale one, acts on each event once, copes with events in any order and survives a rolled secret.
The API security guide covers the rest of an application's API, and the plugin library's page on the WooCommerce Stripe gateway covers where that plugin's webhook status is read.
What Stripe does, and what stays with your handler
What Stripe's documentation says Stripe itself does: it signs every webhook event by putting a signature in the Stripe-Signature header, generates a unique secret for each endpoint, generates a new timestamp and signature for each delivery attempt, retries deliveries that fail, and sends webhook events from a set list of IP addresses.
Stripe's pages on receiving events and on managing webhook endpoints give the integration a list of its own. Verify that events come from Stripe before acting on them. Pass the raw request body to verification untouched. Guard against duplicate receipts by logging the event IDs you have processed and not processing those already logged.
Make sure your destination does not depend on receiving events in a specific order. Return a 2xx quickly, before any complex logic that might cause a timeout. On this page's reading, each of those is code you write, deploy and keep running.
The endpoint register in this page's asset has a row for each item on that list, and each of its rows reads something on your side: a setting in your Stripe account, your deployment or your hosting, or part of your own code or runbook.
Stripe webhook signature verification: what is signed, and how to check it
The Stripe-Signature header holds comma-separated entries, including a timestamp and one or more signatures.
The t entry is the time Stripe signed the event, in seconds since the Unix epoch, and Stripe notes that it does not represent when the event itself was generated. Each v1 entry is an HMAC with SHA-256 that incorporates the event payload, the timestamp and the endpoint's signing secret, and a header can carry more than one.
Stripe's page, read on 15 November 2026, says the only valid live signature scheme is v1. For sandbox events it adds a signature with a fake v0 scheme, which is not valid for verification and which your code must ignore.
Stripe recommends its official libraries for the check: you pass the event payload, the Stripe-Signature header and the endpoint's secret, and a failed verification gives an error. Its page on managing webhook endpoints names the calls, constructEvent() for snapshot events and parseEventNotification() for thin events, and says each takes the raw request body, the header value and the endpoint secret.
For code that verifies without the libraries, Stripe sets out these steps. First, split the header on commas and each element on the equals sign, and keep the t value and every v1 value. Second, build the signed_payload string from the timestamp as a string, the character . and the unmodified request body.
Third, compute an HMAC with SHA-256, using an active endpoint signing secret as the key and signed_payload as the message. Fourth, compare the expected signature with every v1 signature using a constant-time string comparison; if one matches, reject the request when the difference between the current time and the received timestamp is outside your tolerance, and if none matches, reject it.
Debug entries that authenticate nothing
Stripe might add optional secret, destination and payload entries to help with debugging. The secret entry is a redacted representation of the endpoint's newest active signing secret, destination is the ID of the endpoint the secret belongs to, and payload is a suffix of the SHA-256 digest of the exact body that was signed.
Stripe says none of these entries is covered by the HMAC and that an attacker can construct debug values that match a forged request. To prevent downgrade attacks, it says to ignore signature schemes other than v1 and use only the t and v1 entries, and that your integration must accept unknown entries and must not depend on a fixed entry count or order.
On this page's reading, a parser that expects exactly one t and one v1 in a fixed position fails that last rule.
Why the raw body matters
Stripe requires the raw body of the request for signature verification, and says any manipulation of it causes verification to fail. Its page on managing webhook endpoints lists ways a framework can do that before your code sees the body: reordering keys, stripping whitespace, converting to JSON or changing encoding.
For stripe-node with Express it says app.use(express.json()) must appear after the webhook route, because Express applies middleware in order and would otherwise parse the body before verification.
The lab shows the failure from the other side. F8 sent a genuine, correctly signed event to a route that parsed the JSON and verified a re-serialised copy, and that route refused it with 400. F9 sent the same event to the route that verifies the bytes it received, which accepted it.
When genuine events fail verification, this page's advice is to give the check the raw bytes, never to switch the check off.
Stripe webhook replay protection: the signed timestamp
Stripe describes a replay attack as an attacker intercepting a valid payload and its signature, then re-transmitting them.
Its mitigation is the timestamp in the Stripe-Signature header. Because the timestamp is part of the signed payload, an attacker cannot change it without invalidating the signature, and if the signature is valid but the timestamp is too old, you can have your application reject the payload.
Stripe's libraries have a default tolerance of 5 minutes between the timestamp and the current time, and you can change it with an extra parameter when verifying. Stripe warns against a tolerance value of 0, which disables the recency check entirely, and says to use Network Time Protocol so your server's clock stays accurate and in step with Stripe's servers.
In the lab, F4 sent a correctly signed event whose signed timestamp was 600 seconds behind the sender's clock, and the receiver, set to the lab's own 300-second tolerance, refused it.
Stripe says it generates the timestamp and signature each time it sends an event, and that a retried event gets a new signature and timestamp. On this page's reading, a retry is therefore not refused for the age of the original event. On the same reading, the tolerance has a limit of its own: a captured delivery sent again within the window still verifies.
Stopping the same event being acted on twice, whatever its timestamp says, is the job of the event-id ledger in the next section.
Stripe webhook idempotency: acting on each event once
Stripe says webhook endpoints might occasionally receive the same event more than once, and that you can guard against duplicated receipts by logging the event IDs you have processed and not processing already-logged events.
It adds that in some cases two separate Event objects are generated and sent, and that you identify those duplicates by the ID of the object in data.object together with the event type. For Checkout, Stripe's fulfilment guide says the fulfilment function might be called multiple times, possibly concurrently, for the same Checkout Session, and must correctly handle being called multiple times with the same Checkout Session ID.
In its section on processing undelivered events, Stripe's page on managing webhook endpoints sets the order of work. Verify the webhook signature before checking whether you have already processed the event, and if you have, skip it and return a 200 response to stop further retries.
Its example marks an event as processing before the work and as processed after it, using functions you implement against your own data store. In the lab, F2 delivered F1's event again and got a 200 marked as a duplicate, and F3 sent a new event id for the same Checkout Session and got a 200 without a second fulfilment.
Two details decide whether a ledger holds, and both are this page's advice. The store has to refuse a second copy of an event ID by itself, such as through a unique constraint, because two deliveries that each check before either writes can both pass; the race conditions guide covers that pattern.
And the ledger entry needs a clear moment. The lab writes it only after the business step succeeds, so F12's failed first delivery left nothing behind and F13's retry was processed.
A processing mark written before the work needs a rule for work that died halfway, or every later delivery of that event is skipped.
A name clash is worth clearing up. Stripe's API also uses idempotency keys, but those make the requests your server sends to Stripe safe to retry without performing the same operation twice. The ledger here protects the other direction, the events Stripe sends to you, and the race conditions guide covers idempotency keys.
Out-of-order events: why created is not a sequence number
Stripe does not guarantee the delivery of events in the order they are generated.
Its example is a new subscription, which might generate customer.subscription.created, invoice.created, invoice.paid and charge.created if there is a charge. Stripe asks that your event destination not depend on receiving events in a specific order.
It is specific about the tempting shortcut. Snapshot events record created in seconds, so distinct events can share a timestamp, and Stripe says not to use created to determine event order or whether you have already processed an event; track event IDs to identify duplicate deliveries instead.
You can also use the API to retrieve any missing objects. Stripe's example is retrieving the invoice, charge and subscription objects with the information from invoice.paid, if that event arrives first.
Stripe's page also says a snapshot event handler can retrieve the API resource from the Stripe API to access the latest and up-to-date object definition, and the lab does that with an invented stand-in. F10 delivered a subscription snapshot saying active, then F11 delivered one saying past_due, standing for an earlier change that arrived late.
The receiver read the subscription's current state from its in-memory store both times, so the late snapshot did not set the subscription back to past_due.
In your own handler that read goes to Stripe's API and brings failure modes of its own, so this page's advice is to write a snapshot's fields directly only where the order of events cannot change the result.
Retries, response codes and recovering missed events
In live mode, Stripe attempts to deliver events for up to three days with an exponential back off, and it retries sandbox deliveries three times over the course of a few hours.
If the destination has been disabled or deleted when a retry is due, Stripe prevents future retries of that event, although a destination disabled and then re-enabled before Stripe is able to retry still sees future retry attempts. Resend on an event in the Dashboard works for up to 15 days after the event was created, and the Stripe CLI's stripe events resend command for up to 30 days.
Stripe says resending an event that failed to reach an endpoint does not cancel its automatic retries, even when the resend gets a 2xx.
Stripe treats a 200 as successful delivery and considers redirect responses to webhook requests failures. It says your endpoint must quickly return a successful status code before any complex logic that could cause a timeout, with the example of returning a 200 before updating a customer's invoice as paid in your accounting system.
It recommends processing incoming events with an asynchronous queue, and warns that a large spike in deliveries, for example at the beginning of the month when all subscriptions renew, might overwhelm your endpoint hosts. The lab processes each event before it answers, to keep the code short: F12 returned 500 when its invented downstream step failed, and the second delivery, F13, was processed.
On this page's reading, a design with a queue would carry that failure in the queue's own retry instead.
To speed up recovery after an endpoint was unavailable, Stripe's page on managing webhook endpoints describes listing events with delivery_success set to false and the event types your endpoint listens for, and notes that Stripe only returns events created in the last 30 days.
It warns that a recovery script might run more than once and that automatic retries might deliver some events while it runs. This page's advice is for the script and the handler to share one ledger.
The Stripe webhook secret: where it lives, and what rolling it changes
Stripe generates a unique secret for each endpoint.
If one endpoint is used with both test and live API keys, the secret is different for each, and with several endpoints you need a secret for each one you verify. The secret begins with whsec_. The Stripe CLI's stripe listen command prints a secret of its own for local testing, and Stripe's page on managing webhook endpoints says the most common cause of a signature verification error is using the wrong endpoint secret, adding that a CLI-forwarded endpoint's secret differs from a Dashboard-managed endpoint's.
An example on Stripe's page on managing webhook endpoints reads the secret from an environment variable called STRIPE_WEBHOOK_SECRET. The register in this page's asset records the variable's name and where it is set, never the value, and it uses neither "Reveal secret" nor "Click to reveal", which Stripe's pages describe for showing the secret.
The same page also suggests printing the endpointSecret value your code uses to compare it. The register leaves that out, because a printed secret can stay in terminal history or a log (this page's advice).
Stripe says the secret is modifiable in the Webhooks tab in Workbench, and recommends rolling it periodically or when you suspect it has been compromised. When you click "Roll secret" you can expire the current secret immediately or delay its expiration for up to 7 days, to allow time to update the verification code on your server.
During that time multiple secrets are active for the endpoint, and Stripe generates one signature per secret until expiration. Rolling changes the endpoint's signing secret, so the asset plans it rather than doing it.
The R steps of RUN 1 act this out with invented secrets. An event carrying a v1 signature for both secrets was accepted by receiver A, which held only the old secret (R1), and by receiver B, which held only the new one (R2).
Once only the new secret signed, receiver A refused the event with 400 (R3) while receiver B accepted it (R4). Taken with Stripe's statement that it generates one signature per secret until expiration, this page's reading is that a deployment can switch secrets at any point in the overlap, and one that has not switched when the old secret expires starts refusing genuine events. If a secret leaked, the secrets exposure guide covers the rest of the clean-up.
IP addresses, HTTPS, CSRF exemptions and who can change an endpoint
Stripe asks for IP allowlisting alongside signature verification: it sends webhook events from a set list of IP addresses, and suggests configuring your server or firewall to accept webhook requests only from them.
Its Domains and IP addresses page carries the list, offers it as text and JSON files for import into iptables or similar tools, and says Stripe gives seven days' notice through its API announce mailing list before changing its IP addresses. This page's advice is to name the person who receives that notice, because a rule nobody updates can start refusing Stripe after a change.
An HTTPS URL is required in live mode. Stripe says your server must be correctly configured to support HTTPS with a valid server certificate, and that its webhooks support only TLS v1.2 and v1.3. Frameworks such as Rails and Django might check every POST request for a CSRF token, which might stop legitimate events from being processed, so Stripe says you might need to exempt the webhooks route. Its Rails example exempts the webhook action alone. Keeping the exemption that narrow is this page's advice.
Stripe's page on managing webhook endpoints also covers who can change where your events go. The webhook_write permission, shown in the Dashboard as "Webhook Endpoints, Event Destinations: Write", can create or change destinations that subscribe to any event available on your account, and allows read access to any event notification payload and Event object, regardless of access to the object behind it.
Stripe recommends configuring destinations in the Dashboard and avoiding that permission where possible, and, where an integration needs it, isolating it in a dedicated restricted key protected as an administrative credential.
How to use the fixture table and the endpoint register
The asset has four parts, and it works best in this order.
- Fill Part B, the endpoint register, once for every endpoint in each sandbox and in live mode, working from the screens and files each row names. Every row reads a setting, a file or a list. None asks you to reveal, roll or resend anything.
- Read Part A beside it. Each block pairs what Stripe's documentation says about one kind of delivery with what the lab receiver did. Where a block has an S fixture, you can send that fixture to a local copy of your handler within the limits printed at the top of Part A. Where it has none, the block tells you what to read in your code.
- Treat any row where your code contradicts the Stripe page it cites as a finding, such as a tolerance of 0, a JSON parser ahead of the webhook route, or a ledger check that runs before signature verification.
- Fill Part C before anyone rolls an endpoint secret, and read the "Event deliveries" tab after the switch.
- Fill the register again after a framework upgrade, a new endpoint or event type, a move to another host, or a secret roll.
The local fixtures, and what the runs showed
Part D is an illustration, not Stripe, and it holds no code from Stripe's libraries.
It is four small files: the invented values both sides share, a receiver, a sender and a script that runs them. Other than one another, the files import node:http and node:crypto only, and nothing needs installing. Each receiver asks for port 0 on 127.0.0.1, which leaves the choice of port to the operating system: Node.js's net documentation says that if the port is 0, the operating system will assign an arbitrary unused port, and its HTTP documentation says the HTTP server's listen() method is identical to the one in net.
The endpoint secrets are invented and deliberately not in the format of a real Stripe secret, every event is an invented test-mode event, and nothing is sent to Stripe.
It was written and run on Node.js v26.0.0 and on no other version, and a script pasted every output in Part D from the captured files.
The run Part D prints as RUN 1 sent 23 requests, each step once. F1 to F13 went to receiver A: a valid event, the same event again, a second event for the same Checkout Session, four deliveries a handler should refuse, the raw-body pair, the out-of-order pair and the retry pair.
R1 to R4 split the secret-roll deliveries between receivers A and B. S1 to S6 are the six fixtures the sender sends on its own, answered by receiver A, so there is a result to compare your own handler with. In RUN 2 the sender refused 203.0.113.10, an address other than 127.0.0.1 or localhost, before sending anything.
The receiver compares signatures with crypto.timingSafeEqual after checking that both are the same length. Node.js's crypto documentation describes timingSafeEqual as comparing the underlying bytes with a constant-time algorithm, and says it throws an error when the two values differ in byte length. It also says that using it does not guarantee the surrounding code is timing-safe.
What a review of your own endpoint cannot show
The register records how the endpoint is set up and how the code is written.
Several questions sit outside it.
- Whether forged events were accepted before verification was in place. That needs your logs and your order records, and the register only says what is logged now.
- Events Stripe never produced. Stripe documents that in rare cases it can fail to generate an Event object, which is then irrecoverable, and that it creates a health event instead, available as a public preview. Its advice, if your integration relies on the failed event type, is to poll the relevant API for the current state of the affected resource.
- How the ledger behaves when two deliveries of one event arrive together. Reading the code shows the design; a test on a staging copy shows the behaviour.
- What your systems do after the handler: emails, accounting entries, stock and access changes. The fixture table stops at the handler's answer.
- Stripe's own platform. This page makes no statement about what Stripe allows a customer to test on systems Stripe runs; read Stripe's terms before sending test traffic to any of them.
- If you think an endpoint secret or a key has already been misused, call an incident response specialist first: emergency incident response and round-the-clock monitoring are outside what Clever Ops provides. The security logging guide covers what to record for next time.
Where a Clever Ops test fits
This guide is for owners and developers checking their own Stripe webhook endpoint.
What Clever Ops tests is what customers reach through a browser or an API, and in a web application and API penetration test the payment work stays on your application's side, not on the provider's platform. A service another business runs, such as a hosted payment page, comes into scope only with its owner's agreement.
Within a scoped test, that payment work includes checking that an upgrade waits for the provider's confirmation of the payment, and that your notification route turns away a message whose signature does not verify.
It uses a staging copy connected to a non-live payment account wherever one exists, so no real card is charged.
Where the handler itself needs a closer look, the scope can add read-only access to the code for named areas such as the webhook handler. A secure code review is a separate piece of work that reads the source code its written scope names, through read-only access to your repository.
If Clever Ops built or hosts your application, the engagement is called a security review instead of an independent test, and the report records who built the application and who hosts it. For PCI work, Clever Ops is not a PCI Approved Scanning Vendor or a Qualified Security Assessor, so those scans and assessments are referred to a provider that holds the role.
A Clever Ops report is evidence for a decision that someone else makes, such as an auditor or a customer, and is not a certificate.
Bring the filled-in register to the scoping call. It shows which events your application depends on, where its secrets are set and how its handler treats a repeat, which is what a scope needs to decide what is in and what stays out.
Frequently asked questions
Each delivery carries a Stripe-Signature header with a t entry, the time Stripe signed the event, and one or more v1 entries. A v1 entry is an HMAC with SHA-256 over the timestamp, the character . and the unmodified request body, keyed with the endpoint's signing secret. Stripe's page, read on 15 November 2026, says v1 is the only valid live scheme, and that the fake v0 signature it adds to sandbox events must be ignored.
Stripe's libraries default to a tolerance of 5 minutes between the signed timestamp and the current time, and accept a different value as an extra parameter. Stripe warns that a tolerance of 0 disables the recency check entirely, and says to keep the server's clock accurate with Network Time Protocol. Stripe says a retried event gets a new timestamp and signature, so on this page's reading a long retry schedule does not call for a longer tolerance.
Stripe's page on managing webhook endpoints says the most common cause is the wrong endpoint secret: the secret printed by stripe listen differs from a Dashboard endpoint's secret, and Stripe's webhooks page adds that one endpoint used with test and live API keys has a different secret for each. A changed body also makes the check fail: Stripe requires the raw request body, and says some frameworks parse or mutate it by reordering keys, stripping whitespace, converting to JSON or changing encoding. For stripe-node with Express, express.json() has to come after the webhook route.
Yes. Stripe says endpoints might occasionally receive the same event more than once, and that you can guard against them by logging the event IDs you have processed and not processing those already logged. Stripe adds that in some cases two separate Event objects are generated and sent, which you identify by the ID of the object in data.object together with the event type. Stripe also says not to use the created field to decide whether an event was already processed.
In live mode, Stripe attempts delivery for up to three days with an exponential back off, and in a sandbox it retries three times over a few hours. Resend in the Dashboard works for up to 15 days after the event was created, and the CLI's stripe events resend command for up to 30 days. Stripe considers redirect responses failures, and its fix is to set the endpoint to the URL the redirect resolves to.
Stripe lets you expire the current secret immediately or delay its expiration for up to 7 days, and says that during that time multiple secrets are active and it generates one signature per secret until expiration. On this page's reading, a handler holding either secret can verify an event during the overlap, and once the old secret expires a handler still holding it refuses genuine events. The lab's R1 and R2 steps act out the first half with invented secrets, and R3 the second. Rolling changes the endpoint's signing secret, so plan which deployments need the new secret before you start.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.