Fulfil orders safely

Deliver each order exactly once, only for money that really arrived. The checks that keep fulfilment correct through retries, duplicate events, late payments and reviews.

On this page

The rule

Fulfil an order only when your server has seen its payment as paid from Railbed itself: a webhook whose signature you verified, or an authenticated GET /v1/payments/:id. Never fulfil from the buyer's return to your success_url, a query parameter, or anything the buyer's browser reports.

Save before you create

Before calling Railbed, save the order with everything that decides what the buyer gets: the user, the items, the price, the currency and the Idempotency-Key you'll send. After the create call, save the returned pay_… id on the order. If the call times out, retry it with the same key: you get the same session back, never a second payment. Send the order itself as order, with your order's id in order.id: a later session for the same order then joins it, and one for an order that's already paid, or whose money arrived and waits for your decision, is refused with 409 order_paid.

Check before you grant

When a payment reports paid, look up your order by the payment's reference (or its id) and check, in this order:

  1. It's the right payment. The payment id matches the one saved on the order, and the mode matches (livemode in the API, livemode on the event).
  2. It's for this order. reference, and any metadata you set, match the order.
  3. It's the price you asked. amount and currency match the order. For a checkout session they can't change after creation, so a mismatch means you're looking at the wrong payment.
  4. It's paid. status is paid. Not held, not pending.
  5. It isn't done already. Record the grant with a unique constraint on the payment id (or the order), in the same database transaction as the delivery itself. A second event for the same payment then changes nothing. When you ship goods, key it on the order: a buyer who paid two sessions for one order has two paid payments, and should get one parcel and a refund.

Resolve the customer from your own order, never from the payment's customer_email: buyers can type any email at checkout.

Payments toward invoices you send from Railbed also send payment.paid. They carry invoice_id, and their amount is the part the customer paid, tip included, so they won't match an order of yours: the first check skips them. Fulfil those from the invoice.paid event or your own invoice record.

Node.js: one grant per payment, in one transaction
async function fulfilFromPayment(payment) {
  // Held, pending, expired: nothing to deliver yet
  if (payment.status !== 'paid') return;
  const order = await db.orders.findByPaymentId(payment.id);
  // Not ours (another store sharing the endpoint), or not saved yet
  if (!order) return;
  if (payment.livemode !== order.livemode) {
    throw new Error('mode mismatch');
  }
  if (payment.reference !== order.reference) {
    throw new Error('reference mismatch');
  }
  if (payment.amount !== order.price || payment.currency !== order.currency) {
    throw new Error('amount mismatch');
  }

  await db.transaction(async (tx) => {
    // UNIQUE(payment_id): a duplicate event or a second worker fails here
    // and delivers nothing
    const inserted = await tx.grants.insertIfAbsent({
      paymentId: payment.id,
      orderId: order.id,
    });
    if (!inserted) return;
    await tx.inventory.deliver(order);
    await tx.orders.markPaid(order.id, payment.paid_at);
  });
}

Sessions from a checkout

When your server makes sessions from a saved checkout, as an embedded checkout does when it asks at Continue, the checkout sets the price. Check the paid payment against what your server saved when it made the session, never against today's checkout, which may have changed since:

  • Find the saved attempt by the payment's id (or its reference), and grant to the user saved on it. metadata.user_id came from your server too; the payment's email may be one the buyer typed.
  • amount, currency and plan_label equal what the session answered when it was made, and checkout_id is the checkout you expected.
  • Grant what the plan you saved gives, plan and option from the request, rather than parsing plan_label.

The webhook's data.payment carries the same as checkoutId, planLabel and metadata.

Node.js: grant the plan to the user who asked for it
async function fulfilAttempt(payment) {
  if (payment.status !== 'paid') return;
  const attempt = await db.attempts.findByPaymentId(payment.id);
  if (!attempt) return; // not made by this server
  if (
    payment.amount !== attempt.amount ||
    payment.currency !== attempt.currency ||
    payment.plan_label !== attempt.planLabel
  ) {
    throw new Error('payment does not match the saved attempt');
  }
  await db.transaction(async (tx) => {
    // UNIQUE(payment_id): a duplicate event grants nothing
    if (!(await tx.grants.insertIfAbsent({ paymentId: payment.id }))) return;
    const { plan, option } = attempt.body;
    await tx.subscriptions.grant(attempt.userId, plan, option);
  });
}

Ship what the order says

Every payment belongs to an order with the items, the addresses and the customer, as your store sent them in order and customer. If your store keeps its own orders, ship from those, checked as above. If your fulfilment works from Railbed instead (a warehouse connected to your webhooks, for example), take what to ship from the order:

  • In a webhook: data.order, with items and shipTo (camelCase). See the order object.
  • From the API: GET /v1/orders/:id with the payment's order_id, with items and shipping_address.

The checks above still apply, plus one: the paid payment's amount and currency equal the order's total and currency. An order's items and totals follow its latest session, so a late payment for an older session can be for a different basket. Hold those for a person to look at.

Ship each order once, keyed on the order's id, then report it with Update an order so the dashboard shows it as fulfilled:

