Guides · Free check · $9 fix pack

Guides

Green webhook tests, broken production: test with signed events, not mocks

You asked an AI agent to make the Stripe webhook idempotent. It wrote dozens of tests, CI is green, and production still sends double emails, grants access twice, or answers Stripe with 400 and 500. Usually the tests never touched the parts that break: the signature check, the raw body, and the database under concurrent deliveries.

Three mocks that hide real bugs

1. Sign test payloads with the real library

You don't need to mock the signature. stripe-node has a helper for tests: "You can use stripeClient.webhooks.generateTestHeaderString to mock webhook events that come from Stripe", and the README pairs it with a real constructEvent call (stripe-node README: Testing Webhook signing). The handler under test runs its normal verification with a test secret.

// webhook.test.ts (sketch; adapt to your test runner and route)
import Stripe from "stripe";
const stripe = new Stripe("sk_test_placeholder");
const secret = "whsec_test_secret";            // set STRIPE_WEBHOOK_SECRET to this in the test env

function signedRequest(event: object) {
  const payload = JSON.stringify(event);
  const header = stripe.webhooks.generateTestHeaderString({ payload, secret });
  return new Request("http://localhost/api/webhooks/stripe", {
    method: "POST",
    headers: { "stripe-signature": header, "content-type": "application/json" },
    body: payload,                              // the exact bytes that were signed
  });
}

const event = { id: "evt_test_1", object: "event", type: "checkout.session.completed",
  data: { object: { id: "cs_test_1", object: "checkout.session", payment_status: "paid" } } };

// 1. Valid signature -> 200, exactly one row in the real test database.
// 2. Same event sent twice at once -> both 200, still exactly one fulfillment row.
await Promise.all([POST(signedRequest(event)), POST(signedRequest(event))]);
// 3. No stripe-signature header -> 400, no row.
// 4. Signed with a different secret -> 400, no row.

Names, routes and the event shape are placeholders. If your handler retrieves the Checkout Session from the API before fulfilling (as Stripe's fulfillment guide does), stub only that outbound API call, or run the end-to-end check in step 3 against a sandbox.

2. Let the database enforce "only once"

Insert the event ID, or better the Checkout Session ID for fulfillment, into a table with a unique constraint, and treat a conflict as "already done". In Postgres (Supabase included), ON CONFLICT DO NOTHING "simply avoids inserting a row as its alternative action", and ON CONFLICT DO UPDATE "guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency" (PostgreSQL docs: INSERT).

-- one fulfillment per Checkout Session, enforced by the database
create table if not exists fulfillments (
  checkout_session_id text primary key,
  user_id uuid not null,
  created_at timestamptz not null default now()
);

insert into fulfillments (checkout_session_id, user_id)
values ($1, $2)
on conflict (checkout_session_id) do nothing
returning checkout_session_id;   -- no row returned = already fulfilled, skip side effects

Send emails and grant credits only when the insert returned a row. Run the concurrent test above against a real Postgres (a local Supabase or a throwaway test database), not a mock, or it proves nothing. Stripe also notes that sometimes "two separate Event objects are generated and sent", and suggests using the ID of data.object with event.type to spot those (source). That is one more reason to key fulfillment on the session, not only on event.id.

3. Run real Stripe events through the real route

Unit tests can't catch a wrong whsec_, a redirect, or a body parser that runs before your handler. Before you trust the suite, send real test events end to end:

  1. Forward events locally. stripe listen forwards events to your machine and prints the signing secret to use (Stripe docs: Test your webhook). The CLI reference says that with --forward-to "you must also select the events to forward with --events, --all-snapshot, or --all-thin" (Stripe CLI: listen).
  2. Trigger an event. stripe trigger checkout.session.completed creates real sandbox objects; "triggering events causes side effects: all necessary API objects will be created in the process" (Stripe CLI: trigger). It won't carry your app's metadata, so add it with --add or --override (source), or see metadata missing user ID.
  3. Replay the same event. stripe events resend evt_… sends an event again to a running stripe listen session, from the last 30 days (Stripe CLI: events resend). Resend it twice and check you still have one fulfillment row.
stripe listen --events checkout.session.completed --forward-to localhost:3000/api/webhooks/stripe
# in another terminal
stripe trigger checkout.session.completed
stripe events resend evt_XXXX   # the event ID printed by listen; run it twice

Prompt for your AI builder

Rewrite the Stripe webhook tests. 1) Do not mock constructEvent or skip signature verification in any test. Use stripe.webhooks.generateTestHeaderString with a test secret, and send the exact signed string as the request body to the real route handler. 2) Use a real test database, not an in-memory fake. 3) Add tests: valid signed event returns 200 and creates exactly one fulfillment row; the same event sent twice concurrently creates exactly one row; a request with no Stripe-Signature header returns 400 and writes nothing; a request signed with the wrong secret returns 400 and writes nothing. 4) Enforce idempotency with a unique constraint on the Checkout Session ID and insert ... on conflict do nothing; run side effects only when the insert returned a row. 5) Only stub outbound Stripe API calls, never our own code under test.

Re-test in production

  1. Send an unsigned curl -i -X POST with an empty JSON body to the live webhook URL: 400 is right, 200 means it isn't verifying (fails-open guide).
  2. In the Dashboard, resend one recent checkout.session.completed to the live endpoint (how) and confirm the user got access once, with no second email or credit.
Check yours in 10 seconds (free).

Paste your webhook URL. WebhookProof sends 3 harmless test requests and tells you whether Stripe can reach it and whether it rejects unsigned events. If it finds a problem, the $9 fix pack gives you the exact copy-paste fix for your stack (refundable for 14 days).

Run the free check

FAQ

Should I mock Stripe signature verification in webhook tests?

No. stripe-node provides webhooks.generateTestHeaderString so tests can send correctly signed payloads to the real handler, which runs its normal constructEvent check with a test secret.

Why do my webhook idempotency tests pass but production still double-fulfills?

Usually the "already processed" check was tested against a mock or one event at a time. Stripe can send the same event more than once and fulfillment can run concurrently. Enforce it with a unique constraint in the real database and test two concurrent deliveries.

How do I test a Stripe webhook end to end before going live?

Run stripe listen with --events and --forward-to your local route, trigger checkout.session.completed with stripe trigger, and resend the same event with stripe events resend to confirm it is handled once.

Sources

More guides

Stripe webhook not working? Check these 7 things in order · A customer paid but didn't get access. What went wrong? · No signatures found matching the expected signature for payload · Stripe webhook failing with a 307 or 308 redirect

Last reviewed 2026-11-16. WebhookProof is an independent tool, not affiliated with Stripe, Inc.. Quotes are from the linked documentation.