Learn Webhooks in API

A webhook is push: the gateway (a service that receives payments) sends a POST to your URL when an event (something that happened) takes place. Polling is…

How does a shop's app know your QR payment succeeded, when the money goes to a payment gateway (a service that receives payments) and not to the shop? A few seconds after you pay, the screen already says "Payment received". Usually the shop's server isn't asking the gateway again and again. It's the gateway that tells the shop, as soon as the money arrives.

The gateway sends that news to the shop through a webhook. As soon as something happens on another server, that server sends a POST request to a URL you registered. It's like ordering food and leaving your phone number at the counter: "we'll call you when it's ready". You don't need to call the restaurant every five minutes to ask. The restaurant is the gateway, the phone number is your webhook URL, the call is the POST request, and the "okay, thanks" you say is the 200 answer.

Polling vs webhook: keep asking or get told

A Bookshop buyer pays for order 1001 (The Rainbow Troops) with a QR payment. The Bookshop server needs to know when the money arrives, that is, when the payment event (something that happened) takes place. There are two ways:

Polling (pull) Webhook (push)
Who starts the Bookshop server asks the gateway the gateway tells the Bookshop server
Requests GET /payments/1001 every 10 seconds: 360 requests an hour, nearly all answered "not yet" one POST when the payment arrives
How soon you know up to 10 seconds late as soon as the event happens
Requirement being able to send requests your server needs a public URL

So a webhook is push: whoever has the news sends it. Polling is pull: whoever needs the news fetches it, again and again. The webhook's requirement, a public URL, means your server's address can be reached from the internet. Real examples: payment gateways such as Midtrans, Xendit and Stripe report payments, and GitHub reports each time new code arrives in a repository (the place where a project's code is kept).

The Bookshop payment webhook, step by step

  1. In the gateway's dashboard, the Bookshop admin registers the URL https://api.bookshop.test/webhooks/payment. The admin then gets a secret, a key only the gateway and the Bookshop server know.
  2. The buyer pays. The gateway creates the event evt_1001 of type payment.succeeded (the payment was successful).
  3. The gateway sends this request to that URL:
POST /webhooks/payment HTTP/1.1
Host: api.bookshop.test
Content-Type: application/json
X-Timestamp: 1791429300
X-Signature: fdcf334c24445140c3df0484ff565aca246dcfd280d46a5fb1a7c4ee351c6fa2

{"id": "evt_1001", "type": "payment.succeeded", "data": {"order_id": 1001, "book_id": 1, "amount": 89000}}
  1. The Bookshop server checks the request, answers 200, then marks order 1001 as paid and lowers the stock of The Rainbow Troops from 12 to 11.

X-Timestamp and X-Signature are explained below. Each gateway names its headers its own way, and the way to prove that a delivery is genuine can differ too. There are three styles. This lesson uses the first, because it checks the whole body:

An extra safeguard for any style: before you ship the goods, ask the gateway's API for the payment status directly. Midtrans recommends this through its GET Status API.

An HMAC signature: proof the delivery is genuine

Anyone who knows your URL can send POST /webhooks/payment saying "order 1001 has been paid". If the server simply believes it, the books are sent without any payment. The check is HMAC (Hash-based Message Authentication Code), a way to calculate a signature from a text and a secret:

An attacker without the secret can't make a matching signature. Changing just one number (89000 to 1000) makes the HMAC completely different. This is the basic form, with one mistake that the next section explains:

const crypto = require("crypto");
const WEBHOOK_SECRET = "webhook-secret";

app.post("/webhooks/payment", (req, res) => {
  const signature = req.headers["x-signature"];
  const payload = JSON.stringify(req.body); // not right yet, see the next section
  const expected = crypto.createHmac("sha256", WEBHOOK_SECRET).update(payload).digest("hex");

  if (signature === expected) {
    res.status(200).json({ received: true });
  } else {
    res.status(401).json({ error: "Invalid signature" });
  }
});

On a real server the secret is kept in an environment variable (process.env.WEBHOOK_SECRET), not in the code, as in the Authentication lesson.

Compute it from the raw body

HMAC is calculated from bytes (the smallest unit of data: one plain letter takes one byte), not from meaning. The gateway signs the body exactly as it sends it: 106 bytes, with a space after every colon and comma. express.json() turns that body into an object, and JSON.stringify(req.body) writes it out again with no spaces:

sent by the gateway (106 bytes): {"id": "evt_1001", "type": "payment.succeeded", ...}
JSON.stringify       (96 bytes): {"id":"evt_1001","type":"payment.succeeded",...}

The content is the same, but the bytes differ, so the HMAC differs too: 84ddb095... from the original body and ce6291f7... from what JSON.stringify gives. As a result, the genuine webhook is refused with 401.

So compute it from the raw body: the bytes as they came, before parsing. In Express, put express.raw() on the webhook route only:

app.post("/webhooks/payment", express.raw({ type: "application/json" }), (req, res) => {
  const rawBody = req.body.toString("utf8"); // a Buffer holding the original bytes
  const expected = crypto.createHmac("sha256", process.env.WEBHOOK_SECRET).update(rawBody).digest("hex");
  const a = Buffer.from(req.headers["x-signature"] || "", "hex");
  const b = Buffer.from(expected, "hex");
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return res.status(401).json({ error: "Invalid signature" });
  }
  const event = JSON.parse(rawBody); // parsed only once it matches
  res.status(200).json({ received: true });
});

In the exercise, you use this form. Its tester sends exactly the same body as the gateway example above, with its spaces. So the signature only matches when it is computed from the raw body.

