Recurring billing with subscriptions

Bill customers each period with subscriptions and plans. Railbed issues an invoice per period and the customer pays it by card. Give access from signed webhooks, send your own emails, read recurring revenue and test a renewal without waiting.

On this page

How it works

A subscription is a schedule for one customer: a price, how often it bills and when it starts. For each period, Railbed issues an ordinary invoice and, if the business leaves emails on, emails it with reminders around the due date. The customer pays it by card on the invoice's page, and the payment settles to the merchant's wallet like any other.

Railbed never stores a card, so nothing is charged automatically. A period counts as paid only when its invoice is paid. If a customer doesn't pay, the subscription goes past due and, after the number of days the business chose, ends. Write your access rules around that: access follows paid invoices, not a card that's billed in the background.

A plan is a price many customers can subscribe to, with its own sign-up page at https://pay.railbed.io/subscribe/…. Each subscriber has a page at https://pay.railbed.io/sub/… where they pay the open invoice, download past ones and, where the business allows it, cancel. Subscriptions add no fee of their own.

When to use one

Use a subscription when you bill the same customer again each week, month, year or your own interval (a membership, a retainer, a hosted service) and want Railbed to keep the schedule, send the invoices and chase them. If your app already decides when to ask for money, keep using checkout sessions; for one bill, use an invoice.

Create subscriptions

Most businesses create them in the dashboard: Create → Subscription, for one customer or as a plan with a sign-up page (user guide). Your server only needs to listen for the webhooks.

To create them from your own code, use the Subscriptions and Subscription plans endpoints. Reads need the payments:read scope (a Read only key has it); everything else needs checkouts:write (Full access).

RouteWhat it does
GET /v1/subscription_plans, POST /v1/subscription_plansList or create plans
GET /v1/subscription_plans/:id, PATCH /v1/subscription_plans/:idRetrieve or update a plan. A new price or interval applies to new subscribers only
GET /v1/subscriptions, POST /v1/subscriptionsList or create subscriptions
GET /v1/subscriptions/:id, PATCH /v1/subscriptions/:idRetrieve or update a subscription. Changes apply from the next invoice
POST /v1/subscriptions/:id/cancelEnd it at the end of the time paid for, or now
POST /v1/subscriptions/:id/keepTake back a cancel at the end of the time paid for
POST /v1/subscriptions/:id/pause, POST /v1/subscriptions/:id/resumeStop issuing invoices, and start again
POST /v1/subscriptions/:id/advanceTest mode only: issue the next period's invoice now
GET /v1/invoices?subscription=sub_…The invoices a subscription has issued
GET /v1/subscription_metricsRecurring revenue, churn and collection, per currency (below)

Send an Idempotency-Key with every create, so a retry after a timeout returns the first subscription instead of making a second one:

Subscribe a customer to a plan
curl https://pay.railbed.io/v1/subscriptions \
  -H "Authorization: Bearer $RAILBED_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: signup_ada_pro" \
  -d '{
    "plan": "spl_8Hq2mVx5RtLc3NwZb7Ks",
    "customer": { "name": "Ada Lovelace", "email": "ada@example.com" }
  }'

A subscription that starts today issues its first invoice before the response comes back: send the customer to its latest_invoice.url, or let Railbed's email reach them. One with a trial or a later start date issues nothing until its first invoice is due to go out.

Give access from webhooks

Subscription events go only to endpoints that name them, like invoice events, so an endpoint made before subscriptions never receives one. Tick Subscription events on the endpoint in Developers, or list them in events when you create or update an endpoint. Each event carries the subscription as data.subscription; Event types has the full list and payload.

EventWhat to do
subscription.activatedIts first paid period has begun. Turn access on
subscription.renewedA later period's invoice was paid. Extend access to the new paid_through
subscription.past_dueThe latest invoice is unpaid after its due date. Keep access for a grace period, or limit it; tell the customer if you like
subscription.canceledIt has ended. Turn access off
subscription.paused, subscription.resumedNo invoices go out while paused. Decide whether a paused subscriber keeps access
subscription.updatedIts price, details or end date changed, or a cancellation was set or taken back. Read the new values

Decide from the subscription's state, not from which event arrived last: events can arrive late or out of order. Use stored_status (Who to serve) and serve a customer while it's trialing or active (and past_due for a grace period), or serve until paid_through (or trial_end), in Unix seconds. status is the dashboard's label; its ending means canceled at the end of the paid time and still running until ends_at, so don't treat it as ended.

Node.js: access from a subscription event
const ACCESS = new Set(['trialing', 'active', 'past_due']); // drop past_due for no grace period

async function onSubscriptionEvent(event) {
  if (!event.type.startsWith('subscription.')) return;
  // Each event is delivered at least once: skip one you have already handled
  if (!(await db.events.insertIfNew(event.id))) return;

  const sub = event.data.subscription;
  if (sub.livemode !== event.livemode) return;
  await db.memberships.upsert({
    subscriptionId: sub.id,
    email: sub.customer.email,
    active: ACCESS.has(sub.stored_status),
    paidThrough: sub.paid_through, // Unix seconds, or null before the first payment
    eventCreated: event.created,   // ignore an event older than the one you applied
  });
}

