Payment Gateway Webhooks, Done Right
Most payment bugs I've fixed weren't in the checkout — they were in the webhook handler. After building gateway plugins for WooCommerce and custom stores, this is the checklist I keep.
1. Verify before you trust
Every webhook must be verified against the gateway's signature using the raw request body. Parse JSON after verification, never before.
const expected = crypto
.createHmac("sha256", process.env.PG_WEBHOOK_SECRET)
.update(rawBody)
.digest("hex");
if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) {
return new Response("Invalid signature", { status: 401 });
}
2. Make every event idempotent
Gateways retry. Store the event ID and ignore duplicates, and make state changes conditional ("mark paid only if pending") so an out-of-order event can't undo a refund.
3. Answer fast, work later
Return 200 quickly and move slow work (emails, invoices, stock updates) to a queue. A slow handler looks like a failed one to the gateway.
4. Treat refunds as first-class
- Support full and partial refunds from the admin.
- Record who refunded, how much and why.
- Reconcile refund webhooks against what the admin requested.
None of this is glamorous, but it's the difference between a plugin merchants trust and one they're afraid to update.
