A webhook endpoint is a public URL that decides whether an order ships. That makes it worth a little care. Anyone on the internet can send it a request, and 402pay, like every system that delivers webhooks reliably, delivers each event at least once and not necessarily in order.
A correct handler therefore does two jobs. It proves each request came from 402pay and wasn't replayed, and it produces the same result whether an event arrives once, three times, or after a later one. This post covers both, with the exact scheme 402pay signs with and the retry schedule it follows.
What a delivery contains
Each delivery is a POST with a JSON body: the event's id, its type (such as payment.succeeded), the subject it's about, the subject as it was when the event happened in data, and created_at. Three headers carry what you need to verify it, named as the Standard Webhooks specification names them[1]:
webhook-id | The event's ID. It stays the same on every retry and resend of that event. |
|---|---|
webhook-timestamp | When this attempt was signed, in seconds since the Unix epoch. |
webhook-signature | One or more signatures, space separated, each written as v1, followed by a base64 value. |
Because 402pay follows that specification, any library that implements it can verify a delivery. The scheme is also small enough to write yourself, which is what the next section does.
Verify the signature on the raw body
The signature is an HMAC-SHA256[2] of the string {id}.{timestamp}.{body}, keyed with the endpoint's signing secret: the part after whsec_, base64-decoded. To check one:
- Read the request body as raw bytes. Don't let a framework parse it into JSON first.
- Refuse the delivery if its timestamp is more than five minutes from your server's clock.
- Compute the HMAC over the ID, the timestamp, and the raw body, joined by periods, and base64 it.
- Compare it with each
v1entry in the signature header, in constant time.
import crypto from "node:crypto"; // secret is the endpoint's whsec_ value; body is the raw request body.export function verifyWebhook(secret, headers, body) { const id = String(headers["webhook-id"] ?? ""); const timestamp = String(headers["webhook-timestamp"] ?? ""); const signatures = String(headers["webhook-signature"] ?? ""); // Refuse replays: the delivery must be less than five minutes old. const sent = Number(timestamp); if (!Number.isInteger(sent) || Math.abs(Date.now() / 1000 - sent) > 300) return false; const key = Buffer.from(secret.slice("whsec_".length), "base64"); const expected = crypto .createHmac("sha256", key) .update(`${id}.${timestamp}.${body}`) .digest("base64"); // During a rotation the header carries one signature per secret. return signatures.split(" ").some((entry) => { const [version, signature = ""] = entry.split(","); return ( version === "v1" && signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) ); });}The first step is where most broken integrations fail. A framework that parses JSON and then serializes it again can change whitespace or key order, and the signature covers the exact bytes402pay sent. If every signature fails, that is almost always the reason. If only some fail, check your server's clock.
The timestamp check is what stops a replay. A valid delivery that someone captured stays valid forever as far as the HMAC is concerned; refusing old timestamps limits how long it can be reused. A constant-time comparison stops an attacker from learning the expected signature one byte at a time from how long your server takes to say no.
Rotating a secret without dropping deliveries
An endpoint's secret is shown once, when you create the endpoint or rotate it. Rotating doesn't cut over instantly: for 24 hours, every delivery carries two signatures, one from the new secret and one from the old, separated by a space. That is why the code above accepts any matching v1 entry rather than only the first.
The practical sequence is to rotate, deploy the new secret, and confirm deliveries still verify, all inside that window. A server that is still on the old secret keeps working until the window ends, so a deploy that takes an hour longer than planned costs nothing.
Answer quickly, then do the work
402pay counts a delivery as delivered when your endpoint answers with any 2xx status within 15 seconds. Anything else is a failure: a 4xx or 5xx, a timeout, and also a redirect, since deliveries don't follow them. Point the endpoint at its final URL.
The reliable pattern is to verify, store the event, answer, and process it afterwards. Sending an email, calling an inventory system, or provisioning an account inside the request is how a handler that works in testing starts timing out under load, and every timeout becomes a retry of an event you may already have half processed.