Key access on the subscription's id, and don't let an older event replace a newer one: compare the event's created. The subscription's version counts only edits, never billing, so it can't order events. Two events can fall in the same second, so when the order matters, read the subscription back with GET /v1/subscriptions/:id and store what it says.

Each payment toward a subscription's invoice also sends payment.paid and, to endpoints that chose them, invoice.paid. You don't need those for access: subscription.activated and subscription.renewed already follow from them. If you fulfil orders from payment.paid, its invoice_id tells you to skip it (Fulfil orders safely).

Send your own emails

By default, Railbed emails each invoice in the business's name, with reminders and receipts. To send your own instead, turn off Email each invoice to the customer on the plan or subscription (billing.send_emails: false in the API), which also stops Railbed's reminders and receipts. Then listen for subscription.invoice_issued: it arrives once for each period's invoice, with the invoice as data.invoice. Send the customer its url, where they pay, and its pdfUrl if you attach the PDF.

Node.js: email each period's invoice yourself
if (event.type === 'subscription.invoice_issued') {
  const { invoice, subscription } = event.data;
  if (!(await db.sentInvoices.insertIfNew(invoice.id))) return; // once per invoice
  await mailer.send({
    to: subscription.customer.email,
    subject: `Your ${subscription.name} invoice ${invoice.number}`,
    text: `Due ${invoice.dueDate}. Pay it here: ${invoice.url}`,
  });
}

data.invoice has the same shape as in invoice events, with camelCase names and times in milliseconds; data.subscription has the API's shape, with snake_case names and times in seconds.

Read recurring revenue

GET /v1/subscription_metrics returns the figures the dashboard's Subscriptions → Revenue tab shows, for the key's mode: monthly recurring revenue and its annual run rate, who's paying, in a trial or past due, the period's movements, churn, net retention, trial conversion, how invoices were collected, a series for a chart and monthly cohorts. Pass period as 30d (the default), 90d or 12m. A Read only key can read it, so a reporting tool needs nothing more.

Recurring revenue over 90 days
curl "https://pay.railbed.io/v1/subscription_metrics?period=90d" \
  -H "Authorization: Bearer $RAILBED_SECRET_KEY"

Every figure sits under its currency in currencies, and nothing is ever added across currencies or converted: a business billing in USD and EUR gets two entries. Money is decimal text ("mrr": "637.00"), rates are fractions (0.1 is 10%) and null when there's nothing to divide by, and mrr_change.percent alone is a percentage. The figures come from each subscription's own history, so editing an invoice doesn't rewrite them, and a pause is never counted as churn. How the figures are counted defines each one in plain words.

Node.js: MRR per currency for a daily report
const res = await fetch('https://pay.railbed.io/v1/subscription_metrics?period=30d', {
  headers: { Authorization: `Bearer ${process.env.RAILBED_SECRET_KEY}` },
});
const metrics = await res.json();
for (const c of metrics.currencies) {
  console.log(`${c.currency}: MRR ${c.mrr}, ${c.subscribers.paying} paying, ${c.past_due.amount} past due`);
}

Don't call it on every page view: the figures change only as subscriptions are billed and paid, so read them once for a report or cache them for a few minutes.

Let an AI assistant help

An assistant connected through the Railbed MCP server can read subscriptions, plans and these figures, and prepare a subscription for a customer on a plan, a cancellation, a pause, a resume or taking back a cancellation. Preparing these needs an owner's connection with Full access, and each change waits for that owner to confirm it in Railbed; the assistant can't confirm it itself. A developer's connection reads subscriptions but can't prepare changes to them. Plans are made and changed in the dashboard or with this API.

Idempotency and ordering

  • Creates: send an Idempotency-Key with every POST /v1/subscriptions and POST /v1/subscription_plans.
  • Events: deduplicate on the event's id. For subscription.invoice_issued, also on data.invoice.id: there is exactly one invoice per period, and Railbed never issues a second one while an invoice is unpaid.
  • Ordering: events can arrive late or out of order. Keep the newest event created of each subscription, or read it back with GET /v1/subscriptions/:id.
  • Mode: Test and Live subscriptions and their events are separate. Check livemode.

Try it in Test mode

Test subscriptions behave like Live ones, except that no email ever reaches the customer. Test endpoints still receive every subscription event, so you can build against them.

  1. In Test mode, create a plan and a subscription that starts today, in the dashboard or with a Test key. subscription.created and subscription.invoice_issued arrive.
  2. Pay the first invoice from its page, in a browser where Test payments are turned on (Testing). subscription.activated arrives.
  3. Issue the next period's invoice without waiting: Renew now on the subscription's page, or POST /v1/subscriptions/:id/advance with a Test key. It works while the subscription isn't paused or ending and has no unpaid invoice.
  4. Pay that invoice and watch for subscription.renewed, or leave it unpaid to see what your code does with an open invoice.

Send test event on a Test endpoint in Developers can also send a sample of each subscription event. Its subscription, for "Sample Customer", is made up and doesn't exist in your account, so don't read it back.

What it doesn't do yet

Subscriptions don't take payment for several periods at once, accept part payments on a period's invoice, prorate or switch plans part way through a period, or change a plan's price for its existing subscribers. Billing days are UTC calendar days, and there's no usage-based billing.

Updated · This page as Markdown