How do you verify a payment webhook signature and avoid fulfilling an order twice?

Tested verifiers in Node, Python and PHP, the mistakes behind failed signatures, and the four kinds of duplicate that can make one sale fulfill twice.

By
Railbed
Published
Reading time
13 min
A sealing desk where a screw press brings a seal down on an envelope's wax, beside a hand tally counter on a plinth, two hand seals, a quill in an inkwell and a tied bundle of envelopes

Press the card to run an example sale.

To verify a payment webhook, recompute an HMAC-SHA256 of the signed timestamp and the raw request body with your endpoint secret, compare it in constant time with every signature in the header, and reject old timestamps. To avoid fulfilling twice, save each event id under a unique constraint and grant each order once.

This page works through both halves on Railbed's webhooks, whose Railbed-Signature header uses the common t=…,v1=… layout. The verifiers below, in Node.js, Python and PHP, were run on 23 November 2026 against the test vector Railbed publishes. The second half maps the four different ways one sale can reach your code twice, and the key that stops each.

What a valid signature proves, and what it doesn't

A verified Railbed signature proves three things: the request was signed with your endpoint's secret, the body is byte for byte what was signed, and it was signed within the last five minutes. Svix's Webhook security 101 puts the division of labor plainly: "An HMAC-SHA256 signature over the raw body stops the first two [forged and tampered requests], a signed timestamp plus deduplication stops replays, constant-time comparison stops timing leaks."

What a signature cannot tell you is whether you have already acted on this event. Railbed's webhooks are delivered at least once, every retry carries "the same event id and body, with a fresh signature and timestamp", and a captured delivery replayed inside the five-minute window still verifies. Nor does the event's payload decide what to ship: it is a snapshot, while GET /v1/payments/:id is, in Railbed's words, "always current". So a correct receiver runs three checks in order: signature, then deduplication, then status.

Three steps: join t, a full stop and the raw body; sign with HMAC-SHA256 keyed with the whsec_ secret; compare with every v1 in constant time. Below, ticks for sent by Railbed with the body unchanged and signed in the last five minutes, and no tick for new to you. The signature answers who sent it and when; whether you have seen it before is your database's job.

How Railbed signs a delivery

Railbed signs each delivery attempt by computing the hex HMAC-SHA256 of the string {t}.{raw body}, keyed with the endpoint's whole signing secret as text, and putting the result in a Railbed-Signature header. An example from the signature docs:

Railbed-Signature: t=1790381342,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd

The table below lists each part of the scheme and the rule your code has to follow for it.

Part What it is The rule
t When this attempt was signed, Unix seconds Reject if more than 300 seconds from your clock
v1 64 lowercase hex characters One normally, two for 24 hours after a roll; accept if any matches
Secret whsec_ plus 43 URL-safe characters, 49 in all The whole value, prefix included, is the HMAC key
Body The exact bytes sent Verify before any JSON parsing

If you have written a Stripe verifier, most of this will look familiar. Stripe's endpoint docs also describe a header with t and "at least one v1 entry", and its libraries default to "a tolerance of 5 minutes" according to its webhooks guide. Two differences matter when you port code. Stripe tells integrations they "must accept unknown entries" (it adds v0 and unsigned debug fields), whereas Railbed's documented parser requires exactly one t followed only by v1 values. And Stripe lets you delay an old secret's expiry "for up to 7 days", where Railbed's overlap is 24 hours. The Standard Webhooks specification is a different design again: three headers (webhook-id, webhook-timestamp, webhook-signature) and base64 signatures in a space-delimited list.

Verify a delivery in four steps

Railbed's docs give the procedure as four steps, and the code below follows them in this order:

  1. Parse the header. Require one t followed by one or more v1=<64 hex characters>; reject anything else, including a missing header.
  2. Check the time. Reject when t is more than five minutes from your clock.
  3. Compute. HMAC-SHA256 over t, a full stop and the raw body, keyed with your secret, hex-encoded.
  4. Compare. Compare with each v1 in constant time, and accept if any one matches.

The three functions below follow those steps. Each returned true for Railbed's test vector (with the tolerance widened, because the vector's timestamp is in the past), false when one byte of the body changed, and true for either secret of a header carrying two v1 values. We ran them on Node.js 22, Python 3 and PHP 8.3.

import crypto from 'node:crypto';

const HEADER = /^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$/;

