Stripe Webhook 穩健架構指南:冪等性與時序安全
Architecting Bulletproof Stripe Webhooks: Idempotency and Timing Safety
Stripe Webhook 採用資料庫層級去重、保留原始請求內容作簽章驗證,並把繁重工作交由背景工作佇列處理,以提升處理可靠性。Stripe 採用至少一次送達機制,網絡延遲或下游逾時可能觸發重試;Webhook 路由應在 200ms 內確認收到。
Payment webhooks are the single most fragile architectural boundary in modern SaaS applications. When integrating Stripe, developers frequently follow tutorial code that functions in local testing but fails under production network latency.
In this guide, we examine the core failure modes and the architecture required to harden webhook handlers.
1. The Duplicate Delivery Trap (Idempotency)
Stripe guarantees at-least-once delivery. Network latency or temporary downstream timeouts cause Stripe to retry webhooks with exponential backoff.
Without database-level deduplication, handlers credit customer accounts multiple times or duplicate fulfillment actions.
// Atomic Deduplication Pattern (Next.js / Prisma)
const existing = await db.webhookEvent.findUnique({ where: { eventId: event.id } });
if (existing && existing.status === "COMPLETED") {
return NextResponse.json({ received: true, deduplicated: true });
}
2. Raw Body Integrity & Signature Verification
Parsing the request body as JSON before verification alters byte order and key serialization, causing HMAC signature verification to fail.
Always extract the raw string/buffer directly before any JSON parser runs:
const rawBody = await req.text();
const signature = req.headers.get("stripe-signature");
const event = stripe.webhooks.constructEvent(rawBody, signature, WEBHOOK_SECRET);
3. Two-Tier Asynchronous Execution
Stripe enforces an HTTP timeout. Heavy tasks (invoice PDFs, customer notification emails, CRM updates) must be offloaded to an asynchronous background worker queue (e.g. BullMQ, Inngest, Celery), ensuring the webhook route acknowledges in under 200ms.
Automated Auditing with Claude Code
If you build on Claude Code or Cursor, you can automate this entire verification suite using the turnkey Stripe Webhook Sentinel on Agensi.
來源:DEV Community · dev.to