@umituz/web-payment
v1.7.0
Published
Universal web payment & subscription billing engine with multi-provider architecture (Polar, Stripe, etc.)
Maintainers
Readme
@umituz/web-payment
Universal web payment and subscription billing engine with multi-provider architecture (Polar.sh, Stripe, etc.), an HTTP adapter, a turnkey billing portal, and React bindings.
The SDK is split into an adapter-agnostic core (BillingAdapter contract, payment models, calculation primitives)
and a React presentation layer (BillingProvider, useBilling).
The HTTP adapter binds the contract to your own API; any payment backend can
be plugged in by implementing the same interface.
Features
- Multi-provider architecture with adapter-agnostic core (
BillingAdapter,PaymentServerClient) - Polar.sh client & webhook verification (
PolarBillingClient,verifyPolarWebhook) - Extensible for Stripe and future payment gateways
- HTTP adapter for your own REST backend (
createHttpAdapter) - Common checkout utilities (
buildCheckoutMetadata,readCheckoutMetadata,formatReceiptNumber) - Billing calculation primitives: minor units, percent discounts, coupon
catalogs (
createCouponCatalog), multi-currency conversion (convertAmount,currencyForLanguage), product-key codec (parseProductKey,buildProductKey), subscription lifecycle normalization (normalizeSubscriptionLifecycle) and paid-order records (buildPaidOrderRecord) - Polar.sh product catalog (
getProducts,getProductById,getAllProducts) - React provider + hooks (
BillingProvider,useBilling,useProducts) - Ready-made UI: pricing table, checkout button, status badge, billing history, customer portal link, cancel flow — all localizable
- Turnkey billing portal page (
TurnkeyBillingPage) - Strongly-typed domain models, abortable I/O
Installation
npm install @umituz/web-paymentPeers are optional — install only what you use:
| You use… | Also install | Runtime requirement |
|---|---|---|
| …/core | — | Any JS runtime (zero deps) |
| …/products | — | fetch (browsers, Node ≥ 18, workers) |
| …/react | react (≥ 18) | React DOM or React Native Web |
| root (@umituz/web-polar-payment) | react if you use the React parts | Node ≥ 18 (engines) |
react-dom is not required. The package is fully tree-shakeable
(sideEffects: false, ESM + CJS + .d.ts via tsup).
Subpath entries
Each surface pulls in only its own dependencies — importing /react
never loads server code, importing /core loads nothing at all:
// Pure domain — types, enums, mappers, the BillingAdapter contract
import { BILLING_CYCLE, parseBillingCycle, mapProduct } from '@umituz/web-polar-payment/core';
// Polar.sh product catalog over a pluggable HttpClient
import { ProductRepository, FetchHttpClient } from '@umituz/web-polar-payment/products';
// React layer: provider, hooks, components, theme tokens
import { BillingProvider, PricingTable } from '@umituz/web-polar-payment/react';
// Server-side Polar.sh operations: checkout sessions, customer portal,
// subscription management, webhook signature verification (server only!)
import { BillingClient, verifyWebhook } from '@umituz/web-polar-payment/server';
// Browser BillingAdapter over your own REST endpoints
import { createHttpAdapter } from '@umituz/web-polar-payment/http';
// Turnkey billing portal page over any adapter
import { TurnkeyBillingPage } from '@umituz/web-polar-payment/portal';
// Root entry = everything above (backwards-compatible import paths)
import { useBilling } from '@umituz/web-polar-payment';Usage
1. Wrap the app
import { BillingProvider, createHttpAdapter } from '@umituz/web-polar-payment';
const adapter = createHttpAdapter({
baseUrl: '/api/billing',
getUserId: () => session.organizationId,
});
function App({ userId, children }) {
return (
<BillingProvider adapter={adapter} userId={userId}>
{children}
</BillingProvider>
);
}2. Read subscription state
import { useBilling } from '@umituz/web-polar-payment';
function PlanBadge() {
const { status, loading } = useBilling();
if (loading) return null;
return <span>{status.plan}</span>;
}3. Start a checkout
import { useBilling } from '@umituz/web-polar-payment';
function UpgradeButton({ productId }) {
const { startCheckout } = useBilling();
return (
<button onClick={() => startCheckout({ productId, billingCycle: 'monthly' })}>
Upgrade
</button>
);
}4. Sync after a checkout redirect
import { useEffect } from 'react';
import { useBilling } from '@umituz/web-polar-payment';
function CheckoutReturn() {
const { syncSubscription } = useBilling();
useEffect(() => {
void syncSubscription();
}, [syncSubscription]);
return null;
}5. Pricing table — the secure pattern
Fetch products on your server and pass them down; no access token ever reaches the browser bundle:
// server.ts
import { getAllProducts } from '@umituz/web-polar-payment/products';
const products = await getAllProducts(
{ apiToken: process.env.POLAR_OAT_TOKEN! }, // server-side secret
{ isRecurring: true },
);
// PricingPage.tsx
<PricingTable products={products} ctaLabel="Subscribe" />⚠️ OAT tokens grant full account access — never ship them to a public browser bundle. The
apiTokenprop onPricingTableexists for local development only.
6. Localize any component
Every component takes an optional labels subset and locale:
<SubscriptionStatusBadge
loading={false}
status={status}
locale="de-DE"
labels={{ statuses: { active: 'Aktiv' }, endsPrefix: 'endet' }}
/>7. Own REST backend — ./server + ./http
When the backend is your own API worker (any runtime with fetch), split the
work with the two transport entry points:
// api/billing.ts — server side
import {
BillingClient,
verifyWebhook,
parseWebhookEvent,
asCheckoutCompleted,
asSubscriptionChanged,
asOrderPaid,
} from '@umituz/web-polar-payment/server';
const billing = new BillingClient({
apiToken: env.POLAR_ACCESS_TOKEN!, // OAT token, server only
sandbox: env.POLAR_SANDBOX === 'true', // sandbox-api.polar.sh
});
// Checkout: POST /v1/checkouts with `products: [id]` — metadata is copied
// onto the order/subscription. Never collect card data yourself: redirect
// the browser to `checkout.url` (Polar-hosted, PCI scope stays SAQ-A).
const checkout = await billing.createCheckout({
productId,
successUrl: `${appUrl}/billing/return?checkout_id={CHECKOUT_ID}`,
externalCustomerId: user.id, // links your user to the Polar customer
metadata: { organizationId: user.orgId },
});
// Dynamic amount (bookings, pay-what-you-want floors): an ad-hoc fixed
// price is created on the checkout session, catalog product stays intact
const bookingCheckout = await billing.createCheckout({
productId: bookingProductId,
amountCents: 2500,
currency: 'usd',
allowDiscountCodes: false,
metadata: { bookingId },
});
// One-time products (digital goods): POST /v1/products with a fixed price
const product = await billing.createProduct({
name: 'Ultralight Gear Course',
amountCents: 7900, // smallest currency unit
metadata: { creatorId },
});
// Managed billing portal (payment methods, invoices, cancellation)
const { url } = await billing.createPortalSession(customerId, appUrl);
// Cancel at period end (reversible) vs revoke (immediate)
await billing.updateSubscription(subscriptionId, { cancelAtPeriodEnd: true });
// Webhooks: Standard Webhooks spec — verify the RAW body, before JSON.parse
const raw = await request.text();
if (!(await verifyWebhook(raw, request.headers, env.POLAR_WEBHOOK_SECRET))) {
return new Response('invalid signature', { status: 401 });
}
// Then parse the (still raw) body into a typed event view
const event = parseWebhookEvent(raw);
const sale = event && asCheckoutCompleted(event); // checkout.completed
const change = event && asSubscriptionChanged(event); // subscription.* lifecycle
const paid = event && asOrderPaid(event); // order.paid (renewals)The browser side binds the same BillingAdapter contract to six endpoints under
one base path — implement them on your worker to match:
// app/billing.ts — browser side
import { createHttpAdapter } from '@umituz/web-polar-payment/http';
const adapter = createHttpAdapter({
baseUrl: '/api/billing',
getUserId: () => session.organizationId, // used when a call has no id
});
// GET /status?userId= POST /checkout { productId, billingCycle?, ... }
// POST /sync { checkoutId? } GET /history?userId=
// POST /cancel { reason? } GET /portal?userId=Failures return a { "error": string | { "message": string } } envelope with
a non-2xx status; the adapter surfaces it as Error("detail (HTTP status)").
8. Turnkey billing page — ./portal over any adapter
TurnkeyBillingPage composes the whole portal (plan comparison, subscription
tabs, invoices, hosted-portal payment methods) over a BillingAdapter. The
host binds the adapter and the server-fetched catalog; everything else —
data loading, checkout redirects, cancellation — is wired inside:
import { TurnkeyBillingPage } from '@umituz/web-polar-payment/portal';
import { createHttpAdapter } from '@umituz/web-polar-payment/http';
// products: fetched from your server (metadata.planId tags plan keys)
<TurnkeyBillingPage
adapter={createHttpAdapter({ baseUrl: '/api/billing', getUserId: () => orgId })}
products={products}
config={{ brandName: 'Acme', supportEmail: '[email protected]' }}
/>Prefer composing yourself? createPortalClient({ adapter, products })
returns the portal's BillingApiClient seam (plus selectPlan /
openPortal) for direct use with useBilling.
Error handling
Server-side failures throw BillingApiError with the HTTP status and the
raw body attached — check with isBillingApiError(error). Browser-side
adapter failures surface as plain Error values carrying the endpoint's
{ "error": ... } envelope detail and the HTTP status.
Architecture
src/
├── core.ts / products.ts / react.tsx # subpath entries (+ server, http, portal)
├── domain/ # Pure types + interfaces (no I/O)
│ ├── entities/ # Subscription, Checkout, Order, ...
│ ├── enums/ # SubscriptionStatus, BillingCycle, ...
│ ├── interfaces/ # BillingAdapter contract
│ ├── utils/ # minor-unit money math
│ └── mappers/ # snake_case DTO → camelCase domain
├── infrastructure/ # Transport, repositories, utilities
│ ├── http/ # HttpClient (Strategy, AbortSignal-aware)
│ ├── query/ # QueryBuilder (Builder)
│ ├── pagination/ # PageIterator (Iterator)
│ ├── services/ # ProductRepository, BillingClient,
│ │ └── http/ # createHttpAdapter (six-endpoint contract)
│ ├── constants/ # SUBSCRIPTION_STATUS, API base URL
│ └── utils/ # validation, security, type-guards
└── presentation/ # React layer
├── context/ # BillingContext (race-safe refresh)
├── hooks/ # useBilling, useProducts
├── navigation/ # NavigationStrategy
├── portal/ # Turnkey billing portal (page + client)
├── theme/ # VisualTokens (self-contained)
└── components/ # Provider + UI componentsPatterns in use
- Adapter —
BillingAdapterinterface, HTTP implementation - Repository — one repository per business operation
- Strategy —
HttpClient(swapfetchfor tests),NavigationStrategy - Builder —
QueryBuilderfor URL search params - Iterator —
PageIteratorfor paginated Polar.sh lists - Error as a value —
BillingApiErrorcarries status + raw body
Design decisions
- Dependency direction points inward.
presentationandinfrastructuredepend ondomain;domaindepends on nothing. This is what lets each subpath ship with only its own dependencies. - VisualTokens are self-contained rather than depending on a shared
design-system package: a billing SDK must be droppable into any app
without dragging a UI framework along. Override styles via
labels,locale, and component composition instead. - Localization via prop injection, not an i18n framework —
labelsobjects with English defaults keep the runtime dependency-free while still allowing full translation. - Optimistic-free state:
BillingProviderserializes refreshes behind a generation counter; a slow earlier response can never overwrite a newer one.
Development
npm run typecheck # tsc --noEmit
npm run lint # eslint (flat config)
npm test # vitest — 170 tests (domain, infra, presentation)
npm run build # tsup — CJS + ESM + d.ts for every subpath entry
npm pack --dry-run # inspect the publishable tarballLicense
MIT