export function verifyRailbedSignature(rawBody, header, secret, toleranceSeconds = 300) {
  const m = HEADER.exec(header ?? '');
  if (!m) return false; // missing or malformed
  if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSeconds) return false;
  const expected = Buffer.from(
    crypto.createHmac('sha256', secret).update(`${m[1]}.${rawBody}`).digest('hex'),
  );
  // Check every v1: for 24 hours after a roll there are two.
  return m[2].slice(1).split(',').some((part) =>
    crypto.timingSafeEqual(expected, Buffer.from(part.slice(3))),
  );
}
import hashlib, hmac, re, time

HEADER = re.compile(r"t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)")

def verify_railbed_signature(raw_body: bytes, header: str, secret: str,
                             tolerance_seconds: int = 300) -> bool:
    m = HEADER.fullmatch(header or "")
    if not m:
        return False
    timestamp, signatures = m.groups()
    if abs(time.time() - int(timestamp)) > tolerance_seconds:
        return False
    expected = hmac.new(secret.encode(), timestamp.encode() + b"." + raw_body,
                        hashlib.sha256).hexdigest()
    # Check every v1: for 24 hours after a roll there are two.
    return any(hmac.compare_digest(expected, part[3:])
               for part in signatures[1:].split(","))
<?php
function verify_railbed_signature(string $rawBody, string $header, string $secret,
                                  int $toleranceSeconds = 300): bool {
  if (!preg_match('/^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$/D', $header, $m)) return false;
  if (abs(time() - (int) $m[1]) > $toleranceSeconds) return false;
  $expected = hash_hmac('sha256', $m[1] . '.' . $rawBody, $secret);
  // Check every v1: for 24 hours after a roll there are two.
  foreach (explode(',', substr($m[2], 1)) as $part) {
    if (hash_equals($expected, substr($part, 3))) return true;
  }
  return false;
}

Three language details are easy to get wrong. Node's crypto.timingSafeEqual throws when its two inputs differ in length; the regex guarantees both are 64 bytes here, so if you loosen it, check lengths first. Python's hmac.compare_digest needs both arguments of the same type, so compare the hexdigest() string with a string, not bytes. PHP's hash_equals takes the known value first: the manual says "provide the user-supplied string as the second parameter". The /D on the PHP pattern stops $ from matching before a trailing newline, so a header with a stray line break is rejected rather than half-parsed.

To check the HMAC step on its own, reproduce the published vector with OpenSSL. It prints ffa4d1ef497dab81940a1183234f88da04bb2e7cd2dbb1637c71ba8348fd3f9e:

printf '%s' '1790380800.' \
  '{"id":"evt_ExampleEventId0001","type":"ping","created":1790380800,' \
  '"livemode":false,"data":{"payment":null,"order":null,"customer":null,"invoice":null}}' \
  | openssl dgst -sha256 -hmac 'whsec_4mJ9pQx2VtR7cY1nKs8LwZ3bHd6fGa0e'

Why verification fails, and why a passing test can hide it

Most "webhook signature verification failed" errors come from a body or secret that is not the one Railbed signed. The table pairs each mistake with the symptom it produces, using Railbed's troubleshooting list and what we saw testing the code above.

Mistake What you see Fix
Verifying parsed and re-serialized JSON Some deliveries fail, others pass Verify the raw bytes, then parse
Test secret on the Live endpoint, or another endpoint's secret Every delivery fails Each endpoint and mode has its own secret
Secret saved with a space, quotes or a newline Every delivery fails Store the 49 characters exactly
A proxy, CDN or security plugin rewrites the body or drops the header Test events pass, real ones fail Let the webhook path through untouched
Server clock drift Works, then fails after a while Keep the clock synced with NTP
Header parsed into a key/value map Fails for up to 24 hours after a secret roll Keep every v1
== or === on the signatures Works, but leaks timing Use the constant-time compare

The re-serialization row deserves a closer look, because a quick test can pass while real traffic fails. We parsed and re-encoded the published test vector's body in three languages. JavaScript's JSON.stringify and PHP's json_encode both reproduced it exactly, so a verifier that wrongly checks re-encoded JSON would pass a test built on that ping body. Real payment events differ. A payment.paid body carries addresses such as url and successUrl, and PHP escapes forward slashes unless you pass JSON_UNESCAPED_SLASHES (the constant's description is "Don't escape /"), so https:// comes back as https:\/\/ and the signature no longer matches. Python's json.dumps fails even on the ping, because its default separators are ', ' and ': ', adding spaces the original never had.

The key/value map row comes from the same test. Splitting a two-signature header on commas and building an object keeps only the second v1, so whichever server holds the secret behind the first one rejects every delivery until the overlap ends.

Four ways one sale reaches your code twice

