Webhook testing: catch, inspect and verify signed webhooks for free
A webhook has two sides, and both need tests. The sender has to deliver the right body, sign it, and retry sensibly when the receiver is down. The receiver has to accept genuine deliveries and turn away forged, edited and replayed ones. Neither is easy to test by pointing a real provider at localhost, so most teams test them by hand once and then hope.
This post builds both test suites with nothing but Node's built-in test runner and two free endpoints: a webhook bin that records whatever is sent to it, and a set of signed Stripe, GitHub and Shopify sample events. Every command and result below was run on 1 December 2026.
Catch a webhook in a bin
A bin is a throwaway URL that records every request it gets. Create one with a POST. No account or key is needed:
$ curl -s -X POST https://api.testingapis.com/api/webhooks/bins
{"message":"Webhook bin created","data":{"id":"8b77363694bd","name":"bin-8b7736",
"createdAt":"2026-12-01T14:44:35Z","requestCount":0,
"url":"https://api.testingapis.com/api/webhooks/8b77363694bd",
"inspectUrl":"https://api.testingapis.com/api/webhooks/bins/8b77363694bd"}}url is the address you give the sender. Anything after the bin id is recorded as a subPath, so one bin can stand in for several endpoints. Adding ?status= makes the bin answer with that code while still recording the request, which is how you play a broken receiver:
$ curl -i -X POST "https://api.testingapis.com/api/webhooks/8b77363694bd/orders/created?status=503" \
-H "Content-Type: application/json" -H "X-Event-Id: evt_1001" \
-d '{"type":"order.created","orderId":1001}'
HTTP/1.1 503 Service Unavailable
{"received":true,"binId":"8b77363694bd","requestId":"req_acafa49e5707","message":"Request captured"}Inspect what arrived
inspectUrl returns every captured request, newest first, with the body exactly as it was sent:
$ curl -s https://api.testingapis.com/api/webhooks/bins/8b77363694bd
{
"id": "8b77363694bd",
"requestCount": 1,
"requests": [
{
"id": "req_acafa49e5707",
"method": "POST",
"path": "/api/webhooks/8b77363694bd/orders/created",
"subPath": "orders/created",
"query": { "status": "503" },
"headers": {
"Accept": "*/*",
"User-Agent": "curl/8.18.0",
"Content-Type": "application/json",
"Content-Length": "39",
"x-event-id": "evt_1001"
},
"contentType": "application/json",
"bodySize": 39,
"bodyEncoding": "utf-8",
"bodyTruncated": false,
"body": "{\"type\":\"order.created\",\"orderId\":1001}",
"ip": "203.0.113.7",
"receivedAt": "2026-12-01T14:44:36.018Z"
}
]
}Look at the headers. Content-Type kept its capitals, but X-Event-Id arrived as x-event-id. A proxy on the way lower-cased it. Header names are case-insensitive, so this is allowed, and it will happen to your webhooks too. Remember it, because it breaks the first version of the test below.
| Limit | Value |
|---|---|
| Bins kept | 100; the oldest goes when a new one would exceed it |
| Requests kept per bin | 50, newest first |
| Body recorded | Up to 256 KB; bigger bodies are cut and marked bodyTruncated: true |
| Binary bodies | Stored as Base64, with bodyEncoding saying so |
To do the same in a browser, with a live list that updates as requests arrive, use the webhook tester.
Test a webhook sender
Here is a small sender: it signs the body with HMAC-SHA256, sends a Webhook-Id that stays the same across retries, and retries 5xx, 429 and network errors with exponential backoff. Your sender will look different, but it should make the same promises.
import { createHmac, randomUUID } from "node:crypto";
// The code under test: signs an event and retries 5xx and network errors.
export async function deliver(url, event, { secret, attempts = 3, backoffMs = 200 } = {}) {
const body = JSON.stringify(event);
const id = randomUUID();
for (let attempt = 1; attempt <= attempts; attempt++) {
const t = Math.floor(Date.now() / 1000);
const sig = createHmac("sha256", secret).update(`${t}.${body}`).digest("hex");
try {
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Webhook-Id": id, // same on every retry, so receivers can drop duplicates
"Webhook-Attempt": String(attempt),
"Webhook-Signature": `t=${t},v1=${sig}`,
},
body,
signal: AbortSignal.timeout(10_000),
});
if (res.ok) return { delivered: true, attempt, status: res.status };
if (res.status < 500 && res.status !== 429) return { delivered: false, attempt, status: res.status };
} catch {
// network error or timeout: retry
}
await new Promise((r) => setTimeout(r, backoffMs * 2 ** (attempt - 1)));
}
return { delivered: false, attempt: attempts };
}The test creates a fresh bin, points the sender at it, then reads the bin and checks the request itself rather than the sender's idea of what it sent:
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { createHmac } from "node:crypto";
import { deliver } from "./sender.js";
const API = "https://api.testingapis.com/api/webhooks";
const SECRET = "test-secret";
let bin;
before(async () => {
bin = (await (await fetch(`${API}/bins`, { method: "POST" })).json()).data;
});
after(() => fetch(`${API}/bins/${bin.id}`, { method: "DELETE" }));
// Proxies can change the case of header names, so look them up without caring about it.
const header = (req, name) =>
Object.entries(req.headers).find(([k]) => k.toLowerCase() === name.toLowerCase())?.[1];
async function captured(subPath) {
const { requests } = await (await fetch(bin.inspectUrl)).json();
return requests.filter((r) => r.subPath === subPath).reverse(); // oldest first
}
test("sends one signed JSON POST", async () => {
const result = await deliver(`${bin.url}/ok`, { type: "order.created", orderId: 1001 }, { secret: SECRET });
assert.deepEqual(result, { delivered: true, attempt: 1, status: 200 });
const [req] = await captured("ok");
assert.equal(req.method, "POST");
assert.equal(req.contentType, "application/json");
assert.deepEqual(JSON.parse(req.body), { type: "order.created", orderId: 1001 });
const [t, v1] = header(req, "Webhook-Signature").split(",").map((p) => p.split("=")[1]);
assert.equal(v1, createHmac("sha256", SECRET).update(`${t}.${req.body}`).digest("hex"));
});
test("retries a 503 with the same Webhook-Id, then gives up", async () => {
const result = await deliver(`${bin.url}/down?status=503`, { type: "order.created" }, { secret: SECRET });
assert.equal(result.delivered, false);
const reqs = await captured("down");
assert.equal(reqs.length, 3);
assert.deepEqual(reqs.map((r) => header(r, "Webhook-Attempt")), ["1", "2", "3"]);
assert.equal(new Set(reqs.map((r) => header(r, "Webhook-Id"))).size, 1);
const gaps = reqs.slice(1).map((r, i) => Date.parse(r.receivedAt) - Date.parse(reqs[i].receivedAt));
assert.ok(gaps[1] > gaps[0], `backoff should grow: ${gaps}`);
});
test("does not retry a 410 Gone", async () => {
const result = await deliver(`${bin.url}/gone?status=410`, { type: "order.created" }, { secret: SECRET });
assert.deepEqual(result, { delivered: false, attempt: 1, status: 410 });
assert.equal((await captured("gone")).length, 1);
});$ node --test sender.test.js
✔ sends one signed JSON POST (1597.81ms)
✔ retries a 503 with the same Webhook-Id, then gives up (2633.392ms)
✔ does not retry a 410 Gone (574.9091ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0The first version of this test looked up req.headers["Webhook-Attempt"] directly, and two of the three tests failed:
✖ sends one signed JSON POST (1536.2892ms)
TypeError: Cannot read properties of undefined (reading 'split')
✖ retries a 503 with the same Webhook-Id, then gives up (2750.011ms)
+ actual - expected
[
+ undefined,
+ undefined,
+ undefined
- '1',
- '2',
- '3'
]The headers were there, under lower-case names. That is the same thing that happens in production when a receiver reads a header from a plain object, so the header() helper is worth keeping in your receiver code as well as in the test.
What the sender tests check
| Test | The bug it catches |
|---|---|
| Body and content type as received | A framework that re-encodes the body, or sends form data instead of JSON |
| The signature matches the received bytes | Signing one string and sending another, such as pretty-printed JSON |
3 attempts on a 503, same Webhook-Id | No retry at all, or a new id per attempt, which defeats duplicate checks |
| Growing gaps between attempts | A tight retry loop that hammers a receiver that is already down |
| One attempt on a 410 | Retrying an endpoint that has told you it is gone |
Signed sample events for receiver tests
Testing a receiver needs deliveries that are correctly signed. The samples endpoint returns fixed Stripe, GitHub and Shopify events as the raw body, with each provider's signature headers, all signed with one published test secret:
$ curl -s https://api.testingapis.com/api/webhooks/samples
{
"signingSecret": "whsec_apibee_test_secret",
"samples": [
{ "provider": "stripe", "eventType": "payment_intent.succeeded", "signatureHeader": "Stripe-Signature" },
{ "provider": "github", "eventType": "push", "signatureHeader": "X-Hub-Signature-256" },
{ "provider": "shopify", "eventType": "orders/create", "signatureHeader": "X-Shopify-Hmac-Sha256" }
]
}
$ curl -s -D - https://api.testingapis.com/api/webhooks/samples/shopify
x-shopify-hmac-sha256: T4dNdfzb+PmpflD8z3HlOC4c1QbKgLkkWzvYnmhEi7k=
x-shopify-shop-domain: apibee-demo.myshopify.com
x-shopify-topic: orders/create
{"id":820982911946154508,"email":"ava.thompson@example.com","currency":"USD","total_price":"199.00", ...}Each provider signs differently, and that is where most receiver bugs come from:
| Provider | Header | What is signed | Encoding |
|---|---|---|---|
| Stripe | Stripe-Signature: t=…,v1=… | {t}.{raw body} | hex |
| GitHub | X-Hub-Signature-256: sha256=… | raw body | hex |
| Shopify | X-Shopify-Hmac-Sha256 | raw body | Base64 |
?format=envelope returns the secret, headers and body together as JSON, which is handy for copying into a fixture file.
Test a webhook receiver
The verifier takes the body as a Buffer of the bytes that arrived. Comparisons use timingSafeEqual, and Stripe deliveries older than five minutes are refused, which is what stops someone replaying a delivery they captured:
import { createHmac, timingSafeEqual } from "node:crypto";
const SECRET = process.env.WEBHOOK_SECRET ?? "whsec_apibee_test_secret";
const TOLERANCE_S = 300; // Stripe's libraries default to 5 minutes
function same(a, b) {
const x = Buffer.from(a), y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
}
// raw is a Buffer: the body exactly as it arrived, never re-serialised JSON.
export function verify(provider, headers, raw, now = Date.now() / 1000) {
const h = (name) => headers.get(name) ?? "";
switch (provider) {
case "github":
return same(h("x-hub-signature-256"),
"sha256=" + createHmac("sha256", SECRET).update(raw).digest("hex"));
case "shopify":
return same(h("x-shopify-hmac-sha256"),
createHmac("sha256", SECRET).update(raw).digest("base64"));
case "stripe": {
const parts = Object.groupBy(h("stripe-signature").split(","), (p) => p.split("=")[0]);
const t = Number(parts.t?.[0]?.split("=")[1]);
if (!t || Math.abs(now - t) > TOLERANCE_S) return false; // old or replayed delivery
const expected = createHmac("sha256", SECRET).update(`${t}.`).update(raw).digest("hex");
return (parts.v1 ?? []).some((p) => same(p.split("=")[1], expected));
}
default:
return false;
}
}The tests feed it the live samples, then change them in the ways an attacker or a careless middleware would:
import { test } from "node:test";
import assert from "node:assert/strict";
import { createHmac } from "node:crypto";
import { verify } from "./verify.js";
const SAMPLES = "https://api.testingapis.com/api/webhooks/samples";
async function sample(provider) {
const res = await fetch(`${SAMPLES}/${provider}`);
return { headers: res.headers, raw: Buffer.from(await res.arrayBuffer()) };
}
// The Stripe sample is signed at t=1721300000, so check it "as of" that moment.
const SIGNED_AT = 1721300000;
for (const provider of ["stripe", "github", "shopify"]) {
test(`${provider}: a genuine delivery verifies`, async () => {
const { headers, raw } = await sample(provider);
assert.equal(verify(provider, headers, raw, SIGNED_AT + 10), true);
});
test(`${provider}: one changed byte fails`, async () => {
const { headers, raw } = await sample(provider);
const tampered = Buffer.from(raw.toString().replace("ava.thompson", "eve.thompson"));
assert.equal(verify(provider, headers, tampered, SIGNED_AT + 10), false);
});
}
test("shopify: re-serialised JSON fails, even with no edits", async () => {
const { headers, raw } = await sample("shopify");
const reserialised = Buffer.from(JSON.stringify(JSON.parse(raw.toString())));
assert.equal(verify("shopify", headers, reserialised), false);
});
test("stripe: the same delivery an hour later is rejected", async () => {
const { headers, raw } = await sample("stripe");
assert.equal(verify("stripe", headers, raw, SIGNED_AT + 3600), false);
});
test("stripe: a fresh signature you make yourself passes the time check", async () => {
const { raw } = await sample("stripe");
const t = Math.floor(Date.now() / 1000);
const v1 = createHmac("sha256", "whsec_apibee_test_secret").update(`${t}.${raw}`).digest("hex");
const headers = new Headers({ "stripe-signature": `t=${t},v1=${v1}` });
assert.equal(verify("stripe", headers, raw), true);
});$ node --test verify.test.js
✔ stripe: a genuine delivery verifies (861.9395ms)
✔ stripe: one changed byte fails (250.3572ms)
✔ github: a genuine delivery verifies (275.3809ms)
✔ github: one changed byte fails (283.5341ms)
✔ shopify: a genuine delivery verifies (267.2435ms)
✔ shopify: one changed byte fails (275.222ms)
✔ shopify: re-serialised JSON fails, even with no edits (280.4209ms)
✔ stripe: the same delivery an hour later is rejected (268.2809ms)
✔ stripe: a fresh signature you make yourself passes the time check (305.4401ms)
ℹ tests 9
ℹ pass 9
ℹ fail 0The Stripe sample was signed at a fixed time in 2024, so a correct receiver rejects it today. The test passes now explicitly for that reason, and the last test signs a fresh copy with the test secret to exercise the real clock. Do the same for your own Stripe handler: if it accepts the sample with no clock override, it has no replay protection.
Why the raw body matters: a real example
The "re-serialised JSON fails" test is the interesting one. Nothing in the body was changed on purpose. The Shopify order id is 820982911946154508, which is bigger than the largest integer a JavaScript number holds exactly:
> JSON.stringify(JSON.parse('{"id":820982911946154508}'))
'{"id":820982911946154500}'So a receiver that parses the JSON first and then signs JSON.stringify(body) computes the HMAC over different bytes, and every Shopify delivery with a large id fails verification. In Express that is what app.use(express.json()) does to a webhook route. Mount express.raw({ type: "application/json" }) on that one route instead, verify, and parse only after the signature checks out.
The same checks in Python
Standard library only. r.read() returns the raw bytes, and hmac.compare_digest is the constant-time comparison:
import base64
import hashlib
import hmac
import json
import urllib.request
SECRET = b"whsec_apibee_test_secret"
BASE = "https://api.testingapis.com/api/webhooks/samples"
def fetch(provider):
with urllib.request.urlopen(f"{BASE}/{provider}") as r:
return r.headers, r.read() # read() gives the raw bytes
def mac(data):
return hmac.new(SECRET, data, hashlib.sha256)
def verify(provider, headers, raw):
if provider == "github":
expected = "sha256=" + mac(raw).hexdigest()
return hmac.compare_digest(headers["X-Hub-Signature-256"], expected)
if provider == "shopify":
expected = base64.b64encode(mac(raw).digest()).decode()
return hmac.compare_digest(headers["X-Shopify-Hmac-Sha256"], expected)
if provider == "stripe":
parts = dict(p.split("=", 1) for p in headers["Stripe-Signature"].split(","))
expected = mac(parts["t"].encode() + b"." + raw).hexdigest()
return hmac.compare_digest(parts["v1"], expected) # add your own timestamp check
for provider in ("stripe", "github", "shopify"):
headers, raw = fetch(provider)
print(provider, verify(provider, headers, raw))
headers, raw = fetch("shopify")
again = json.dumps(json.loads(raw)).encode()
print("shopify, re-serialised:", verify("shopify", headers, again))$ python verify_samples.py
stripe True
github True
shopify True
shopify, re-serialised: FalseIn Flask, read the body with request.get_data(); in Django, request.body; in FastAPI, await request.body(). Don't verify against request.json or a Pydantic model.
Common webhook testing problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Every signature fails in production but passes in unit tests | A JSON body parser runs before the webhook handler | Verify the raw bytes; parse afterwards |
| Only some deliveries fail verification | Large ids or unicode changed by a parse and re-stringify | Same fix; the sample with a big id reproduces it |
| A header is undefined, though the sender set it | A proxy changed the case of the name | Look headers up case-insensitively |
| Old Stripe deliveries are accepted | No timestamp check | Reject when t is more than 5 minutes from now |
| The same event is processed twice | The receiver ignores the delivery id on retries | Store the id (Webhook-Id, X-GitHub-Delivery, Stripe's event id) and skip repeats |
| The sender retries a 400 forever | It treats every non-2xx as temporary | Retry 5xx, 429 and timeouts only |
| Tests hang | A delivery with no timeout against a receiver that never answers | Use AbortSignal.timeout() on every request |
Questions
Is there a free way to test webhooks without exposing localhost?
For a sender, yes: point it at a bin, which is a public URL, and read what arrived. For a receiver on localhost, you don't need the provider at all. Fetch a signed sample and POST it to your handler with its headers, or call your verify function directly as in the tests above. You only need a tunnel when you want the real provider to call your machine.
Can I use the sample secret in my app?
Only in tests. whsec_apibee_test_secret is public, so anything signed with it proves nothing. Load the real secret from an environment variable, as verify.js does.
Is a webhook bin private?
No. Anyone with the bin id can read it, and the record includes the sender's IP address. Send test data only and delete the bin when the test finishes, as the after hook does.
Where can I learn the basics first?
The lessons on testing webhooks with a bin and verifying webhook signatures explain each part step by step. The full endpoint list is in the webhooks API reference.