Video in progress
How do you make an endpoint that receives webhooks from a payment provider reliable and secure?
I verify the signature, write the event to the DB first and return 2xx right away, and do the heavy work in the background. The provider may send the same event several times and out of order, so processing is idempotent by event ID.
📖 Answer
Providers usually work like this: if no response arrives within a few seconds, or it isn't 2xx, they resend for hours, sometimes days. So you should expect duplicates and out-of-order delivery up front.
@PostMapping("/webhooks/payments")
ResponseEntity<Void> receive(@RequestHeader("X-Signature") String signature,
@RequestBody byte[] rawBody) {
if (!signatureVerifier.isValid(rawBody, signature)) {
return ResponseEntity.status(401).build();
}
WebhookEvent event = parser.parse(rawBody);
inbox.saveIfAbsent(event.id(), event.type(), rawBody); // UNIQUE(event_id)
return ResponseEntity.ok().build();
}
Important points:
- The signature is checked over the raw bytes. If you parse the JSON into an object and serialize it again, whitespace and field order change and the signature won't match. Compare with
MessageDigest.isEqual, because plainequalsis open to a timing attack. - Check the timestamp too (for example, nothing older than 5 minutes), which protects against replay attacks.
- The endpoint only records. Updating the order, sending email, publishing an event to another service all happen in a background worker that reads from the
inboxtable. That way you don't hit the provider's timeout, and your own bugs don't cause resends. - Ordering:
payment.refundedmay arrive beforepayment.succeeded. During processing, check the state machine, or when in doubt ask the provider's API for the current state. - Don't trust a webhook blindly. For large amounts it is standard practice to take only the ID from the event and confirm the state through the provider's API.
And monitoring: a "when did the last webhook arrive" metric. On the day the provider stops sending, this is the first thing to show it.
Sign up to mark studied questions and save your progress.