A payment provider’s webhook is production code you did not write, calling production code you did. When it goes wrong, the failure is silent and the symptom is an angry customer whose paid order says “pending”.
The four rules
- Verify the signature, on the raw body. Parse-then-verify fails because JSON re-serialization changes bytes:
const sig = createHmac('sha256', WEBHOOK_SECRET).update(rawBody).digest()
const given = Buffer.from(c.req.header('X-Signature') ?? '', 'hex')
if (given.length !== sig.length || !timingSafeEqual(sig, given)) return c.text('no', 401)-
Ack in milliseconds, process async. Insert the event into a queue/table and return 200. Providers time out at 5-10 s and mark you as failing - which pauses your deliveries. Your inventory logic has no business inside the request handler.
-
Dedupe by event id. Every provider redelivers - that is a feature.
INSERT ... ON CONFLICT (event_id) DO NOTHING; if no row was inserted, you have processed it before, stop. -
Treat order as unknown.
payment.settledcan arrive beforepayment.created. Process events as state assertions (“this payment is now settled”), not as a story told in sequence.
And a reconciliation job
Webhooks are best-effort even from the best providers. A nightly job that pulls the provider’s API and diffs against your database is the safety net that turns “we lost 14 orders” into a log line nobody had to escalate.