Node.js: ship a paid order once, then report it
// railbed() is the small helper from /docs/api/errors/
async function shipOrder(paymentId) {
  const payment = await railbed(`/payments/${paymentId}`);
  if (payment.status !== 'paid') return;
  const order = await railbed(`/orders/${payment.order_id}`);
  // The order follows its latest session: check this payment covers it
  if (
    payment.amount !== order.total ||
    payment.currency !== order.currency
  ) {
    return flagForReview(order, payment);
  }
  await db.transaction(async (tx) => {
    // UNIQUE(order_id): a second paid payment for this order ships nothing
    const isNew = await tx.shipments.insertIfAbsent({ orderId: order.id });
    if (!isNew) return;
    await tx.shipments.queue({
      to: order.shipping_address,
      lines: order.items.map((i) => ({ sku: i.sku, quantity: i.quantity })),
    });
  });
}

// Later, when the parcel leaves the warehouse
async function markShipped(orderId) {
  await railbed(`/orders/${orderId}`, {
    method: 'PATCH',
    body: JSON.stringify({ fulfillment: 'fulfilled' }),
  });
}

fulfillment is a record for you and your team; it doesn't touch the payment. Orders you sent with order.id get their fulfilment only from your store, so report every change; send unfulfilled if a shipment is recalled. The WooCommerce plugin does this for you.

Webhooks, the API, or both

SignalStrengthsWatch out for
payment.paid webhookArrives the moment the payment settles; retried for about a dayYour endpoint must be reachable, answer 2xx quickly and verify signatures
GET /v1/payments/:idAlways current; no public endpoint neededYou decide when to ask: poll gently, with backoff

The most robust integrations use both: fulfil on the webhook, and run a background job that checks orders still waiting. The job catches anything a webhook missed (your server was down for a day, a deploy dropped a request) without anyone watching.

Check unfinished orders in the background

Run a job every few minutes that checks each order still waiting on a payment, gently:

  • Check the payment ids you saved whose last known status is open, pending or held, with GET /v1/payments/:id.
  • Include orders whose payment expired in the last two days. Money can arrive after the 24-hour window, and the payment then becomes paid or held.
  • Check recent orders often and older ones less often (for example after 1, 5, 15 and 60 minutes, then hourly).
  • Stop checking a payment once it's paid, failed, or has been expired for two days. A payment.paid webhook that arrives later still counts.
  • Survive restarts: keep the queue in your database, not in memory.

Keep it within the rate limit: about 120 requests a minute per mode, shared by all of the account's secret keys (a connected AI agent has its own). The limit is approximate, and responses carry no rate-limit headers today, so plan well below it. For example:

CallerA budget that fits
The background jobOne pass every 5 minutes over a bounded batch, oldest check first, such as 50 payments a pass (about 10 requests a minute)
Buyers' status screensThey ask your server, which reads Railbed at most once per payment every 10 seconds and answers other polls from your database
Everything elseCreates, starts (at most 12 a minute per mode) and order updates as they happen, queued on your server

On a 429, stop and wait for Retry-After seconds (60 today) before the next request, then carry on where the pass stopped.

Held payments

held means money arrived but didn't pass a check, most often because the provider delivered less than 85% of the order's value. Don't fulfil. The dashboard shows it as Needs your decision: open it and choose Accept as paid when the shortfall is fine with you; the payment then becomes paid and payment.paid is sent, so your normal fulfilment path handles it. A payment whose money may have gone somewhere else (holdAcceptable: false) shows as Not received and can't be accepted; contact support.

Listen for payment.held if you want to tell the buyer their payment is being reviewed.

Late payments

A buyer can open a provider's page, leave, and come back to finish after the session's 24 hours. The payment was expired, and then becomes paid (or held). If your system cancelled the order on payment.expired, decide what a late payment means for you: fulfil it, or refund it from your wallet. Either way, don't ignore a payment.paid because the order was once marked abandoned.

Refunds

Railbed can't reverse a settled payment; the money is already in your wallet, and there's no refund endpoint. To refund, send the money back from your wallet (USDC for most card sales, or the coin the buyer paid in) to an address the buyer gives you, or refund in another way you both agree. Card disputes are handled by the provider that charged the card.

To keep a refund on Railbed's record of the order:

  1. Refund the buyer and record the refund in your own system, with your own refund id. Reverse what the order granted, once.
  2. Post it to the order with Report a cancellation or refund: type refunded, your refund id as id, and optionally the amount in the order's currency.
  3. Retry freely on a timeout or 5xx: the same id is recorded once and answers 200 with the same event. The same id with a different type or amount is 409 event_conflict.
Node.js: record a refund you made
// railbed() is the small helper from /docs/api/errors/
async function recordRefund(paymentId, refund) {
  const payment = await railbed(`/payments/${paymentId}`);
  await railbed(`/orders/${payment.order_id}/events`, {
    method: 'POST',
    body: JSON.stringify({
      type: 'refunded',
      id: `refund-${refund.id}`, // your own stable id, never personal details
      amount: refund.amount, // optional, such as "12.00", in the order's currency
    }),
  });
}

The record is a note on the order's timeline in the dashboard. It doesn't change the payment's or the order's status, sends no webhook and moves no money. It needs a key with Full access.

Updated · This page as Markdown