Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 40 ยท Projects

Project: A Payment Webhook Handler

Build a payment webhook handler in Node.js: verify HMAC signatures with a timestamp window, dedupe events, ignore stale out-of-order events, update payment state and survive provider retries.

When a customer pays, the most important message in the whole flow is not sent by your own front end. It is sent by the payment provider, to a URL on your server, saying "this payment succeeded". That message, a webhook, decides whether you ship the goods. Anyone on the internet can send a request to that URL, so the handler has to be careful, and the provider will deliver the same event more than once, in the wrong order, and at inconvenient moments.

In this project you build the handler end to end and exercise it with a small simulated provider. It brings together the ideas from webhooks and signatures and idempotency. The code is a single Node.js file with no packages, and it runs on the site's Node runner.

What the handler must guarantee

Read this list as the specification. Each item becomes a few lines of code.

  1. Authenticity. Only accept events signed with the shared secret. Verify the signature over the raw body, exactly as received, before parsing anything.
  2. Freshness. Reject events whose signed timestamp is too old (or too far in the future), so a recorded request cannot be replayed later.
  3. Constant-time comparison. Compare signatures with crypto.timingSafeEqual, not ===, so response timing leaks nothing.
  4. Deduplication. The provider delivers at least once. Processing the same event ID twice must have the effect of processing it once.
  5. Ordering. Events can arrive out of order. A late "authorized" must not undo an earlier "captured".
  6. Correct acknowledgements. Return 2xx when the event is handled (or safely ignored), 4xx for events that will never be valid, and 5xx when something transient failed, so the provider retries.
flowchart TD
  A["Request arrives<br/>raw body + signature header"] --> B{"Signature and<br/>timestamp valid?"}
  B -- "no" --> R1["400, do not process"]
  B -- "yes" --> C{"Event id already<br/>processed?"}
  C -- "yes" --> R2["200, duplicate ignored"]
  C -- "no" --> D{"Version newer than<br/>stored payment?"}
  D -- "no" --> R3["Record id, 200,<br/>stale ignored"]
  D -- "yes" --> E["Update payment state,<br/>record event id"]
  E --> R4["200"]
  E -. "storage error" .-> R5["500, provider retries"]

The decision path of the handler: every branch ends in a deliberate status code.

The signature scheme

Many providers sign timestamp + "." + body with HMAC-SHA256 and send the result in a header such as t=1700000000,v1=<hex>. Including the timestamp in the signed text binds the signature to a moment: an attacker cannot reuse an old body with a new timestamp, because the signature would no longer match. The provider's real header format varies, so always read its documentation; this lesson uses a common shape to teach the technique.

Three pitfalls are worth stating plainly:

  • Parse after verifying. If you parse the JSON and then re-serialize it to check the signature, whitespace or key order may change and valid events fail. Keep the raw string for the check.
  • Length before timingSafeEqual. The function throws if the two buffers have different lengths, so check lengths first and treat a mismatch as a failure.
  • Secrets stay secret. Load the signing secret from configuration, never from source control. Here it is a demo value.

Try the signature on its own first. The example signs a body, verifies it, and then shows the two most common ways a valid event gets rejected or a bad one gets through.

Node.js Signing, verifying and the raw-body trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The valid event fails after a parse-and-stringify round trip, which is why the handler keeps the raw string. The tampered amount fails as it should, and a signature of the wrong length is rejected before timingSafeEqual can throw.

The handler and a simulated provider

The program below contains the signing helper, the handler (with its in-memory "database"), and six scenarios. A fake clock keeps the output the same on every run. The simulated provider re-signs on each delivery attempt, as real providers do, and retries with growing delays when it gets a 5xx.

Node.js Webhook handler: verify, dedupe, order, retry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Walk through the output. Scenario 2 is the same event delivered twice, and the second delivery is recognised by its ID. Scenario 3 carries a signature made with the wrong secret and is rejected with a 400; scenario 4 has a valid signature but a timestamp from long ago, which is what a replay attack looks like. Scenarios 5 and 6 show ordering: the captured event with version 3 arrives first and is applied, then the late version 2 is recorded as processed but changes nothing. In scenario 7 the first attempt fails with a 500 before anything is stored; the provider retries and the second attempt succeeds, so the state changes exactly once.

