Stripe webhook 處理程序必須應對的 11 種情況(25 秒短片)
11 things your Stripe webhook handler has to survive (25-second clip)
Syncoders 整理了 Stripe webhook 處理程序需要應對的 11 種情況,並為每項列出一行修正方法。情況涵蓋事件重複或亂序、請求重播或遭竄改、簽署密鑰錯配,以及非同步付款、續訂失敗、退款和爭議;例如用 event.id 去重,並在付款成功事件到達時才授予存取權。
Stripe delivers webhooks at least once, out of order, and sometimes late. Most billing bugs (double emails, a cancelled user getting Pro back, a lost payment) come from those three facts. This short walks through the 11 situations we test a handler against:
Here they are in plain words, with the one-line fix for each:
-
Duplicate delivery. The same event arrives twice. Store
event.idand skip any id you've already processed. -
Out of order.
subscription.updatedcan land beforesubscription.created. Don't trust arrival order; re-read the object from Stripe or compare timestamps before you overwrite state. - Replayed old request. Someone resends a captured request. Signature verification checks the timestamp, so keep the default tolerance.
- Tampered body. Verify against the raw request bytes, not re-serialised JSON, or a perfectly valid signature will fail. A changed body must be rejected.
- Wrong secret. Test mode, live mode and the Stripe CLI each have their own signing secret. A mismatch should fail loudly with a 400, not silently.
-
Guest checkout with a null
customer_email. Read the email fromcustomer_detailsand handle the null case. -
Async payment. A checkout can complete unpaid, then
checkout.session.async_payment_succeededarrives later, then gets redelivered. Grant access on the payment event, once. -
Async payment failed. Handle
async_payment_failedso the order doesn't hang in "pending". -
Failed renewal.
invoice.payment_failedshould start your dunning flow, not cut access on the first try. - Refund. Decide what a refund does to access, and make it idempotent too.
-
Dispute.
charge.dispute.createdis worth an alert to a human.
The longer write-up, with diagrams and code for each failure, is here: 7 ways Stripe webhooks break in production. There's also a free Stripe webhooks go-live checklist.
Disclosure: the clip is for our paid Stripe Webhook Survival Pack ($9). It replays these 11 scenarios offline with real Stripe-Signature headers, no Stripe account needed: TypeScript (52 tests) and Python (41 tests), plus a 31-point checklist, a 9-page chapter and a "review my handler" AI prompt.
來源:DEV Community · dev.to