Skip to main content

Webhook Delivery and Signature Verification

Last Updated: 2026-12-01 Status: Complete

A webhook is an HTTP callback that tells another system something happened. A PayFac is on both sides: it sends webhooks to its platforms and merchants, and it receives them from processors. This page shows how to design reliable delivery and webhook signature verification for both directions, so you can build a delivery worker, a signing scheme and a safe receiving endpoint.

Quick Reference​

SideMust do
SendingFed by the outbox; at-least-once; timeout; exponential backoff with jitter; per-endpoint secret; delivery log; SSRF protection
SigningHMAC-SHA256 over id, timestamp and raw payload; timestamp tolerance; secret rotation with overlap
ReceivingVerify on the raw body; constant-time compare; check timestamp; persist; return 2xx fast; process asynchronously; dedupe
RecoveryFetch current state by API; reconcile for missed events
Time-Sensitive

Vendor retry windows, tolerances and response rules change. Values below come from vendor documentation as of 2026-12-01; confirm in the current docs and see Key Numbers.

Part 1: Sending Webhooks to Platforms and Merchants​

What Does the Delivery Pipeline Look Like?​

The worker is fed from the outbox described in Event-Driven Payment Architecture: one event fans out to one delivery row per matching endpoint, so one slow endpoint never blocks another.

How Should Endpoints Be Registered?​

  • Event-type filters: the endpoint chooses which types it receives.
  • Multiple endpoints per account, each with its own state.
  • Per-endpoint secret, shown once, stored encrypted (see Sensitive Data).
  • Rotation with overlap: issue a new secret, sign with both for a window, then retire the old one. Stripe documents that rolled secrets can stay valid for up to seven days.
  • HTTPS only, and validate the URL at registration and again at every delivery.

Retries, Timeouts and Disabling​

At-least-once delivery means a retry whenever the receiver does not return 2xx in time. Standard Webhooks suggests a 15 to 30 second timeout, treats 2xx as success, 3xx as failure, and 410 as a signal to disable the endpoint.

Reference points from vendors:

SourceRetry behavior
StripeLive mode: Up to three days, with exponential backoff
AdyenFailed webhooks are queued and retried for up to 30 days
Standard WebhooksMulti-day retries with exponential backoff and jitter; its example runs about three days
Svix (vendor)Immediately, then 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h (8 attempts); endpoints failing for 5 days are disabled