A timestamp: refuse old recordings

A signature proves a request is genuine, but not that it is new. An attacker who records one genuine webhook can send it again tomorrow, and its signature still matches. So the gateway adds X-Timestamp, the time it was sent in Unix seconds (the number of seconds since 1970). The gateway signs timestamp + "." + rawBody, not the body alone. The server refuses the request when the difference between the timestamp and the server's clock (Date.now() / 1000, in seconds) is over 300 seconds (5 minutes):

const timestamp = Number(req.headers["x-timestamp"]);
if (Math.abs(Date.now() / 1000 - timestamp) > 300) {
  return res.status(401).json({ error: "Timestamp outside the tolerance zone" });
}
const expected = crypto
  .createHmac("sha256", process.env.WEBHOOK_SECRET)
  .update(`${timestamp}.${rawBody}`)
  .digest("hex");

The timestamp is signed too, so an attacker can't swap it. When the gateway itself sends an event again (see the next section), that delivery carries a new timestamp and signature, so it isn't refused.

Answer fast, process later

The gateway only waits a short while, say 10 seconds (GitHub uses that limit). For example, the Bookshop server first builds a PDF invoice and sends an email, for 12 seconds, and only then answers. The gateway counts it as failed, even though the order was processed. So the steps are: check, answer 200, then process. Ideally the processing goes through a queue (a list of jobs that are done later).

Anything other than 2xx (a 503 because the server is down, a timeout, a 401) counts as a failed delivery, and the gateway sends it again (a retry) with longer and longer gaps. This is called exponential backoff: 1 minute, 2 minutes, 4 minutes, 8 minutes. Stripe keeps retrying for up to 3 days. So when your server recovers, the event still arrives.

The same event can arrive twice

Retries have a side effect. If your 200 gets lost or arrives late, an event you already processed is sent again. A gateway promises to deliver each event "at least once", not "exactly once". With no guard, evt_1001 is processed twice: the stock of The Rainbow Troops drops to 10, and the receipt email goes out twice.

The guard is the event id as an idempotency key, a marker for recognising a delivery you have seen. Record the ids you have processed in a Set (a JavaScript container that holds each value only once), and skip the ones that come again:

const processed = new Set(); // in a real app: a database table

if (processed.has(event.id)) {
  return res.status(200).json({ received: true, duplicate: true });
}
processed.add(event.id);

A duplicate delivery (the same event, arriving again) still gets 200, so the gateway stops resending. So the point of an idempotency key is to prevent duplicates: the same event is never processed twice. The next lesson, Idempotency, uses the same idea for requests from a client.

⚠️ Genuine webhooks refused, duplicates processed

TL;DR: A webhook is push: the gateway (a service that receives payments) sends a POST to your URL when an event (something that happened) takes place. Polling is pull: your server asks again and again. Check that a webhook is genuine with HMAC, a signature only the holder of the secret (the secret key) can make: compute createHmac("sha256", secret).update(...).digest("hex"), compare it with the x-signature header, and answer 401 when it doesn't match. Compute it from the raw body (the bytes as they came, before parsing), because JSON.stringify(req.body) changes the bytes. Refuse a request whose timestamp (the time it was sent) is more than 5 minutes away from the server's clock, so an old webhook that an attacker recorded can't be sent again. Answer 200 as soon as you can and process later. If the gateway gets no 200, it resends with backoff (longer and longer gaps), so an event can arrive twice. Record the event id (an idempotency key) so it isn't processed twice, and still answer 200 for a duplicate.

⚡ A webhook is push, polling is pull

Meaning: With polling, the Bookshop server asks the payment gateway GET /payments/1001 every 10 seconds: 360 requests an hour, nearly all answered "not yet". With a webhook, the gateway sends one POST to the Bookshop server as soon as the payment arrives. The requirement: your server needs a public URL, an address that can be reached from the internet.

⚡ HMAC from the raw body

Write:

app.post("/webhooks/payment", express.raw({ type: "application/json" }), (req, res) => {
  const rawBody = req.body.toString("utf8"); // a Buffer holding the original bytes
  const expected = crypto.createHmac("sha256", process.env.WEBHOOK_SECRET).update(rawBody).digest("hex");
  const a = Buffer.from(req.headers["x-signature"] || "", "hex");
  const b = Buffer.from(expected, "hex");
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return res.status(401).json({ error: "Invalid signature" });
  }
  const event = JSON.parse(rawBody); // parsed only once it matches
  res.status(200).json({ received: true });
});
Guess first: the gateway signs the body exactly as it sends it, with spaces. JSON.stringify(req.body) writes that body out again with no spaces. If the server computes the signature from what JSON.stringify gives, does the genuine webhook pass the check?

No. The gateway signs 106 bytes with a space after every colon and comma, while JSON.stringify writes it out again with no spaces, 96 bytes. Different bytes, a different signature, and the genuine webhook is refused with 401.

Meaning: HMAC is a signature calculated from the bytes of the body and a secret (a secret key), not from the body's meaning. So compute it from the raw body, the bytes exactly as they came, before parsing. express.raw() puts those bytes in req.body, then crypto.timingSafeEqual compares the result with the gateway's signature in the x-signature header.

⚡ The same event can arrive twice

Meaning: The gateway resends an event (the news that something happened) when it doesn't get a 200 answer quickly. So one event can arrive twice. Record the event id as an idempotency key so it isn't processed twice, and still answer 200 for a duplicate.

What you will learn