The short answer
A Stripe webhook is an HTTPS request from Stripe to your server whenever something happens in your account. For license keys, six events matter. Your endpoint must prove each request came from Stripe, reply with a 2xx quickly, and do the work in a way that is safe to run twice. Everything else in this article follows from those three rules and from three facts about delivery: Stripe retries, Stripe sometimes sends duplicates, and Stripe does not promise order.
The six events
This is the set Clavem subscribes to when it registers an endpoint in your Stripe account, and it is a good minimum for any licensing system.
| Event | Fires when | What your handler does | Trap |
|---|---|---|---|
checkout.session.completed |
A Checkout Session finishes, including Payment Links | Retrieve the session with line items. If payment_status is paid or no_payment_required, create the order and keys |
A delayed method completes as unpaid. Issue nothing yet |
checkout.session.async_payment_succeeded |
A delayed payment, such as a bank debit, settles | Run the same fulfilment function | Without it, bank-debit buyers never get a key |
invoice.paid |
A subscription invoice is paid, including renewals | Move the license expiry to the end of the period the invoice paid for, and revive an expired license | The first invoice also fires it. Fulfilment must not issue a second key |
customer.subscription.updated |
A subscription starts or changes: renewals, coupons, plan changes, a cancellation scheduled for the period end | Mirror the subscription’s current status onto the license | It fires for every change, so read the status, not the fact of the event |
customer.subscription.deleted |
A subscription ends, by direct cancel or at the end of a period set to cancel | Expire the license | A hand-disabled license must stay disabled |
charge.refunded |
A charge is refunded, in full or in part | Full refund: disable the license from that order. Partial: apply your rule | A refund of a subscription invoice should cancel the subscription instead |
Two events you might expect are missing. checkout.session.async_payment_failed is useful for emailing a buyer whose bank debit failed, since Stripe’s guide suggests it. charge.dispute.created tells you a chargeback has started. Neither is required to issue keys, and you can add them without changing the rest. Clavem does not subscribe to them.
Verify the signature
Stripe signs every webhook it sends to an endpoint. The Stripe-Signature header looks like t=1795126928,v1=91d8be82.... Your server rebuilds the signature from three things: the timestamp t, a dot, and the exact raw request body. It hashes that string with HMAC-SHA256, keyed with the endpoint’s signing secret (it starts with whsec_), and compares the hex result with each v1 value.
The check below uses only node:crypto. I ran it, and I also ran Stripe’s own stripe-node library on the same payload and header:
const crypto = require('node:crypto');
function verifyStripeSignature(rawBody, header, endpointSecret, toleranceSeconds = 300, now = Math.floor(Date.now() / 1000)) {
const t = Number(header.split(',').find((p) => p.startsWith('t='))?.slice(2));
// A header can hold several v1 entries, for example while a secret is being rolled.
const candidates = header.split(',').filter((p) => p.startsWith('v1=')).map((p) => p.slice(3));
if (!t || candidates.length === 0) return false;
if (Math.abs(now - t) > toleranceSeconds) return false; // replayed or stale
const expected = crypto.createHmac('sha256', endpointSecret).update(`${t}.${rawBody}`, 'utf8').digest();
return candidates.some((c) => {
const got = Buffer.from(c, 'hex');
return got.length === expected.length && crypto.timingSafeEqual(got, expected);
});
}
Results of the run:
own verify, exact body : true
own verify, re-serialised body: false
own verify, wrong secret : false
own verify, 10 minutes later : false
stripe-node constructEvent : checkout.session.completed evt_test_123
own verify accepts lib header : true
lib accepts own header : evt_test_123
lib on re-serialised body : StripeSignatureVerificationError - No signatures found matching the expected signature for payload. Are you passing the raw r
So the hand-written check and the library agree, a body that was parsed and written back out fails, a wrong secret fails, and a request ten minutes old fails the five-minute tolerance. In production use the library. Stripe’s documentation recommends official libraries for verification, and with stripe-node and Express it looks like this:
app.post('/webhook', express.raw({ type: 'application/json' }), (request, response) => {
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
return;
}
// ...handle event.type, then:
response.sendStatus(200);
});
Stripe’s libraries default to a five-minute tolerance. Stripe warns against setting it to 0, because that disables the recency check entirely.
The raw body trap
Verification needs the exact bytes Stripe sent. A framework that parses the JSON before your code runs, then hands you an object you serialise again, changes whitespace and key order, and the signature no longer matches. The run above shows it: JSON.stringify(JSON.parse(payload)) failed even though the content was identical.
Read the body as text or a buffer before anything else touches it. In Express that means express.raw on the webhook route, as above. In frameworks built on the Fetch API, such as Hono, Next.js route handlers and Cloudflare Workers, call await request.text() and verify that string. The other common causes are in Stripe’s troubleshooting guide:
- The wrong secret. The signing secret of a listener started with the Stripe CLI is different from the secret of a Dashboard endpoint. Do not mix them.
- A rolled secret. If you roll the secret in Stripe and do not update your server, every delivery fails with
400.
Retries, duplicates and order
Three documented behaviors decide how you write the handler:
- Retries. In live mode Stripe attempts delivery for up to three days with exponential backoff. In a sandbox it retries three times over a few hours. Failed events can be resent by hand from the Dashboard for up to 15 days after creation, or with
stripe events resend <event_id> --webhook-endpoint=<endpoint_id>for up to 30. - Duplicates. Endpoints can receive the same event more than once, and sometimes two separate Event objects are generated for one occurrence. Stripe’s advice is to log processed event ids, and to use the object id in
data.objecttogether with the event type to spot the second kind. - Order. Stripe does not guarantee events arrive in the order they were generated. Creating a subscription can produce
customer.subscription.created,invoice.created,invoice.paidandcharge.createdin any order. Do not usecreatedtimestamps to order events, because distinct events can share one.
The consequence for subscriptions is practical. If customer.subscription.deleted arrives before an older customer.subscription.updated, applying them in arrival order resurrects a cancelled license. The fix is to treat the event as a nudge, then fetch the subscription from the API and act on its current state.
A handler that survives all of it
Reply 2xx quickly, because Stripe wants the response before slow work, such as an email. Return 4xx for a bad signature and 5xx when your own work fails, so Stripe retries. Record the event id only after the work succeeded.
I ran this skeleton against signed requests with a stubbed set of side effects:
async function handleWebhook(rawBody, header) {
if (!verify(rawBody, header, secret)) return { status: 400 };
const event = JSON.parse(rawBody);
if (seenEvents.has(event.id)) return { status: 200, duplicate: true };
try {
switch (event.type) {
case 'checkout.session.completed':
case 'checkout.session.async_payment_succeeded':
await fulfil(event.data.object.id); break;
case 'invoice.paid':
await extend(event.data.object.subscription); break;
case 'customer.subscription.updated':
case 'customer.subscription.deleted':
await reread(event.data.object.id); break; // act on the subscription as it is now
case 'charge.refunded':
await refund(event.data.object.payment_intent); break;
default: break; // everything else: answer 200 and move on
}
} catch {
return { status: 500 }; // not recorded, so Stripe's retry runs it again
}
seenEvents.add(event.id);
return { status: 200 };
}
The output: the first delivery returned 200, a retry of the same event returned 200 with duplicate: true and did nothing, a body edited after signing returned 400, and an unrelated event type returned 200. The event id alone is not enough, though. The business operation needs its own key as well, such as a unique order per Checkout Session id, because two deliveries of one event can arrive concurrently before either is recorded.
Stripe’s current webhook documentation also describes thin events and recommends them for new integrations. The six events here are snapshot events, which carry the whole object. If you build on thin events, the shape of your handler changes, but the rules above do not.
Test it without a customer
The Stripe CLI covers most of this. stripe listen --forward-to localhost:4242/webhook forwards your account’s events to a local server and prints a signing secret for that listener, which is the secret to use locally. stripe trigger payment_intent.succeeded fires a test event, and Stripe’s documentation shows it as the example. Events triggered this way use Stripe’s own fixture objects, so a mapping-based system will report them as unmapped, which is a useful test of that path too. For the real flow, run a sandbox checkout with 4242 4242 4242 4242 and watch the endpoint’s deliveries in the Dashboard.
Doing this with Clavem
When you connect Stripe, Clavem creates a webhook endpoint in your account pointing at a private URL, subscribed to these six events and pinned to a fixed Stripe API version. It verifies each signature against the endpoint’s secret, which it stores encrypted. Each event id is processed once, an event is recorded only when its work succeeded so a crash leaves it open for Stripe’s retry, and subscription events re-read the subscription instead of trusting arrival order. A paid purchase issues its licenses even over your plan’s limit.
If deliveries show 400 in Stripe after you rolled the signing secret, disconnect and connect again. The Stripe connection guide lists each event, the troubleshooting table and the key permissions, and how to add license keys to Stripe shows the fulfilment function the first two events call.
Questions
How does Stripe sign a webhook?
Each request carries a Stripe-Signature header with a timestamp (t) and one or more v1 values. A v1 value is an HMAC-SHA256 of the timestamp, a dot and the exact raw request body, keyed with the endpoint's whsec signing secret. Stripe's libraries do the check for you and reject timestamps more than five minutes old by default.
How long does Stripe keep retrying a failed webhook?
In live mode, for up to three days with exponential backoff. In a sandbox, three times over a few hours. You can also resend an event by hand from the Dashboard for up to 15 days, or with the Stripe CLI for up to 30 days.
Why does signature verification fail with a correct secret?
Almost always because the body was changed before verification, for example by a JSON parser and re-serialiser. The next most common cause is mixing the signing secret of a CLI listener with that of a Dashboard endpoint.
Sources
- Stripe docs, receive events with webhooks (as of November 2026)
- Stripe docs, resolve webhook signature verification errors (as of November 2026)
- Stripe docs, fulfil orders after Checkout (as of November 2026)
- Stripe docs, subscription webhooks (as of November 2026)
- Stripe docs, cancel subscriptions (as of November 2026)