An illustrative schedule for your own design (tune it from your merchants' real outage data):

AttemptDelay before attempt
1Immediate
2About 30 s
3About 2 min
4About 10 min
5About 1 h
6About 6 h
7 and laterAbout 12 h, until the total window ends

Add random jitter of, say, plus or minus 20 percent so a recovering endpoint is not hit by every queued retry at once. After the window, mark the delivery failed and notify the owner; disable the endpoint after sustained failure or on 410. Provide a delivery log (request, response status, latency, attempt number) visible to the customer, and a manual resend button that re-sends the same event id.

How Do You Prevent SSRF From Customer-Supplied URLs?​

Your delivery worker makes requests to URLs that customers control, which is a textbook server-side request forgery risk (OWASP API Security Top 10:2023, API7). Controls:

  1. Resolve the hostname yourself, validate the IP, then connect to that IP, so a DNS answer cannot change between check and use (DNS rebinding). Keep TLS certificate verification and SNI against the original hostname, not the IP.
  2. Block loopback, private (RFC 1918), link-local (including the cloud metadata address range) and equivalent IPv6 ranges, plus IPv4-mapped IPv6 addresses and 0.0.0.0.
  3. Do not follow redirects; treat 3xx as failure.
  4. Allow only HTTPS and expected ports; cap response size and time.
  5. Run the worker in a network segment with egress controls, and never send internal credentials in webhook requests.

Thin or Full Payloads?​

Stripe now recommends thin events for new integrations: a small payload, with the receiver fetching details by API. Thin payloads limit data exposure and avoid stale state; full payloads save a round trip. Either way, keep payloads small and free of PAN, SAD and raw PII.

{
"id": "evt_01J_[example]",
"type": "payment.captured",
"created": "2026-12-01T10:15:30Z",
"api_version": "2026-11-01",
"data": {
"payment_id": "pay_01J_[example]",
"merchant_id": "mer_[example]",
"amount": 4999,
"currency": "USD",
"status": "captured",
"payment_method": { "token": "pm_tok_[redacted]", "brand": "visa", "last4": "1111" },
"captured_at": "2026-12-01T10:15:29Z"
}
}

How Do You Sign Webhooks?​

Standard Webhooks (a community specification) defines three headers: webhook-id (unique, unchanged across retries), webhook-timestamp (Unix seconds) and webhook-signature (a space-delimited list). The symmetric scheme signs id.timestamp.payload with HMAC-SHA256 and sends v1,<base64 signature>, with whsec_-prefixed base64 secrets. An asymmetric option, v2a using ed25519, lets receivers verify without holding a secret the sender could be blamed for leaking. Stripe's format is Stripe-Signature: t=<timestamp>,v1=<hex HMAC> over timestamp.raw_body, and each retry gets a new timestamp and signature.

import { createHmac } from 'node:crypto';

export function signWebhook(secret: string, id: string, body: string, now = Date.now()) {
const timestamp = Math.floor(now / 1000).toString();
const key = Buffer.from(secret.replace('whsec_', ''), 'base64');
const signature = createHmac('sha256', key).update(`${id}.${timestamp}.${body}`).digest('base64');
return {
'webhook-id': id,
'webhook-timestamp': timestamp,
'webhook-signature': `v1,${signature}`, // add a second "v1,..." during rotation
};
}

The timestamp defends against replay: receivers reject messages outside a tolerance window. Standard Webhooks requires a tolerance but sets no number; Stripe's libraries use Five minutes by default in Stripe’s official libraries by default. Choose yours and document it.

Part 2: Receiving Webhooks From Processors​

What Must the Receiving Endpoint Do?​

  1. Verify the signature on the raw body. Re-serialized JSON differs byte-wise and will fail verification.
  2. Compare in constant time (crypto.timingSafeEqual) against every candidate signature.
  3. Check the timestamp against your tolerance.
  4. Persist the raw event, then acknowledge. Return 2xx quickly and process asynchronously. Adyen's guidance is any 2xx, 202 with an empty body recommended, within 10 seconds; legacy Adyen webhooks still expect the [accepted] body until migrated.
  5. Deduplicate on the event id. For Stripe, where two Event objects can occasionally be generated for one occurrence, also consider object id plus event type.
  6. Handle disorder: Stripe documents no ordering guarantee, and Adyen's docs do not state ordering or duplicate guarantees, so design for both. Fetch the current object state by API instead of trusting event order.
  7. Reconcile for missed events by listing recent events through the API; Stripe documents 30 days through the Events API. Beyond that window, reconcile against settlement files (Reconciliation).

Adyen signs standard webhooks with HMAC-SHA256 in additionalData.hmacSignature over a fixed list of fields, and other webhook types sign the raw body in the hmacsignature header. Use Adyen's library validator rather than rebuilding the signing string; keys differ between test and live, and the previous key should be accepted briefly after rotation.

NestJS Example​

Enable raw body capture once:

const app = await NestFactory.create(AppModule, { rawBody: true });
import { createHmac, timingSafeEqual } from 'node:crypto';
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';

@Injectable()
export class WebhookVerifier {
constructor(private readonly secrets: ProcessorSecretProvider /* from your vault */) {}

verify(rawBody: Buffer, header: string | undefined, toleranceSeconds: number): void {
if (!header) throw new UnauthorizedException();
const parts = header.split(',').map((p) => p.split('=') as [string, string]);
const t = parts.find(([k]) => k === 't')?.[1];
const candidates = parts.filter(([k]) => k === 'v1').map(([, v]) => v);
if (!t || candidates.length === 0) throw new UnauthorizedException();

const ts = Number(t);
if (!Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) > toleranceSeconds) {
throw new UnauthorizedException(); // a non-numeric timestamp must fail, not pass
}

const payload = Buffer.concat([Buffer.from(`${t}.`), rawBody]);
const ok = this.secrets.activeSecrets().some((secret) => {
const expected = createHmac('sha256', secret).update(payload).digest();
return candidates.some((c) => {
const got = Buffer.from(c, 'hex');
return got.length === expected.length && timingSafeEqual(got, expected);
});
});
if (!ok) throw new UnauthorizedException();
}
}
@Controller('webhooks')
export class ProcessorWebhookController {
constructor(
private readonly verifier: WebhookVerifier,
private readonly inbound: InboundEventService,
) {}

@Post('processor')
@HttpCode(202)
async receive(@Req() req: RawBodyRequest<Request>, @Headers('stripe-signature') sig?: string) {
if (!req.rawBody) throw new BadRequestException();
this.verifier.verify(req.rawBody, sig, 300); // tolerance from your own policy
// INSERT ... ON CONFLICT (provider, event_id) DO NOTHING, then enqueue for async processing.
await this.inbound.persistAndEnqueue('processor-a', req.rawBody);
}
}

Use the vendor's SDK verifier in production where one exists; the code above shows what it does. Secrets come from a vault, never from source code (Secrets Management). Persisting the raw event gives you an audit record and the ability to replay after a bug. Keep the raw payloads under the same access controls as other sensitive records.

How Do You Investigate Duplicate Webhooks?​

A platform reports duplicate events. Duplicates are expected under at-least-once delivery, so the question is whether they are normal or a defect.

Cause (sender side)How to confirmFix
Receiver returned 2xx slowly or timed out after doing the workDelivery log shows an attempt with a timeout, then a successAcknowledge before processing; shorten work in the handler
Same event sent to multiple registered endpointsTwo endpoints in the account match the event typeShow endpoint list; let the customer remove duplicates
Two events generated for one occurrenceDifferent event ids, same object id and typeDedupe on object id plus type where the sender documents this
Manual resend or replay toolDelivery log shows manual actionSame event id: consumer dedupe handles it
Retry after a network failure on the responseSame event id, different attempt numbersExpected; dedupe on id

Sender-side prevention: keep webhook-id identical across retries, log every attempt, and document that delivery is at-least-once. Receiver-side prevention: a unique constraint on (provider, event_id), and an idempotent handler as in Event-Driven Payment Architecture. You cannot make duplicates impossible; you can make them harmless.

References​

Share: