Belajar
← All lessons

How webhooks work

Poll for a payment, then get a webhook

Customer
Payments
Your server

poll.js

// polling: ask on a timer, mostly for nothingsetInterval(async () => {  const res = await fetch(`${API}/payments?since=${last}`);  const payments = await res.json();  payments.forEach(markPaid);}, 30_000);

server.js

// webhooks: register your URL onceconst { secret } = await provider.webhookEndpoints.create({  url: "https://shop.test/webhooks",  events: ["payment.succeeded"],}); // then the provider calls youapp.post("/webhooks", async (req, res) => {  const event = verify(req, secret);  await queue.add(event);  res.sendStatus(200);});

Check the signature so you know it's really them

The provider sends
its secretwhsec_42, kept, never sent
header
Secret on your serverBody on arrivalUntouchedEditedReformatted
Raw body your server got
in header
you compute

Check the raw bytes first. Parse the JSON after

provider.js

// provider: sign the exact bytes it sendsconst t = Math.floor(Date.now() / 1000);const v1 = hmacSha256(SECRET, `${t}.${body}`);headers["Webhook-Signature"] = `t=${t},v1=${v1}`;

server.js

// your server: use the raw body, not parsed JSONconst { t, v1 } = parseHeader(req.get("Webhook-Signature"));const expected = hmacSha256(MY_SECRET, `${t}.${rawBody}`);if (!timingSafeEqual(v1, expected)) {  return res.status(400).send("bad signature");}const event = JSON.parse(rawBody);

Deliveries fail and get retried so handle each event once

Payments
Your server
Database

provider.js

// provider: retry until it gets a 2xxfor (const delay of [0, 60, 300, 1800]) {  await sleep(delay * 1000);  const res = await post(url, event, { timeout: 10_000 });  if (res.ok) break;}

server.js

app.post("/webhooks", async (req, res) => {  const event = verify(req, secret);  if (await db.seen(event.id)) {    return res.sendStatus(200);  }  await fulfillOrder(event);  await db.markSeen(event.id);  res.sendStatus(200);});

Old requests get turned away a timestamp stops replays

Arrives after signing0 min
Timestamp in the headerAs signedChanged to now

Inside the window, the event id check from above catches a repeat

server.js

const { t, v1 } = parseHeader(req.get("Webhook-Signature"));const expected = hmacSha256(SECRET, `${t}.${rawBody}`);if (!timingSafeEqual(v1, expected)) {  return res.status(400).send("bad signature");}const age = Math.floor(Date.now() / 1000) - t;if (age > 300) {  return res.status(400).send("too old");}handle(JSON.parse(rawBody));

Topics

Next: How WebSockets work

Open lesson