npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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_url with <EmbeddedPayment>. OpenRails can reuse an open checkout with the same lines.
  • onPaid receives the completed session, including its invoice_id. Grant access from your server's entitlement check or the invoice.paid event.
  • <CheckoutPayment sessionId> pays a session using the same form as InvoicePayment. Pass session to 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. onSettled follows completion. returnUrl must be on one of your app's return origins. Pass invoice when 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 be redirect_to_url (top window), solana_pay (a QR code or wallet link) or authenticate (the bank's challenge, in the page). In the EEA and UK a new card is kept only with reusable: true, the customer's own opt-in.
  • Saved payment methods report reusable for one-click buys and default_eligible when 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.
  • fallbacks keeps 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, InvoicePayment and EmbeddedPayment take it.
  • A customer_amount price takes the buyer's amount: validate and normalize it with parseAmount(text, currency.decimals) and check the price's bounds with compareDecimals. <Cart> shows the customer's draft checkout session, their cart, and freezes it into the checkout it pays or hands to a host through onCheckout; hosts fill it with client.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/config and GET /v1/me/config once per provider (useConfig(), useCustomerConfig()). A page your server renders can pass both as config and customerConfig (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. authenticateChange runs 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; messages layers bundles and t lets your i18n win. Styles are scoped under .orck; appearance.theme is light, dark, auto or inherit (your shadcn tokens).
  • Notifications. The inbox's UI (User Intelligence's @openrails/user-intelligence-ui) owns the inbox; BillingNotification and isBillingNotification render OpenRails' customer notices (kind openrails.<event type>, never an operator's openrails.incident) through its renderItem. A payment problem, an ended membership and an applied downgrade get billing's own localized words, their facts read from the notice's keyed fields (retry_status, next_attempt_at, ended_at); any other notice shows its own title and body. The action is the notice's recovery_action field (update the card, resubscribe, authenticate, contact support), linked to the URL you pass in actions, else your manage_billing URL, else the notice's own link. billingNotificationContent and billingNotificationField read 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 FeedbackBox itself, here after the cancel (BillingProvider's onChange names 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.

  • auth supplies authFetch; 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.
  • merchant fixes the merchant; the shell switches it (AdminShell's merchants and onMerchantChange). settingsTabs, customerPanels and userHref add your content.
  • Keep each prop the same object while it holds (memoize navigation and your callbacks): a new one re-renders every billing page.
  • useBillingAdminAccess reads the staff member's access for your navigation; pass what it read as access and the console opens without reading it again. BillingCustomerSummary previews a customer's billing on your page; billingConfirmWarnings words 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).