Webhooks
Railbed sends a signed HTTPS request to your server when a payment starts, settles, is held, expires or is canceled, and, if you choose, when an invoice is issued, sent, viewed or paid. How endpoints, deliveries, retries and the delivery log work.
On this page
How webhooks work
When something happens to a payment, Railbed sends a POST with a JSON event to each of your endpoints that subscribes to it. The event carries the payment, its order with the items and addresses, and the customer. Endpoints that choose them also get invoice events, which carry the invoice instead. The request is signed with the endpoint's secret, so your server can prove it came from Railbed and wasn't changed.
POST https://yourstore.com/webhooks/railbed
Content-Type: application/json
User-Agent: Railbed-Webhooks/1.0
Railbed-Signature: t=1790381342,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
{"id":"evt_4Qm8ZsUe2VhNc7RwTb1Y","type":"payment.paid",…,"data":{"payment":{…},"order":{…},"customer":{…},"invoice":null}}Your server verifies the signature, records the event, answers 2xx and does the slow work afterwards. Events are queued in the same step as the payment change itself, so a payment can't become paid without its webhook being queued. Most are sent as soon as the change is saved; expiries go out within five minutes.
| Event | Sent when |
|---|---|
payment.started | The buyer entered their email and was given a way to pay |
payment.paid | The money arrived and passed Railbed's checks. Fulfil on this |
payment.held | Money arrived but failed a check, so it waits for your review |
payment.updated | A paid payment's settlement details were filled in |
payment.failed | The payment ended in a terminal Test failure |
payment.expired | Nobody paid in time |
payment.canceled | Before anyone went to a provider to pay: you voided an invoice, canceled a payment link or checkout session through the API, or a Shopify buyer started a new attempt |
invoice.* | An invoice was issued, sent, viewed, partly paid, paid in full or voided. Only to endpoints that chose these events |
ping | You chose Send test event (or Send ping on a Live endpoint) |
Add an endpoint
- In the dashboard, choose the mode (turn Test mode on or off in the business block at the top of the sidebar), then open Developers.
- Choose Add endpoint (its dialog says Add a Test endpoint or Add a Live endpoint) and enter your server's address. Add a description if you like ("Fulfilment server"), and pick the events it should receive. It gets every payment event unless you choose; tick Invoice events too if your code follows invoices.
- Copy the signing secret (
whsec_…) into your server's configuration, for exampleRAILBED_WEBHOOK_SECRET. You can reveal it again on the endpoint later. - Choose Send test event (on a Live endpoint, Send ping) and check how your server answered.
Each mode has its own endpoints and secrets: Test endpoints receive only Test events, and Live endpoints only Live events. To get Test events at an address you already use in Live, add it in Test mode too; it gets its own signing secret. When Live has endpoints and Test has none, Developers in Test mode says No Test endpoints yet and Test payments don’t reach your Live endpoints. The other way round, with an endpoint in Test and none in Live, Developers in Live mode says No Live endpoints yet, and Home says No Live endpoint with a button to add one. You can have up to 10 endpoints in each mode, each with a different address.
Your code, or an automation tool such as n8n, can also add and remove endpoints itself with the webhook endpoints API. Those endpoints follow the same rules and show up here in Developers like any other.
Address rules. Endpoints use https:// with no username or password in the address. (Test endpoints also accept http://localhost, but Railbed's servers can't reach your computer that way.) Live endpoints must be on the public internet: private networks, localhost and internal hostnames are refused, and addresses are checked again at each send. While you build on your own computer, use a tunnel.
Two notes can appear under the address as you type it, and on the endpoint's card. Neither stops you saving:
- A Test endpoint on
localhostor your private network: Railbed’s servers can’t reach localhost or your private network, so deliveries here will fail. Use a tunnel’s https:// address. - An address with no path, such as
https://yourstore.com: it may be your site's home page, which often redirects. Use the path your server receives webhooks on, like/webhooks/railbed. Addresses with a query, such as WooCommerce's, don't get this note.
The card leaves the note out while the latest delivery there succeeded, since some receivers do answer at their root.
Respond to deliveries
A delivery succeeds when your endpoint answers with any 2xx status within 10 seconds. The body of your answer is ignored.
- Answer fast. Verify, record the event, answer
200, then fulfil in a background job. A slow fulfilment that runs past 10 seconds counts as a failure and is retried, even if it later finishes. - Redirects aren't followed. A
3xxis a failure. Save the final address as the endpoint. - Reject what you can't verify with a
4xx, such as400. Deliveries that fail are retried, so a bad secret shows up in the log instead of losing events. - Don't answer
2xxbefore the event is saved. A2xxtells Railbed to stop sending it.
Retries
A delivery that fails is retried 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 12 hours after each failed attempt: seven attempts over about 21 hours. After the last one it's marked failed and stays in the delivery log, where you can send it again.
Those intervals are when a retry becomes due. The retry job checks within five minutes and gives each endpoint a turn; a busy backlog or an endpoint that has already failed in that run waits for a later pass.
After three consecutive failed attempts to an endpoint, or when a delivery runs out of retries, the bell at the top of the dashboard shows a dot in the affected Live or Test mode, and its panel names the endpoint by its host (never its path or query, which can carry a token), with a link to Developers for owners and developers. For a Live endpoint, owners and developers also get one email naming the endpoint and the latest failed event (each person can turn it off in Settings → Email notifications). If you connected Telegram or Slack, you also receive one notice there; Test notices follow your Test-alert preference. A successful delivery clears the notice and allows a later failure run to notify you again. A failed Send test event, Resend or Retry now shows its answer where you sent it and doesn't count toward these notices; one that succeeds clears them, like any delivery.
Every attempt carries the same event id and body, with a fresh signature and timestamp. When you edit the endpoint's address, pending retries go to the new one. When you roll its secret, attempts carry signatures from both the current and previous key for 24 hours, then only the current key.
Duplicates and order
Webhooks are delivered at least once. The same event can arrive more than once (a retry after a timeout, a resend from the log), and events for one payment can arrive in a different order than they happened, even in the same second.
- Deduplicate on the event
id. Store each id you process, with a unique constraint, in the same transaction as its effects. - Make fulfilment idempotent too. Grant each order once per payment id, whatever event or job arrives first. See Fulfil orders safely.
- Don't undo a paid order on a later event. A
payment.expiredthat arrives afterpayment.paiddoesn't make the payment unpaid. When in doubt, read the payment: it's always current.
The delivery log
Deliveries on each endpoint shows 25 deliveries per page: event, time, attempts, status or error, and next retry. Use Older deliveries and Newer deliveries to page through the retained history. Filter by status, event type, event or payment id, and date range; filters apply to the full retained history. Show body loads the exact body when you open a row.
- Retry now sends a delivery that's still retrying straight away. If it fails again, its automatic retries carry on as before, so pressing it while your server is down never uses them up.
- Resend sends a finished delivery again, once, with the same event id.
- When the latest delivery to an endpoint failed or is retrying, its card says so, says what to do when your server's answer points to a cause, and links to the log.
Why a delivery failed
The log, the endpoint's card and the result of Send test event show how your server answered, and for these answers what to do:
| Answer | What it usually means |
|---|---|
400 or 422 | Your handler rejected the body. Most often the signature was checked with another endpoint's or mode's secret, or over parsed JSON instead of the raw body |
3xx | The address redirects, and Railbed doesn't follow redirects. Save the address it redirects to |
401 or 407 asking for a password | A password in front of your site, such as a protected staging site. Turn it off for this address, or use one that has none |
Any other 401, 403 or 407 | Your server refused the request. Check that it verifies Railbed-Signature with this endpoint's signing secret over the raw body, and that no login page, firewall or bot protection blocks it |
404 or 405 | The address isn't your webhook route, or the route doesn't accept POST |
500 to 504 | Your handler, or a proxy in front of it, hit an error. Look in your server's logs for the event's id |
520 to 529 | Cloudflare, in front of your server, couldn't get an answer from it. Check the server is running and its certificate works, and that any tunnel it runs through is still running |
530 | Cloudflare found no running server for the address: a Cloudflare Tunnel that isn't running, or a DNS record that doesn't point at your server |
| No response within 10 seconds | Your handler took too long. Answer 2xx as soon as the event is saved, then fulfil |
| Could not connect | The domain doesn't resolve, or nothing accepts HTTPS with a valid certificate there. If you use a tunnel that gets a new address each time it starts, update the endpoint |
Railbed judges a delivery by its status alone, and for a 401 or 407 by whether it asks for a password. It keeps the last attempt's answer with the delivery (the status, the headers and the first 8 KB of the body) so Railbed support can see what your server said, and clears it with the delivery after 30 days.
When a Test endpoint on localhost fails, or an address with no path answers a redirect, 404 or 405, the card names the address as the cause instead. A failed Send ping, Retry now or Resend shows your server's answer in its message, and adds See the endpoint for what to do. or See the delivery for what to do. when there's advice. A retry or resend that fails then opens in the log with its advice.
Finished deliveries are kept for 30 days. Removed endpoints stay under Removed endpoints for 30 days; their history is readable, and resends are disabled. A payment's timeline in the dashboard also shows when its webhooks were delivered or failed.
Test events
Send test event on a Test endpoint sends one signed event, straight away, and shows the body sent and how your server answered. On a Live endpoint the button is Send ping: it sends a ping and reports the answer. Test sends are never retried, and test sends and resends are limited per business: after too many in a row, wait a minute before sending another.
- Test endpoints can receive a
pingor a sample of any payment or invoice event. The sample carries a made-up payment (metadata.sampleis"true"), order (ord_sample, two items shipping to San Francisco) and customer (cus_sample), none of which exist in your account or the API. Use them to build your order handling before a real sale. - Live endpoints can receive a
pingonly, so a live system never receives a payment that didn't happen.
A receiver or job that reads the payment back gets 404 not_found for a sample, because its pay_… id isn't a real payment. Skip a Test event whose payment has metadata.sample set to "true", before queueing any work for it, and acknowledge it with 2xx: failing it shows a failed delivery in the log.
To test the whole flow, create a Test session through the API and simulate its outcome. That sends the real sequence of events for a real Test payment.
Manage endpoints
| Action | What happens |
|---|---|
| Edit | Change the address, the description or the events. Pending retries follow the new address |
| Roll secret | A new secret takes effect at once. Both keys sign for 24 hours so you can update your server during the overlap. Your verifier must accept any matching v1. Rolling again during the overlap ends it early: the secret from before the last roll stops signing at once, and the one you're replacing signs beside the new one for the next 24 hours |
| Remove | The endpoint stops receiving events, pending retries stop, and retained history stays readable under Removed endpoints for 30 days |
An endpoint a tool added through the API is removed when it answers 410 Gone, and when you revoke the secret key that added it; one you added in Developers keeps retrying until you remove it. When a key adds a Live endpoint, the business's owners and developers get an email.
The webhook endpoints API can create, list, update and delete endpoints too, and an endpoint it creates without events gets the payment events only. It can change an endpoint's events and description, but not its address, and it can't roll secrets: an endpoint a tool created and you roll keeps working for the 24-hour overlap only, so turn that tool's automation off and on again instead.
A receiver, end to end
Express
import crypto from 'node:crypto';
import express from 'express';
const app = express();
// The raw body: verify exactly the bytes that were signed.
const rawJson = express.raw({ type: 'application/json' });
app.post('/webhooks/railbed', rawJson, async (req, res) => {
const raw = req.body.toString('utf8');
const secret = process.env.RAILBED_WEBHOOK_SECRET;
const header = req.get('Railbed-Signature');
if (!verify(raw, header, secret)) return res.sendStatus(400);
const event = JSON.parse(raw);
const isNew = await db.events.insertIfAbsent(event.id); // UNIQUE(id)
if (isNew && event.type === 'payment.paid') {
await queue.add('fulfil', { paymentId: event.data.payment.id });
}
res.sendStatus(200);
});
function verify(raw, header, secret) {
const m = /^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$/.exec(header ?? '');
if (!m) return false;
if (Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(`${m[1]}.${raw}`)
.digest('hex');
return m[2].slice(1).split(',').some((part) =>
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(part.slice(3))),
);
}Flask
import hashlib, hmac, os, re, time
from flask import Flask, request
app = Flask(__name__)
@app.post("/webhooks/railbed")
def railbed_webhook():
raw = request.get_data() # the raw bytes, before any JSON parsing
header = request.headers.get("Railbed-Signature", "")
if not verify(raw, header, os.environ["RAILBED_WEBHOOK_SECRET"]):
return "", 400
event = request.get_json()
is_new = db.events.insert_if_absent(event["id"])
if is_new and event["type"] == "payment.paid":
queue.enqueue("fulfil", event["data"]["payment"]["id"])
return "", 200
def verify(raw: bytes, header: str, secret: str) -> bool:
m = re.fullmatch(r"t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)", header or "")
if not m:
return False
expected = hmac.new(
secret.encode(), m[1].encode() + b"." + raw, hashlib.sha256
).hexdigest()
return (
abs(time.time() - int(m[1])) < 300
and any(hmac.compare_digest(expected, part[3:]) for part in m[2][1:].split(","))
)<?php
$raw = file_get_contents('php://input');
$header = $_SERVER['HTTP_RAILBED_SIGNATURE'] ?? '';
if (!railbed_verify($raw, $header, getenv('RAILBED_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($raw, true);
if (events_insert_if_absent($event['id']) && $event['type'] === 'payment.paid') {
queue_fulfilment($event['data']['payment']['id']);
}
http_response_code(200);
function railbed_verify(string $raw, string $header, string $secret): bool {
if (!preg_match('/^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$/D', $header, $m)) return false;
if (abs(time() - (int) $m[1]) >= 300) return false;
$expected = hash_hmac('sha256', $m[1] . '.' . $raw, $secret);
foreach (explode(',', substr($m[2], 1)) as $part) {
if (hash_equals($expected, substr($part, 3))) return true;
}
return false;
}The fulfilment job then reads the payment and grants the order once, as in Fulfil orders safely. Verification in more languages, and a test vector to check yours against, are in Verify signatures.
Checklist
- The endpoint verifies
Railbed-Signatureagainst the raw body and rejects anything else with a4xx - Timestamps older than five minutes are rejected
- Event ids are stored with a unique constraint, and duplicates are acknowledged with
2xxand ignored - The endpoint answers within a second or two and fulfils in the background
- Unknown event types are acknowledged with
2xxand ignored, and unknown fields are ignored - Test samples (
metadata.sampleis"true") are acknowledged with2xx, though the API doesn't know their payment - Orders are granted once per payment, from
paidonly - A background job checks orders still waiting, in case a webhook never arrives
- The Live endpoint uses the Live secret, and the Test endpoint the Test secret