A Stripe webhook is an HTTPS POST that Stripe sends to a URL you register whenever something happens on your account: a payment succeeds, a subscription renews, a customer disputes a charge. Your endpoint verifies the request came from Stripe, records the event, returns a 2xx quickly, and does the real work afterwards. Stripe's own docs put the order bluntly: return the 200 before updating anything slow, like marking an invoice paid in your accounting system (Stripe).
You need webhooks because the browser can't be trusted to tell you a payment happened. Customers close tabs, lose signal, and pay with bank debits that settle days later. The webhook is the only notice that reaches your server every time.
Setting up the endpoint
- Register it. In the Dashboard, open the Webhooks tab in Workbench, create an event destination, pick the event types and give it your URL. Live endpoints must be public HTTPS, and you can register up to 16 event destinations per account (Stripe).
- Copy the signing secret. Each endpoint gets its own secret starting
whsec_. The same endpoint has a different secret in test and live mode, so "the webhook secret" is really two values, and mixing them up is the most common cause of signature failures (Stripe). - Subscribe to what you handle, not everything. Stripe says listening to all events "puts undue strain on your server". Which Stripe webhook events to subscribe to has the list by integration type.
- Exempt the route from CSRF protection. Rails and Django will otherwise reject Stripe's POSTs for not carrying a CSRF token.
Stripe now offers two payload formats when you create a destination: snapshot events, which carry a copy of the object, and thin events, which carry a reference you fetch. The Dashboard labels thin as recommended for new integrations; snapshot is still what most existing code, the CLI's --forward-to and the examples below expect (Stripe).
How Stripe signs a webhook
Every delivery carries a Stripe-Signature header, one line of comma-separated entries:
Stripe-Signature: t=1798765432,v1=5257a869e7ec...,v0=6ffbb59b2300...
tis the Unix timestamp when Stripe signed this delivery. It isn't when the event happened.v1is a hex HMAC-SHA256. The key is your endpoint's signing secret, and the message is the timestamp, a literal., and the raw request body:t.payload. There can be severalv1entries.v0shows up on sandbox events and is fake. Ignore it, and ignore any scheme other thanv1, which is how you avoid downgrade attacks.
Stripe may also add secret, destination and payload entries for debugging. They aren't signed, so never trust them, and your parser must accept entries it doesn't recognise in any order (Stripe).
Stripe webhook signature verification in Python
Use the library unless you have a reason not to. construct_event checks the signature and the timestamp, then parses the JSON:
import os
import stripe
from flask import Flask, request
app = Flask(__name__)
endpoint_secret = os.environ["STRIPE_WEBHOOK_SECRET"] # whsec_...
@app.post("/webhooks/stripe")
def stripe_webhook():
payload = request.get_data() # the raw bytes, never request.json
sig_header = request.headers.get("Stripe-Signature", "")
try:
event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
except ValueError:
return "Invalid payload", 400
except stripe.SignatureVerificationError:
return "Invalid signature", 400
if not claim_event(event["id"]): # atomic insert; False if already seen
return "", 200
enqueue(event["id"], event["type"]) # do the real work off the request
return "", 200
The raw body is the whole game. Parse the JSON and re-serialise it, and the bytes change and every signature fails, which is why request.get_data() and not request.json. In FastAPI that's await request.body().
If you can't use the library (a minimal Lambda, a language Stripe doesn't ship), the manual check is short. This follows Stripe's four steps: split the header, build t.payload, compute the HMAC, compare in constant time, then check the age:
import hashlib
import hmac
import time
def verify_stripe_signature(payload: bytes, header: str, secret: str,
tolerance: int = 300) -> bool:
timestamp, signatures = None, []
for item in header.split(","):
key, _, value = item.strip().partition("=")
if key == "t" and timestamp is None:
timestamp = value
elif key == "v1":
signatures.append(value)
if not timestamp or not signatures:
return False
signed_payload = timestamp.encode() + b"." + payload
expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
if not any(hmac.compare_digest(expected, sig) for sig in signatures):
return False
try:
return abs(time.time() - int(timestamp)) <= tolerance
except ValueError:
return False
The 300 seconds matches the libraries' default tolerance of five minutes. Don't pass a tolerance of 0; Stripe warns that it switches the recency check off entirely, which turns a captured request into a reusable one. Keep the server clock synced with NTP, because a drifting clock rejects real events. Retries don't trip the check: Stripe generates a fresh timestamp and signature for every delivery attempt (Stripe).
Rolling the webhook secret
Roll the secret periodically, and immediately if it leaks. In the endpoint's menu, Roll secret lets you expire the old one at once or keep it alive for up to 7 days. While both are active, Stripe signs each delivery once per secret, so the header carries two v1 values and the old code keeps passing until you deploy the new secret (Stripe). That's why the verifier above checks every v1, not just the first.
Retries, duplicates and ordering
Checked November 2026 against Stripe's webhook docs:
| Behaviour | What Stripe does | What it means for you |
|---|---|---|
| Automatic retries | Live mode: up to three days, exponential backoff. Sandbox: three times over a few hours | Your store of seen event IDs must outlast three days |
| Manual resend | Dashboard: up to 15 days after the event. CLI stripe events resend: up to 30 days | A resend is a duplicate too. Dedupe it the same way |
| Event history | The List Events API returns the last 30 days | Recover from an outage inside that window or not at all |
| Redirects | A 3xx counts as a failed delivery | Register the final URL, including the trailing slash your framework wants |
| Ordering | Not guaranteed. created has one-second resolution | Never order by created; fetch the object for current state |
| Duplicates | Same event.id on a redelivery; occasionally two distinct events for one change | Dedupe on event.id, plus data.object.id with type for the rare pair |
A manual resend that gets a 2xx doesn't cancel the automatic schedule, either. After an outage, process the backlog from the Events API, and when the retries arrive, verify, see the ID is already done, and return 200 to stop them (Stripe).
The duplicate and ordering material has its own pages: Stripe webhook duplicates and ordering for the delivery semantics, and webhook idempotency in Python for the store that makes a second delivery harmless.
Two more locks on the door
Signature verification is the one you can't skip. Stripe also publishes the IP addresses webhooks come from and recommends allowlisting them as a second layer, and it only delivers over TLS 1.2 or 1.3 (Stripe).
Local testing with the Stripe CLI: listen, trigger and resend, with the signing-secret trap that catches everyone once. From chapter 9.
The Stripe CLI Loop
stripe login
stripe listen --forward-to localhost:4242/webhooks/stripe # prints a whsec_... signing secret
stripe trigger payment_intent.succeeded
stripe trigger invoice.payment_failed
stripe events resend evt_1ABC... # replay a real event against your local endpoint
listen gives your local server a webhook feed and a temporary signing secret; put that secret in your local environment, not the one from the Dashboard, or every local signature check fails. trigger creates real test-mode objects, so the event you receive carries real IDs you can retrieve. events resend replays an event that already happened, which is the fastest way to reproduce a customer's problem on your machine.
What Test Mode Won't Tell You
Radar scores test cards differently from real ones, real issuers run their own 3DS challenge screens, payout timing is fake, and test-mode webhooks give up after three retries where live mode retries for three days. Before launch, run a few small live charges on your own card, watch them through the webhook endpoint and into your database, then refund them.
What to assert once the CLI is wired up. Chapter 39's test plan for the three failure modes, written for five providers; the Stripe parts apply as is.
Testing Duplicates, Reordering, and Late Delivery
Test the store, not the response. Every provider will happily tell you your endpoint returned 200; the question is whether the payments table changed once. Deliver the same signed payload twice and assert one row updated and one email sent. Then flush Redis and deliver it a third time, and assert the database layer caught it. That third delivery is the TTL-expiry test most suites never run.
Capture fixtures from the real thing. Run a tunnel, fire events with the tools in the table (stripe trigger, Paddle's simulator, Square's Send test event, Adyen's Test configuration, PayPal's simulator), and save the raw bytes and headers to disk. For the HMAC providers you can also sign your own fixtures with a test secret, which lets you build cases the simulators won't, like a valid signature over a tampered body. PayPal you can't sign locally, so mock the verify endpoint and test both SUCCESS and a failure response.
Reordering tests take a captured sequence and deliver it backwards. If you use fetch-current-state, mock the provider's read API to return the final object and assert the final row matches it regardless of order. If you use sequence numbers, deliver the second event first, assert it's queued and nothing changed, deliver the first, and assert both applied in order. Then test the timeout: deliver the second event alone, advance the clock past an hour, and assert whatever you decided abandoned events should do.
Late delivery has two flavors. For Stripe and Paddle, deliver a fixture with a signature timestamp older than the tolerance and assert rejection before any parsing. For every provider, deliver a fixture whose event ID you recorded longer ago than your retention and assert your chosen behavior, because the code will process it as new. Sandbox retry schedules are shorter than live ones, three tries over a few hours for Stripe and 15 minutes for Paddle, so the three-day tail is something you have to simulate, not wait for.
The Stripe CLI commands worth memorising
| Command | What it does |
|---|---|
stripe login | Pairs the CLI with your account |
stripe listen --forward-to localhost:4242/webhooks/stripe | Forwards snapshot events to your local endpoint and prints a temporary whsec_ secret |
stripe listen --forward-connect-to localhost:4242/webhooks/stripe | The same for events from connected accounts |
stripe listen --forward-thin-to localhost:4242/webhooks/stripe --thin-events "*" | The same for thin events |
stripe trigger payment_intent.succeeded | Creates real test objects and fires the event |
stripe events resend <event_id> --webhook-endpoint=<endpoint_id> | Redelivers an event created in the last 30 days |
--forward-to only works from a real terminal. Workbench Shell in the Dashboard can run stripe trigger but doesn't support forwarding (Stripe).
Questions
How do I verify a Stripe webhook signature?
Pass the raw request body, the Stripe-Signature header and your endpoint's whsec_ signing secret to stripe.Webhook.construct_event. To do it by hand, compute an HMAC-SHA256 of the timestamp, a dot and the raw body with the signing secret as the key, compare it in constant time with every v1 value in the header, and reject timestamps outside your tolerance.
Where do I find my Stripe webhook secret?
Open the endpoint in the Webhooks tab in Workbench and reveal the signing secret, which starts with whsec_. Each endpoint has its own, test and live mode have different ones, and stripe listen prints a separate temporary secret for local development.
Why does Stripe webhook signature verification fail?
Usually because the body was parsed and re-serialised before verification, or because the code uses the wrong secret: the Dashboard endpoint's secret instead of the one stripe listen printed, or test instead of live. Verify against the exact raw bytes, and print the secret your code loads to compare.
How long does Stripe retry a failed webhook?
In live mode Stripe retries for up to three days with exponential backoff. In a sandbox it retries three times over a few hours. You can resend an event manually for up to 15 days in the Dashboard and up to 30 days with the Stripe CLI.
What is the default timestamp tolerance for Stripe webhooks?
Five minutes, or 300 seconds, in Stripe's official libraries. Each retry is signed with a new timestamp, so legitimate retries pass. Don't set the tolerance to 0, which disables the check.
How do I test Stripe webhooks locally?
Run stripe listen --forward-to with your local URL, put the whsec_ secret it prints into your local environment, then fire events with stripe trigger or replay real ones with stripe events resend.