Deduplicating on the event id is necessary but not enough, because only one of the four kinds of duplicate shares an event id. The table names each kind, an example of it with Railbed, and the unique key that stops it.

Duplicate Example Unique key
The same event, delivered again Your handler took longer than 10 seconds, so Railbed retried; someone chose Resend in the delivery log Event id (the same on every attempt)
Two signals about one payment payment.paid then payment.updated; the webhook and your background check both see paid Payment id
Two paid payments for one order A buyer abandons a session, opens a second, then finishes both Your order id
Your own create call, retried POST /v1/checkout_sessions timed out and your code sent it again Idempotency-Key

Four rows pairing each duplicate with its unique key: same event again with event id, one payment twice with payment id, one order paid twice with order id, and create call retried with Idempotency-Key. Only the first row is solved by remembering event ids; the other three need keys on your own records.

How long you remember event ids matters too. The Standard Webhooks specification suggests using webhook-id as an idempotency key and gives the example "save the IDs in redis for 5 minutes". For Railbed that window is far too short: failed deliveries are retried at 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 12 hours, "seven attempts over about 21 hours", and a finished delivery can be resent from the log while it is kept, which is 30 days. Keep event ids in your database for at least 30 days; keeping them for good costs one small row per event.

The last row happens before any webhook exists. Railbed's API honors Idempotency-Key on POST /v1/checkout_sessions: the same key and body within 24 hours returns the same session, and the same key with a different body answers 409 idempotency_conflict. Save the key with your order before the first call, as the fulfillment guide describes.

A handler that records, queues and answers

A receiver that never double-fulfills does as little as possible inside the request: verify, record the event id, queue a job, answer 2xx. Railbed counts a delivery as successful on "any 2xx status within 10 seconds", and warns: "Don't answer 2xx before the event is saved." The example uses Express and PostgreSQL; INSERT … ON CONFLICT DO NOTHING inserts nothing when the key exists, and the command tag's count tells you which happened.

