Webhook signature verification and replay protection
A webhook is a public address on the internet that receives notifications, and anyone who knows that address can send it whatever they like.
In a system handling payments the stakes are concrete: whoever knows the address can tell your system an invoice was paid.
Layer one: the signature
Every notification the provider sends carries a signature, computed over the message content with a secret that only the two of you hold.
Your system runs the same computation over what actually arrived. A match means the message came from the provider and was not modified on the way. On a mismatch, you reject and move on.
Trap one: the order of operations
Compute the signature over the raw body exactly as it arrived, before any parsing or re-serialisation. Parse the JSON and serialise it again and you have already changed field order and whitespace; the signature stops matching and you begin rejecting valid messages.
Trap two: the comparison
Compare the two signatures with a comparison whose running time does not depend on where the first difference sits. An ordinary comparison returns at the first differing character, and that exit time leaks information.
Layer two: replay protection
A valid signature stays valid forever, so anyone who captured one genuine message can resend it a hundred times.
The fix: every notification carries a unique identifier, and your system stores each one it processes. When an identifier that is already in storage shows up again, the notification is ignored.
That constraint belongs in the database, not in the code: a unique index on the identifier. Even when two copies land at the same instant, the database refuses the second insert. A duplicate check written in application code can wave both through.
What I learned about retries
Providers resend a notification whenever they fail to get a successful response, so your system will see the same notification several times during perfectly normal operation. Deduplication has to hold for the accounting to stay correct, whether or not an attacker ever shows up.
Related reading
Tell me what you want to build. Your first 15 minutes of consulting are free.
Book a consultation