Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 40 ยท Payments

Webhooks and Signature Verification

Learn how payment webhooks work in an online shop: signed events, HMAC verification, timestamp tolerance, constant-time compare, retries, ordering and replay protection.

When a customer pays, the interesting part often happens after your code has stopped listening. A bank may approve the payment seconds later, a 3-D Secure challenge may be completed in another tab, a transfer may settle the next day, or a dispute may arrive weeks afterwards. Your shop cannot keep a request open for all of that. Instead the payment provider calls you: it sends an HTTP POST to a URL you registered, describing what just happened. That call is a webhook.

Webhooks are the way your order system learns the truth about money. They are also a public URL that anyone on the internet can call. If your handler marks an order as paid because a request says so, then anyone who finds the URL can get free goods. This lesson shows how a webhook is shaped, how providers sign it, how you verify the signature, and how to cope with retries, duplicates and events arriving out of order. We build on the payment states from Authorization, Capture, Refunds and Chargebacks and the order states from The Order Lifecycle and State Machines.

Why webhooks exist

There are two ways to learn that a payment finished: ask repeatedly (polling) or be told (a webhook). Polling wastes requests and still has delays. A webhook arrives when the provider knows the outcome. Many things also happen with no browser involved at all: refunds started from the provider's dashboard, chargebacks, failed subscription renewals, bank transfers that settle later.

sequenceDiagram
    participant C as Customer browser
    participant S as Your shop
    participant P as Payment provider
    C->>S: Click "Pay"
    S->>P: Create payment
    P-->>C: Redirect for 3-D Secure
    C->>P: Completes challenge
    P-->>C: Redirect back to shop
    P->>S: POST /webhooks (payment.succeeded)
    S-->>P: 200 OK
    S->>S: Mark order paid

The browser redirect is a hint; the signed webhook is the proof.

Never treat the customer returning to your "thank you" page as proof of payment. The customer can close the tab before it loads, or type the URL by hand. Use the return page to show a friendly "we are confirming your payment" message, and let the webhook change the order status.

What an event looks like

Providers differ in names, but nearly all send a small JSON document called an event:

JSON
{
  "id": "evt_1042",
  "type": "payment.succeeded",
  "created": 1767225600,
  "data": {
    "payment_id": "pay_77",
    "order_ref": "ORD-2026-0001",
    "amount": 4999,
    "currency": "USD"
  }
}

The important fields are:

  • id: unique per event. You use it to ignore duplicates.
  • type: what happened. Handle the types you know; acknowledge and ignore the rest.
  • created: when the provider created the event. You use it for ordering.
  • data: the facts. Amounts are integer minor units, as in Representing Money Correctly.

Some providers send a "thin" event that holds only ids, so you call their API to fetch the current object. That is safe against stale data, at the price of one extra call.

Signing: proving the sender

How can you know a request really came from the provider? They and you share a secret that is never sent over the wire. The provider computes an HMAC (a keyed hash, usually HMAC-SHA256) over the exact bytes of the request body and sends the result in a header. You recompute it with your copy of the secret. If both values match, the body was produced by someone who knows the secret and was not changed on the way.

Many providers also include a timestamp in what is signed, for example the string timestamp + "." + body. We will use that format, since it also gives you replay protection. Header names and exact formats differ between providers, so always check your provider's documentation; the ideas below stay the same.

Node.js Sign a webhook body with HMAC-SHA256

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 signature is 64 hexadecimal characters (32 bytes). Changing a single character of the body gives a completely different one, so an attacker cannot edit the amount and keep the signature valid without the secret.

Verifying correctly

Verification has four steps, and each one defends against a different mistake.

  1. Use the raw body. Compute the HMAC over the exact bytes you received, before any JSON parsing. If a framework parses the JSON and you re-serialize it, spacing and key order may differ and a valid signature fails. In most web frameworks you must switch on raw-body access for the webhook route.
  2. Compare in constant time. A normal === on strings stops at the first different character. An attacker who can measure response times could, in theory, learn the correct signature one character at a time. Use crypto.timingSafeEqual (PHP has hash_equals, Python has hmac.compare_digest). It requires buffers of equal length, so check the length first.
  3. Check the timestamp. A captured request with a valid signature stays valid forever unless you limit its age. Reject requests whose timestamp differs from your clock by more than a tolerance, commonly a few minutes. This stops replay attacks.
  4. Parse only after verification. Never act on, or even trust, JSON from a request that failed the check.
