Insights · Software engineering

Payment webhooks that survive retries: HMAC, idempotency and integer kobo

Payment providers retry webhooks. Customers pay twice, pay part, or pay without the reference. A payment system is mostly the code that handles those cases correctly.

In our quote-to-pay system, approved quotes go out with Paystack payment links, and payments come back as webhooks. These are the four safeguards between a webhook arriving and a customer being marked as paid.

1. Verify the signature before anything else

Anyone can send a request to your webhook URL. Paystack signs each webhook with an HMAC of the raw request body, sent in the x-paystack-signature header. Recompute it with your secret key and compare in constant time. Unsigned or mismatched requests are refused before any parsing.

const expected = crypto.createHmac("sha512", SECRET).update(rawBody).digest("hex");
const ok = expected.length === sig.length &&
  crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig));
if (!ok) return res.status(401).end();

Note the raw body: re-serialising parsed JSON can change bytes and break the signature.

2. Make ingestion idempotent

The same event can arrive more than once. Record each payment under its unique provider reference (for example with a uniqueness constraint), so a second delivery is recognised and acknowledged without being applied twice.

3. Lock the row for concurrent payments

Two payments for the same quote can land at the same moment, for example a customer who pays the deposit and the balance back to back. Without a lock, both read "₦0 paid so far" and both write their own total. Inside one transaction, lock the quote row (SELECT ... FOR UPDATE), add the payment, recompute the balance, then commit.

4. Store money as integers

Floating point can't represent most decimal amounts exactly, so totals drift by fractions of a kobo and stop matching. Store every amount in the smallest unit (kobo for naira) as an integer, and only format it for display.

And when a payment can't be matched?

Some customers pay without the reference. Those payments go to an unmatched queue for a person to assign, rather than being matched to the most likely quote. A wrong automatic match is worse than a short wait.

How we know it holds

The tests cover the ugly cases on purpose: an unsigned webhook is refused, a signed one is applied once, a repeated delivery changes nothing, and concurrent payments add up correctly. Under load, a single instance handled 358 requests per second with a median latency of 263 ms and a p99 of 596 ms.

Building something that moves money? Our custom software practice builds payments the way this article describes, and our QA practice tests them. Or book a free 30-minute call.