LearnFrenzy
Sign in Take a free test

Versioning, Webhooks and Alternatives · Lesson 24 of 30

Webhooks: Building and Verifying Signed Webhooks

5 min read Updated Nov 8, 2026 Saurabh Samir

A webhook is an API call in reverse: instead of your app asking "has the payment completed yet?", the payment provider calls your URL when it happens. Stripe, Razorpay, GitHub, Shopify, Twilio and Salesforce all use them. Because anyone on the internet can POST to your webhook URL, every webhook must be verified – and because networks fail, handlers must cope with duplicates and retries.

In this lesson

  • How webhooks work
  • Signing with HMAC-SHA256
  • Verifying signatures and timestamps – shown live
  • Retries and idempotent handlers

A signed webhook delivery

  1. Eventpayment.succeeded happens at the provider
  2. Signsignature = HMAC-SHA256(secret, timestamp + "." + raw body)
  3. DeliverPOST to your URL with the body, timestamp and signature headers
  4. Verifyyou recompute the HMAC with the shared secret and compare
  5. Acknowledgereturn 2xx quickly; do heavy work in the background

The receiver

// server.js
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';

const app = express();
const SECRET = 'whsec_demo_shared_secret';          // from the provider's dashboard, kept in a secret store
const TOLERANCE_SECONDS = 300;
const processed = new Set();                        // event ids already handled (a DB table in production)

// IMPORTANT: verify against the raw bytes, not re-serialised JSON
app.post('/webhooks/payments', express.raw({ type: 'application/json' }), (req, res) => {
  const timestamp = Number(req.get('X-Webhook-Timestamp'));
  const signature = req.get('X-Webhook-Signature') ?? '';

  if (!timestamp || Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE_SECONDS) {
    return res.status(400).json({ error: 'Timestamp missing or too old (possible replay)' });
  }
  const expected = createHmac('sha256', SECRET).update(`${timestamp}.${req.body}`).digest('hex');
  const valid = signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
  if (!valid) return res.status(401).json({ error: 'Invalid signature' });

  const event = JSON.parse(req.body);
  if (processed.has(event.id)) {
    return res.status(200).json({ received: true, duplicate: true });   // already handled: acknowledge, do nothing
  }
  processed.add(event.id);
  console.log(`handled ${event.type} for order ${event.data.orderId}`);  // enqueue real work here
  res.status(200).json({ received: true });
});

app.listen(process.env.PORT ?? 3000);

The sender (what the provider does)

// client.js
import { createHmac } from 'node:crypto';

const URL = 'http://localhost:3000/webhooks/payments';
const SECRET = 'whsec_demo_shared_secret';

async function deliver(event, { secret = SECRET, timestamp = Math.floor(Date.now() / 1000), tamper = false } = {}) {
  const body = JSON.stringify(event);
  const signature = createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');
  const sent = tamper ? body.replace('"amount":249900', '"amount":1') : body;     // attacker edits the body
  const res = await fetch(URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Webhook-Timestamp': String(timestamp), 'X-Webhook-Signature': signature },
    body: sent,
  });
  return `${res.status} ${JSON.stringify(await res.json())}`;
}

const event = { id: 'evt_9001', type: 'payment.succeeded', data: { orderId: 'ord_77', amount: 249900 } };

console.log('genuine:     ', await deliver(event));
console.log('retry (dup): ', await deliver(event));
console.log('tampered:    ', await deliver({ ...event, id: 'evt_9002' }, { tamper: true }));
console.log('wrong secret:', await deliver({ ...event, id: 'evt_9003' }, { secret: 'guessed' }));
console.log('replayed old:', await deliver({ ...event, id: 'evt_9004' }, { timestamp: Math.floor(Date.now() / 1000) - 3600 }));

Real output of five deliveries, and the receiver's log

$ node client.js
genuine:      200 {"received":true}
retry (dup):  200 {"received":true,"duplicate":true}
tampered:     401 {"error":"Invalid signature"}
wrong secret: 401 {"error":"Invalid signature"}
replayed old: 400 {"error":"Timestamp missing or too old (possible replay)"}

Server log:
  handled payment.succeeded for order ord_77
  • Only the genuine delivery was processed – once. The retry was acknowledged with 200 but not processed again.
  • Changing a single value in the body broke the signature; so did a guessed secret.
  • A correctly signed but hour-old request was rejected: the timestamp is part of the signed data, so an attacker who captured a request can't replay it later.
  • Verify against the raw body (express.raw): parsing and re-stringifying JSON can change spacing or key order and break the signature.

If you send webhooks

  • Sign every delivery (HMAC with a per-endpoint secret), include a timestamp and a unique event id.
  • Retry failures with exponential backoff for hours or days; show delivery logs and a "resend" button.
  • Keep payloads small – an event type and ids – and let receivers fetch full details from your API.
  • Expect receivers to be slow or down; never block your own work on webhook delivery.
  • Deliveries can arrive out of order – include timestamps or versions so receivers can ignore stale events.

Practice

Try it yourself

  1. Your webhook handler takes 40 seconds to generate an invoice PDF, and the provider times out after 10 seconds and retries. What goes wrong, and how do you fix it?

    Show answer

    The provider treats each attempt as failed and retries, so the work may run several times and the provider may eventually disable your endpoint. Verify, record the event id, put a job on a queue and return 200 immediately; a worker generates the PDF. The event-id check makes retries harmless.

Quick check

Why include a timestamp in the signed data?

To stop captured requests being replayed later.

Why compare signatures with timingSafeEqual?

A normal comparison can leak timing information that helps attackers guess signatures.

What should a handler do with a duplicate event id?

Return 2xx and skip processing.

Summary

  • Webhooks push events to your URL; anyone can call it, so verify every request.
  • Check an HMAC over timestamp + raw body, in constant time, within a time window.
  • Respond fast, queue the work, and make handlers idempotent by event id.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links