Return 2xx only once the event is stored
If you answer before writing the event anywhere durable and your process dies, the event is gone on your side and 402pay has no reason to send it again.
How retries work
A delivery that fails is tried again, 8 attempts in all. The waits between them are 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, and 10 hours, about 28 hours from the first attempt to the last. That covers a bad deploy, a certificate that expired overnight, or a database migration that ran long.
After the last attempt the delivery is marked failed, and you can resend it from the dashboard or with the resend endpoint. A resend is signed again with a fresh timestamp but keeps the same webhook-id, so your deduplication still recognizes it. Two endpoint settings change the picture: an endpoint that is turned off drops any retry that comes due while it's off, and deleting an endpoint removes its pending retries.
The deliveries view records every attempt with the request 402pay sent and the status and body your server answered with, which is usually the fastest way to see why a delivery failed.
Duplicates and events out of order
Retries mean the same event can reach you more than once: your server stored it and answered, but the answer was lost or arrived after the timeout. Each delivery also runs on its own schedule, so a retried payment.created can land after payment.succeeded for the same payment. Two rules handle both cases:
- Record each event's ID under a unique constraint and skip any ID you've already processed.
- Treat an event as a prompt to look, not as the state itself. Its
datais the payment as it was when the event happened; read the payment again before you act on it.
app.post("/webhooks/402pay", express.raw({ type: "application/json" }), async (req, res) => { const body = req.body.toString("utf8"); if (!verifyWebhook(process.env.PAY402_WEBHOOK_SECRET, req.headers, body)) { return res.sendStatus(400); } const event = JSON.parse(body); if (event.test) return res.sendStatus(200); // A unique index on event_id turns a duplicate into a no-op. const isNew = await db.webhookEvents.insertIfAbsent({ event_id: event.id, type: event.type, body }); res.sendStatus(200); if (isNew) await queue.enqueue("process-402pay-event", { eventId: event.id });}); // In the worker: read the payment as it is now, then fulfill once.async function processEvent({ eventId }) { const event = await db.webhookEvents.find(eventId); if (event.type !== "payment.succeeded") return; const response = await fetch(`https://dash.402pay.co/api/v1/payments/${event.subject.id}`, { headers: { Authorization: `Bearer ${process.env.PAY402_SECRET_KEY}` }, }); const { data: payment } = await response.json(); if (payment.status === "succeeded") await orders.fulfillOnce(payment.reference, payment.id);}The last line carries the other half of the job. Even with deduplication by event ID, fulfillment itself should be idempotent: key it on your own order reference or the payment's ID, so two different events about the same payment can never ship the order twice. Our post on idempotency keys covers the same idea from the other direction, for requests you send to 402pay.
Deduplicate on the event. Fulfill on the payment.
Test deliveries
From the dashboard or the API you can send an endpoint a signed sample of any event type it subscribes to. Test deliveries are signed exactly like real ones, so they exercise your verification. They also carry test: true and a made-up subject, and they go out once without retries. Check for test before you act, as the handler above does, so a sample event never fulfills a real order.
The webhooks guide has the full event fields and a troubleshooting table, and the event catalog lists every type and the order a payment's events usually arrive in.
Common questions
- With the Standard Webhooks scheme: an HMAC-SHA256 of the event ID, the timestamp, and the raw body, joined by periods, keyed with the base64-decoded part of the endpoint's secret after whsec_. The result is base64 encoded and sent in the webhook-signature header after v1,.
- Almost always because the body was parsed and serialized again before verifying. The signature covers the exact bytes 402pay sent, so verify the raw body first and parse it afterwards.
- A delivery gets 8 attempts in all, spread over about 28 hours. After that it's marked failed and can be resent from the dashboard or the API.
- Yes. Delivery is at least once, so record each webhook-id and skip any you've already processed. Retries and resends of an event keep the same ID.
- For 24 hours after a rotation, each delivery is signed with both the new and the old secret, so a server on either one keeps verifying while you deploy.
References
- [1]Standard Webhooks. Standard Webhooks.
- [2]RFC 2104: HMAC, Keyed-Hashing for Message Authentication. IETF.
See what 402pay can do for you.
Discover how 402pay helps your business accept any card and get paid in crypto, straight to a wallet you control.







