@openrails/billing-ui
v0.291.0
Published
Embeddable OpenRails purchase and account-billing UI: client, React hooks and styled components.
Readme
@openrails/billing-ui
OpenRails billing in the browser: purchase, the customer's account billing, and staff administration, inside your app. Card data is tokenized in the PSP's own fields (Collect.js, Stripe Elements) and never enters your app. How it fits an integration: the client guide.
| Import | Contents |
|---|---|
| @openrails/billing-ui/client | the typed client for /v1/me and BillingError, framework-free |
| @openrails/billing-ui/react | BillingProvider and headless hooks, no styles |
| @openrails/billing-ui | the provider, styled purchase and account components, i18n |
| @openrails/billing-ui/locales/* | en de es ja ko zh |
| @openrails/billing-ui/admin, /admin.css | AdminConsole, BillingAdmin, BillingCustomerSummary and their helpers |
Each OpenRails release vX.Y.Z publishes @openrails/[email protected] with
provenance; pin the exact version: pnpm add @openrails/[email protected].
The client
import { BillingProvider, createBillingClient } from "@openrails/billing-ui"
// Embedded: your app's own mount, with your auth's fetch (auth-ui's authFetch
// attaches the DPoP-bound token and its proof, and retries once after a refresh).
const billing = createBillingClient({ baseUrl: "/billing/v1", fetch: auth.authFetch })
<BillingProvider client={billing} appearance={{ theme: "auto" }}>
<App />
</BillingProvider>Standalone or hosted, the browser calls the billing API with a short
openrails:self token your backend mints. tokenSource keeps it in memory
only, fetches the next one skew seconds (60) before expiry with one request
however many calls wait, and resends a call answered 401 credential_expired once:
const billing = createBillingClient({
baseUrl: "https://billing.example/v1",
getToken: tokenSource({
fetchToken: async () => {
const { assertion } = await (await fetch("/api/billing/assertion", { method: "POST" })).json()
return redeemAssertion({ tokenEndpoint: "https://billing.example/oauth2/token", assertion })
},
}),
})A fetch that adds a DPoP proof (auth-ui's dpopFetch) binds the token to the
browser's key. Requests omit credentials; any origin may call.
Buying
The browser never reads the catalog: your server reads the products it sells
(Go Catalog.ListProducts) and puts them, priced as a buyer sees them
(billing.BuyerPrices), in its own page.
<BuyButton price={course.prices[0]} signedIn={signedIn}
onSignInRequired={openSignIn} onPaid={() => navigate("/courses/css-101")} />
<ProductList products={products} signedIn={signedIn}
onSignInRequired={openSignIn} onPaid={() => navigate("/courses/css-101")} />- A button creates the signed-in customer's checkout session and pays it in a dialog. On a registered merchant origin, it frames the session's
pay_urlwith<EmbeddedPayment>. OpenRails can reuse an open checkout with the same lines. onPaidreceives the completed session, including itsinvoice_id. Grant access from your server's entitlement check or theinvoice.paidevent.<CheckoutPayment sessionId>pays a session using the same form asInvoicePayment. Passsessionto show the result of a prior read or creation.<InvoicePayment invoiceId>pays an invoice your server created (Invoices.Create): saved cards, a new card, a hosted page, a Solana wallet, Apple and Google Pay through Stripe.onSettledfollows completion.returnUrlmust be on one of your app's return origins. Passinvoicewhen your page already read it: the form shows at once instead of reading it again.- A rail's next step comes from the bill or checkout's
payment.next_action. It can beredirect_to_url(top window),solana_pay(a QR code or wallet link) orauthenticate(the bank's challenge, in the page). In the EEA and UK a new card is kept only withreusable: true, the customer's own opt-in. - Saved payment methods report
reusablefor one-click buys anddefault_eligiblewhen making the card a default would be accepted. - A card the customer pays with becomes their default card. When they have a default and pay with another card, the form offers an unticked "Keep … as my default card" checkbox; ticked, the payment sends
keep_default: true. fallbackskeeps a PSP back until the PSPs it stands in for fail ({ ccbill: { for: ["nmi-main"], afterFailures: 2 } }), then offers it under "Card payment isn't working?".BuyButton,ProductList,Cart,CheckoutPayment,InvoicePaymentandEmbeddedPaymenttake it.- A
customer_amountprice takes the buyer'samount: validate and normalize it withparseAmount(text, currency.decimals)and check the price's bounds withcompareDecimals.<Cart>shows the customer's draft checkout session, their cart, and freezes it into the checkout it pays or hands to a host throughonCheckout; hosts fill it withclient.setDraftLine.
The form's fields, autofill and exact money rules: payment form contract.
Account billing
<AccountBilling plansHref="/plans"
sendSolanaTransaction={(tx) => wallet.signAndSend(tx)} />AccountBilling stacks SubscriptionsPanel (cancel, resume, change card,
change plan), PaymentMethodsPanel, PaymentHistory and, with usageCurrency,
UsagePanel; RenewalPrompt invites a customer whose subscriptions all ended
back to plansHref. UsagePanel charts the customer's usage by hour, day, week
or month in a zone it picks (the browser's by default), from
client.getUsageSeries; it loads its chart only where it is shown. The hooks
(useSubscriptions, useChangeOptions, usePaymentMethods, usePayments,
useUsageSeries) resolve to null or a BillingError, never throwing.
- Configuration. The panels read
GET /v1/configandGET /v1/me/configonce per provider (useConfig(),useCustomerConfig()). A page your server renders can pass both asconfigandcustomerConfig(Go:Engine.PublicConfig,Engine.CustomerConfig), so nothing is fetched to load. - Plan changes.
changeSubscription(id, { priceId?, quantity?, idempotencyKey })is a money write: mint one key per attempt and reuse it until the change resolves. More seats and upgrades charge now; fewer and downgrades apply at the next renewal.authenticateChangeruns a card challenge in the page; Solana changes sign in the wallet (signWalletAction). - Money and periods are exact: amounts are major-unit decimal strings
validated against OpenRails' currency registry precision (
formatAmount), and 720 hours reads "every 30 days", never "monthly". - Words and styles. English is complete and the fallback;
messageslayers bundles andtlets your i18n win. Styles are scoped under.orck;appearance.themeislight,dark,autoorinherit(your shadcn tokens). - Notifications. The inbox's UI (User Intelligence's
@openrails/user-intelligence-ui) owns the inbox;BillingNotificationandisBillingNotificationrender OpenRails' customer notices (kindopenrails.<event type>, never an operator'sopenrails.incident) through itsrenderItem. A payment problem, an ended membership and an applied downgrade get billing's own localized words, their facts read from the notice's keyedfields(retry_status,next_attempt_at,ended_at); any other notice shows its owntitleandbody. The action is the notice'srecovery_actionfield (update the card, resubscribe, authenticate, contact support), linked to the URL you pass inactions, else yourmanage_billingURL, else the notice's ownlink.billingNotificationContentandbillingNotificationFieldread a notice's data yourself. - Why they left. The cancel dialog asks no reason and OpenRails stores none. To ask, your app composes User Intelligence's
FeedbackBoxitself, here after the cancel (BillingProvider'sonChangenames it):
const [left, setLeft] = useState<string | null>(null)
<BillingProvider client={billing} onChange={(c) => c.type === "subscription.canceled" && setLeft(c.subscriptionId)}>
<AccountBilling />
</BillingProvider>
{left && <FeedbackBox key={left} client={inbox} prompt="cancellation"
subject={{ system: "openrails", type: "subscription", id: left }} onSubmitted={() => setLeft(null)} />}Staff administration
Needs @tanstack/react-query. AdminConsole is the whole staff console, AuthKit's
account administration and billing together (needs @openrails/auth-ui):
<AdminConsole authBaseUrl="/auth/v1" billingBaseUrl="/billing/v1" merchant={merchant} basePath="/admin" />AdminShell is the admin's one shell, as AdminConsole and the standalone console use it: the merchant switcher top-left, your sections in the sidebar, a top bar with the breadcrumb, your actions and the profile menu (the person, account settings, theme, sign out), and the page. BillingAdmin is the billing pages alone, content only, inside your own shell or AdminShell:
import { BillingAdmin } from "@openrails/billing-ui/admin"
import "@openrails/billing-ui/admin.css"
<BillingAdmin baseUrl="/billing/v1" auth={auth} basePath="/admin/billing"
navigation={{ pathname, search, navigate }} appearance={{ theme: "inherit" }} />To put billing's navigation and bell in the shell, wrap it in BillingAdminProvider (the same props) and render BillingAdminPages as the page; inside it useBillingNav() is the Billing section's items and the merchant's Settings, and BillingNotifications the incidents bell. billingNav(access, basePath) is the same list for a shell of your own.
authsuppliesauthFetch; the component stores no tokens. Mount it for the signed-in person and remount when that changes. Each page shows only to whoever holds its permission (GET /v1/admin/access); the API checks every request.merchantfixes the merchant; the shell switches it (AdminShell'smerchantsandonMerchantChange).settingsTabs,customerPanelsanduserHrefadd your content.- Keep each prop the same object while it holds (memoize
navigationand your callbacks): a new one re-renders every billing page. useBillingAdminAccessreads the staff member's access for your navigation; pass what it read asaccessand the console opens without reading it again.BillingCustomerSummarypreviews a customer's billing on your page;billingConfirmWarningswords a ban or deletion warning (neither cancels subscriptions).- The customer imports load no admin code or styles. The customer stylesheet is installed when the first component mounts; importing a helper adds no CSS.
Developing
pnpm critical:build builds the package and checks the browser driver types;
pnpm critical:static runs type, lint and packed-artifact checks;
pnpm contract:check fails when the generated wire types under
src/client/generated are stale (pnpm contract regenerates them with
OpenRails' contracts). Browser behaviour runs in OpenRails' critical suite.
src/components/ui is shadcn (base-vega, zinc; see components.json).
License
MIT; see LICENSE. Only this package is MIT: the rest of the OpenRails repository is under the Elastic License 2.0 (ELv2).