Design decisions worth understanding

Why record the event ID in the same step as the state change? If you record the ID first and then crash before updating the payment, the retry looks like a duplicate and the update is lost forever. If you update first and crash before recording the ID, a retry applies the update twice. In a real system, both writes go inside one database transaction, with a unique constraint on the event ID as the final safety net: if two copies of the same event are processed simultaneously, the second insert fails and the transaction rolls back.

Why 200 for stale and duplicate events? From the provider's point of view, "I received it and there is nothing more to do" is a success. A 4xx or 5xx would trigger pointless retries. Use 4xx only for requests that are permanently invalid, such as a bad signature.

Why versions, not arrival order or timestamps? Arrival order is exactly what you cannot trust. Some providers give a sequence number or a creation time per object; use whichever is monotonic for that object. If a provider offers neither, fetch the current payment from its API when an event arrives and treat the webhook only as a notification. That pattern is slower but removes the ordering problem.

Why acknowledge quickly? Providers time out after a few seconds. Do the minimum inside the request: verify, store, acknowledge. Push email, ERP updates and fulfillment into a queue and process them afterwards. That also means the queued work should be idempotent, since queues deliver at least once too.

What about the order itself? This handler updates a payment. A second step, still inside the same transaction or triggered by the stored event, moves the order from pending to paid using the transition rules from the order engine. Keep the concerns apart: the webhook layer knows about payments, the order layer knows about orders.

Hardening for production

  • Enforce a maximum body size and read the raw body before any JSON middleware touches it.
  • Log the event ID, type and outcome, never the full payload with personal data.
  • Support secret rotation by accepting two secrets for a transition period.
  • Alert on a sudden rise in signature failures; it may mean a misconfigured secret or an attack.
  • Run a periodic job that compares your payment states with the provider's records and repairs differences, because deliveries can still fail permanently.
  • Keep the endpoint separate from user sessions: no cookies, no CSRF token, nothing that depends on a logged-in user.

Extend it

  1. Add a dead_letter list: if an event fails three times, store it with the error and stop retrying.
  2. Support two valid secrets and write a test that rotates from the old one to the new one.
  3. Add a rule that a failed payment can never become captured, even with a higher version, and decide what to return.
  4. Turn the in-memory processed set into a map with timestamps and delete entries older than the provider's retry window.
  5. Port the handler into a real HTTP server on loopback and call it with fetch; the next project does something similar for checkout.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the signature be verified against the raw request body?

    The signature was computed over the exact bytes the provider sent. Any change, even harmless whitespace, makes the check fail.
  2. 2. What does the timestamp tolerance protect against?

    Because the timestamp is part of the signed text, an attacker cannot refresh an old request. The handler rejects timestamps outside the allowed window.
  3. 3. Event v4 fails with a database error before anything is stored. What should the handler return?

    A 5xx tells the provider the event was not handled and should be retried. Since no ID was recorded, the retry is processed normally.
  4. 4. A late 'authorized' event (v2) arrives after 'captured' (v3). What is the right behavior?

    The event is genuine but outdated. Acknowledge it so it is not retried, and keep the newer state.
  5. 5. Why record the event ID in the same transaction as the state change?

    Separate writes can lose an update (ID saved, state not) or apply it twice (state saved, ID not). One transaction keeps them consistent.

Summary

  • Verify an HMAC over the raw body, include the timestamp in the signed text and reject stale timestamps.
  • Compare signatures with timingSafeEqual, checking lengths first.
  • Deduplicate by event ID and record the ID together with the state change.
  • Use a per-object version to ignore outdated events; acknowledge them with 200.
  • Return 400 for permanently invalid requests, 200 for handled or harmless ones, 5xx for transient failures.
  • Acknowledge fast, queue the slow work, and reconcile with the provider periodically.

Next, wrap an HTTP interface around these ideas in Project: A Checkout API.