CREATE TABLE railbed_events (
  id          text PRIMARY KEY,               -- evt_…
  type        text NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE fulfill_jobs (
  payment_id text PRIMARY KEY,                -- pay_…
  created_at timestamptz NOT NULL DEFAULT now(),
  done_at    timestamptz
);
CREATE TABLE grants (
  order_id   text PRIMARY KEY,                -- one grant per order
  payment_id text NOT NULL,
  granted_at timestamptz NOT NULL DEFAULT now()
);
import express from 'express';
import pg from 'pg';
import { verifyRailbedSignature } from './verify.mjs';

const app = express();
const pool = new pg.Pool();

app.post('/webhooks/railbed', express.raw({ type: 'application/json' }), async (req, res) => {
  const raw = req.body.toString('utf8');
  const header = req.get('Railbed-Signature');
  if (!verifyRailbedSignature(raw, header, process.env.RAILBED_WEBHOOK_SECRET)) {
    return res.sendStatus(400); // a 4xx: retried, and shown in the delivery log
  }
  const event = JSON.parse(raw);
  const payment = event.data?.payment;
  if (payment?.metadata?.sample === 'true') return res.sendStatus(200); // a Test sample

  const db = await pool.connect();
  try {
    await db.query('BEGIN');
    const seen = await db.query(
      'INSERT INTO railbed_events (id, type) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING',
      [event.id, event.type],
    );
    if (seen.rowCount === 1 && event.type === 'payment.paid') {
      await db.query(
        'INSERT INTO fulfill_jobs (payment_id) VALUES ($1) ON CONFLICT (payment_id) DO NOTHING',
        [payment.id],
      );
    }
    await db.query('COMMIT');
    res.sendStatus(200); // new or duplicate, both are done
  } catch (err) {
    await db.query('ROLLBACK');
    res.sendStatus(500); // nothing saved, so let Railbed retry
  } finally {
    db.release();
  }
});

Reject a bad signature with a 4xx such as 400, as Railbed's docs recommend; a 401 that asks for a password shows in the delivery log as a password-protected site rather than a signature problem. A worker then takes each row from fulfill_jobs and runs the function below. It reads the payment back from the API, for two reasons Railbed's docs give: the payment inside an event uses camelCase names and millisecond timestamps while the API uses snake_case and seconds, and a read returns the payment "as it is now". The grant row and the delivery commit together, so a second worker, a duplicate event or a retried job finds the order already granted and delivers nothing.

async function fulfill(db, paymentId) {
  const res = await fetch(`https://pay.railbed.io/v1/payments/${paymentId}`, {
    headers: { Authorization: `Bearer ${process.env.RAILBED_SECRET_KEY}` },
  });
  if (!res.ok) throw new Error(`Railbed answered ${res.status}`); // the job retries later
  const payment = await res.json();
  if (payment.status !== 'paid') return; // held, pending or expired: nothing to deliver

  await db.query('BEGIN');
  try {
    const { rows: [order] } = await db.query(
      'SELECT * FROM orders WHERE reference = $1 FOR UPDATE', [payment.reference]);
    if (!order) throw new Error('no order for this payment');
    if (payment.livemode !== order.livemode ||
        payment.amount !== order.price || payment.currency !== order.currency) {
      throw new Error('payment does not match the order'); // for a person to look at
    }
    const granted = await db.query(
      'INSERT INTO grants (order_id, payment_id) VALUES ($1, $2) ON CONFLICT (order_id) DO NOTHING',
      [order.id, payment.id]);
    if (granted.rowCount === 1) {
      await deliver(db, order); // same transaction as the grant row
    } else {
      const { rows: [first] } = await db.query(
        'SELECT payment_id FROM grants WHERE order_id = $1', [order.id]);
      if (first.payment_id !== payment.id) await flagForRefund(db, order, payment);
    }
    await db.query('COMMIT');
  } catch (err) {
    await db.query('ROLLBACK');
    throw err;
  }
}

The grant is keyed on the order, not the payment, so the "one order, paid twice" case delivers once and flags the second payment. Railbed has no refund endpoint; a refund is money you send back from your own wallet, then record it on the order if you want it on Railbed's timeline. The amount comparison works because the API returns amounts as decimal strings with two decimals, such as "27.00" (it turns "27" into "27.00"); store your price the same way.

Statuses that are not "paid"

A correct handler treats every status except paid as "not yet", including two that look final. Railbed's statuses behave like this for fulfillment:

  • held: money arrived but failed a check, most often because less than 85% of the order's value arrived. Don't fulfill. If the merchant chooses Accept as paid in the dashboard, the payment becomes paid and payment.paid is sent, so the normal path handles it.
  • expired: nobody paid in time, but "money that arrives late still settles and the payment becomes paid or held". Don't let an earlier cancellation block a later payment.paid, and never undo a paid order because a payment.expired arrives after it, since events can arrive out of order.
  • payment.updated: a paid payment's settlement details were filled in. There is nothing to deliver again.
  • Unknown event types and fields: acknowledge with 2xx and ignore. Railbed only adds to events within v1.
  • The success_url visit: not a signal at all. A buyer can open it without paying, and one who pays can close the tab before it loads.

Prove it in Test mode before going live

Railbed's Test mode sends real signed webhooks for simulated payments, so every rule above can be checked without moving money:

  1. Unit-test the verifier with the published vector, a changed byte and a two-v1 header, as above.
  2. Point a Test endpoint at your code through a tunnel (testing guide) and choose Send test event. Check the delivery log shows 200.
  3. Create and start a Test checkout session, then simulate it paid with POST /v1/payments/:id/simulate and "outcome": "paid". Confirm one row in grants.
  4. Choose Resend on that payment.paid in the delivery log. It arrives with the same event id; your handler should answer 200 and grants should still hold one row.
  5. Simulate underpaid on a second started session. Half the value arrives, the payment is held, and nothing should be granted.
  6. Roll the Test endpoint's secret and send another event before updating your server. It should still verify against the old secret during the overlap, then against the new one once you switch.

When this guide is about Railbed, and when it isn't

The pattern here (raw body, constant-time compare, timestamp window, deduplication, grant keyed on your order) applies to any HMAC-signed payment webhook; only the header name, window and retry schedule change. If you already take cards through a processor with an official library, use its verification function rather than your own, and keep the deduplication half of this page.

Railbed is card checkout for online merchants that mainstream processors turn away. Buyers pay by card through independent, licensed on-ramp providers, and each sale settles to a wallet you control, almost always as USDC on Polygon. That shapes two parts of this guide: confirmation is not instant (a card payment takes a few minutes on the provider's page, then settlement is checked), and refunds are yours to send. Build the buyer's order screen to wait for paid rather than assume it, and read webhooks or polling for payment status for the background check that catches anything a webhook misses. For one vertical's version of the same problem, see preventing duplicate crediting of adult-app purchases.

Check your receiver against Railbed's test vector

The signature docs carry the scheme, verifiers in six languages, the raw-body call for each framework and the vector to test against. A Test account sends real signed webhooks for simulated payments.

Read the signature docsCreate a Test account