Node.js A verifier with tolerance and constant-time compare

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.

Notice that the replayed request has a perfectly valid signature and is still rejected, because it is too old. Also notice that the failure responses do not say which part of the signature was wrong. Return a plain 400 or 401 to the caller and log the reason on your side.

Keep the signing secret out of your code repository and out of client-side code. Store it in an environment variable or secrets manager, use a different secret for test and live mode, and rotate it if it leaks. Many providers let two secrets be valid at the same time during a rotation, so accept either.

Acknowledge fast, work later

The provider is waiting for your response. If you take too long, it assumes delivery failed and tries again. The pattern that works:

  1. Verify the signature.
  2. Store the raw event (and its id) in a table, or put it on a queue.
  3. Return 200 immediately.
  4. Process the event in a background worker.

Return a 2xx status only once the event is safely stored. Return 4xx for a bad signature, and a 5xx if you could not store it, so the provider retries. Heavy work such as sending e-mails, creating shipping labels or calling other APIs must never run before the response.

Retries, duplicates and ordering

Delivery is at least once. Providers retry on timeouts and non-2xx answers, usually with growing delays over hours or days. That has two consequences you must design for.

Duplicates. The same event can arrive twice, even if you answered 200 the first time, because your response might be lost on the network. Record each processed event.id in a table with a unique constraint and skip events you have seen. The full pattern, including keys for your own outgoing calls, is in Idempotency and Reliable Payments.

Out-of-order delivery. Nobody promises that payment.succeeded arrives before refund.created, especially after retries. Do not assume a sequence. Two safe approaches:

  • Compare the event's created time (or a version number) with what you already stored for that object, and ignore anything older.
  • Treat the event as a prompt to fetch the current state from the provider's API and store that.

Also make your state changes follow the legal transitions of your state machine. A payment.failed that arrives after the order is already paid should be logged, not applied blindly.

Node.js Dedupe and ordering in an event handler

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 retry is ignored, the late payment.failed (created at time 90, before the success at 100) is ignored as stale, an unknown type is acknowledged without action, and the refund moves the order to its final state.

Operating webhooks

  • Register separate endpoints for test and live mode, and keep the URL hard to guess, but never rely on secrecy of the URL instead of signatures.
  • Log every delivery (id, type, result, time) so you can answer "did we get it?" when support asks.
  • Provide a replay tool. When your worker has a bug, you want to re-run stored events after the fix, which works because handlers are idempotent.
  • Monitor failures. Providers disable endpoints that fail for days. Alert on a rising error rate and on silence: a shop that normally gets events every minute and suddenly gets none has a problem.
  • Verify, then reconcile. Run a periodic job that compares your paid orders against the provider's records, to catch any event that was lost.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the signature be computed over the raw request body rather than over re-serialized JSON?

    An HMAC is computed over exact bytes. If your framework parses the JSON and you write it back out, even harmless differences produce a different signature, so verification fails or, worse, you verify something other than what was sent.
  2. 2. What does a timestamp tolerance protect against?

    Without an age limit, an attacker who records one valid request can send it again later. Signing the timestamp and rejecting old ones makes recorded requests useless after a few minutes.
  3. 3. Why use crypto.timingSafeEqual instead of === to compare signatures?

    A normal comparison returns as soon as it finds a difference, so its timing can leak information about the expected value. A constant-time comparison avoids that.
  4. 4. The provider retries events, so your handler may see evt_1042 twice. What is the right defence?

    Delivery is at least once. Deduplicating by event id makes the second delivery harmless, and your handler produces the same result no matter how many times an event arrives.
  5. 5. A customer lands on your thank-you page after paying. Should that page mark the order as paid?

    A browser redirect can be skipped, faked or never happen. Only a verified webhook or a server-to-server check with the provider is proof of payment.

Summary

  • A webhook is an HTTP call from the provider to your server; it is how you learn about payments, refunds and disputes that finish after the customer has left.
  • Anyone can call your URL, so verify an HMAC signature computed over the raw body and a timestamp with your shared secret.
  • Compare in constant time, reject timestamps outside a small tolerance, and parse the JSON only after verification.
  • Answer 2xx quickly after storing the event, then process in the background.
  • Delivery is at least once and unordered: deduplicate by event id, ignore stale events, and obey your state machine's legal transitions.
  • Keep secrets out of code, log deliveries, and reconcile with the provider regularly.

Next: Idempotency and Reliable Payments shows how to make repeated requests safe, in both directions.