BBackend CourseLeroy Labs
0/0
Search the course

Verifying webhooks with HMAC signatures (Stripe & Paystack)

How providers sign webhook payloads, why you need the raw body, constant-time comparison, replay protection with timestamps and event ids, and idempotent processing.

● advancedSpring-Boot-StoreIR3D (Kontentt)

The concept

A webhook is a public URL (/checkout/webhook) that a provider POSTs to when something happens, such as “payment succeeded”. Anyone can POST to that URL. Without verification, an attacker sends {"event":"charge.success","amount":...} and gets free goods.

HMAC (Hash-based Message Authentication Code): the provider and you share a secret, and the provider sends HMAC(secret, rawBody) in a header. You recompute it and compare.

@PostMapping("/api/webhooks/paystack")
public ResponseEntity<Void> paystack(@RequestBody String rawBody,              // RAW string!
                                     @RequestHeader("x-paystack-signature") String sig) {
    Mac mac = Mac.getInstance("HmacSHA512");
    mac.init(new SecretKeySpec(secret.getBytes(UTF_8), "HmacSHA512"));
    byte[] expected = HexFormat.of().formatHex(mac.doFinal(rawBody.getBytes(UTF_8))).getBytes(UTF_8);

    if (!MessageDigest.isEqual(expected, sig.getBytes(UTF_8)))                 // constant time
        return ResponseEntity.status(401).build();

    webhookService.handle(rawBody);   // idempotent!
    return ResponseEntity.ok().build();  // ack fast; heavy work async
}

Why the raw body

If Spring parses the JSON into an object and you re-serialise it, whitespace, key order and number formats change, and the HMAC no longer matches. Always take @RequestBody String (or byte[]) for signed payloads.

Why constant-time comparison

String.equals returns at the first mismatching byte. By measuring response times, an attacker can guess the signature one byte at a time. MessageDigest.isEqual always takes the same time.

Replay protection

A captured valid webhook could be re-sent. Defences:

  • A timestamp in the signed content, rejected if older than about 5 minutes. Stripe’s Stripe-Signature: t=...,v1=... does this.
  • Event id deduplication: store processed event ids and ignore repeats.

In your projects

Spring-Boot-Storepayment/StripePaymentGateway.parseWebhookRequest · CheckoutController
Event event = Webhook.constructEvent(payload, signatureHeader, webhookSecretKey); // verifies v1 + timestamp
switch (event.getType()) {
    case "payment_intent.succeeded"      -> order.setStatus(PaymentStatus.PAYED);
    case "payment_intent.payment_failed" -> order.setStatus(PaymentStatus.FAILED);
}

The controller takes @RequestBody String payload and the headers. The Stripe SDK handles HMAC-SHA256 and timestamp tolerance. /checkout/webhook is permitAll, which is correct, because the signature is the authentication.

IR3D (Kontentt)wallet/web/PaystackWebhookController.java:66 · webhook_events table (changelog 081)

It verifies HMAC-SHA512 of the raw body against x-paystack-signature, and stores events in a webhook_events table for deduplication and an audit trail. WithdrawalReconciliationJob (every 5 minutes) also asks Paystack directly about any transfer still pending, so a lost webhook can’t strand money.

Alternatives / complements

  • IP allow-listing of provider ranges is extra defence, but providers change their IPs, so it can’t replace signatures.
  • Mutual TLS for B2B integrations.
  • Fetch-back verification: on receiving an event, call the provider’s API (GET /transaction/verify/:ref) to confirm it.
  • Respond 2xx fast. Providers retry when they get errors or timeouts. Do heavy work asynchronously (an outbox or queue).
  • Idempotent handlers. Processing charge.success twice must not credit the wallet twice (Module 6).
  • Out-of-order events. payment_failed can arrive after succeeded. Use state-machine rules: don’t move PAID back to FAILED.
  • Signing your own outbound webhooks. If SperoTek ever sends webhooks to customers, sign them the same way.

Check yourself

1. Why take the webhook body as a raw String?
2. Which prevents replay of a captured webhook?