@hjam91/billing
The app-side client for a billing-kit service: one shared Stripe billing backend that many apps use. Your server
asks it "may this account do this?" and it answers from Stripe's subscriptions, trials, plans, features, credits and
usage limits — so the app never stores billing state itself.
- Zero runtime dependencies. ESM, with TypeScript types. Node >= 20, Cloudflare Workers, Deno and bundlers.
- Fail-open by design: entitlement checks are cached and keep working through a billing outage.
- Entitlements, feature checks and usage tracking, Stripe Checkout and the customer portal, plan changes and add-ons,
signed webhook verification, a Hono gate, and an optional React billing card.
SDK: MIT. The billing service is a hosted product.
Install
npm install @hjam91/billing
hono and react are optional peer dependencies, needed only for @hjam91/billing/hono and @hjam91/billing/react.
0.11.0: the pricing editor
// server (a scoped key with read + config + pricing, from the service owner)
app.route('/super-admin/billing/pricing', billingPricingRoutes(createBillingAdmin({ baseUrl, appId, key }), { canManage: (c) => isSuperAdmin(c) }));
// browser
<PricingEditor basePath="/super-admin/billing/pricing" /> // edit ladders and prices, preview, save, move subscribers
0.10.0: tiered plans (priced by a count your app reports)
// billing.config.ts — the ladder is the source of truth; the service renders it as one tiered Stripe price
plans: { masjid: { price: { currency: 'usd', interval: 'month', tiers: [{ up_to: 10, amount: 2500 }, { up_to: 25, amount: 3900 }, { up_to: 500, amount: 19900 }] }, unit: 'students' } }
await billing.checkout({ accountId, plan: 'masjid', quantity: students, successUrl, cancelUrl }); // starts at the right tier
const r = await billing.setQuantity(accountId, students); // idempotent: unchanged | applied (now, prorated up a tier; no proration within) | scheduled (down a tier, period end) | requires_action
if (r.subscription?.over_max) contactUs(r.subscription.reported_quantity); // past the ladder: still active, held at the top tier
const { plans } = await billing.plans(); // plan.tiers [{from, up_to, amount}], max_quantity, unit
await billing.changePlan(accountId, 'masjid', { quantity: 6 }); // another ladder, with the count
Above the ladder, Checkout and plan changes throw custom_pricing_required; the owner sets a custom plan or exempts the account.
setQuantity is changeQuantity under its new name. Needs a service on migration 0018.
0.8.0: discounts and offers
Needs a billing service with migration 0016. Owner-made discount codes customers type, and automatic offers.
// Before Checkout: is the typed code good, and what does the first period cost?
const d = await billing.checkDiscount(orgId, typed, { plan: 'pro' });
if (!d.valid) showError(d.reason); // unknown | inactive | expired | used_up | not_first_time | plan_not_eligible
else show(`${d.discount.label}: ${d.plans[0].first_amount} instead of ${d.plans[0].amount}`);
const { url } = await billing.checkout({ accountId: orgId, plan: 'pro', successUrl, cancelUrl, discountCode: typed });
// Offers the account may take now: a comeback offer (lapsed), trial over (trial_ended), a save offer (canceling).
for (const o of await billing.offers(orgId)) {
if (o.audience === 'canceling') await billing.acceptOffer(orgId, o.id); // discount on, renewal back on
else await billing.checkout({ accountId: orgId, plan: o.plans[0].plan, successUrl, cancelUrl, offerId: o.id });
}
checkDiscount never throws for a code that cannot be used: it answers {valid: false, reason}. Checkout re-checks
and throws BillingError 409 discount_invalid (details.reason) or offer_not_eligible.
- Send at most one of
discountCode, offerId, promotionCode; none with several covers.
acceptOffer acts on the subscription the account OWNS: gate it with your canManage, like checkout.
- Admin (
createBillingAdmin): discounts(), createDiscount({code, percentOff | amountOff + currency, duration, durationInMonths?, plans?, maxRedemptions?, firstTimeOnly?, expiresAt?, note?}), deactivateDiscount(id),
offers(), createOffer({name, audience, …terms, afterDays?, withinDays?, headline?, active?}),
updateOffer(id, {active?, headline?, name?, afterDays?, withinDays?}) (never the money). Creating needs a key with
the pricing scope; on an app billed through the service owner's Stripe account only the owner creates them.
- Admin, since 0.9.0:
redemptions({accountId?}) answers {redemptions: RedemptionAdminView[]}, every code and offer
redemption newest first (at most 1000) with its subscription, plan, subscription_status and discount_active
(the subscription still carries a discount); read scope. removeDiscount(accountId, {subscriptionId?}) ends the
discount on the account's own live discounted subscriptions so the next invoice is full price, and answers the
account status (support scope, like cancel; 404 discount_not_found when there is none, 409
operation_in_progress under a pending plan change). The code or offer itself is untouched.
- Admin, since 0.13.0:
grantFreeMonths(accountId, {idempotencyKey, months?, reason?}) gives the account's own paying
monthly subscription free renewals (100% off from now; it stays active; rewards add up; a retried key answers the
first grant) and answers a FreeMonthsGrant (support scope; 409 no_subscription → give a trial instead,
subscription_ending, interval_not_supported, idempotency_key_reused). freeMonths(accountId) lists the grants
(read). AccountStatus.first_paid_at says when the account first paid real money (absent = never).
- Since 0.14.0:
billing.setExternalSubscription(accountId, source, {eventId, plan, status, periodEnd, …}) reports a
subscription bought outside Stripe (source 'app_store', 'play_store', …): idempotent per eventId, an older
eventAt changes nothing; it answers the status with outcome ('applied' | 'stale' | 'replayed').
clearExternalSubscription(accountId, source) forgets it. Entitlement is the best of Stripe and the stores (a store
subscription never overrides one Stripe grants); apps that report them get Entitlement.billing_source,
AccountStatus.source and external_subscriptions. Admin: externalSubscriptions({source?, status?, accountId?})
(read). The subscription.renewal_upcoming event (opt in via event_types; renewal_notice_days, default 7) carries
RenewalUpcomingData.
billingRoutes (Hono) adds GET /offers, POST /discount {code, plan?}, POST /accept-offer {offer_id}, and
discount_code / offer_id on POST /checkout; a refused code answers its reason.
0.7.1 fixes
plans() can include the service's current trial_days and trial_mode, so apps
can display trial terms from their billing settings. These fields are optional
for compatibility with older services.
- Cached entitlement reads respect
maxStaleSeconds, including ordinary reads without fresh.
- Feature checks clear cached access after authentication failures or a kill-switch denial, so later reads cannot restore the rejected access.
- Malformed successful entitlement/status responses become
BillingError(502, 'invalid_response') and never replace a valid cached entitlement. Entitlement checks retain the configured outage policy.
No API migration is required. The default fail-open and kill-switch policies are unchanged.
Quick start (server)
The client holds your app's secret: server-side only.
import { createBilling } from '@hjam91/billing';
const billing = createBilling({
baseUrl: process.env.BILLING_URL!, // e.g. https://billing.example.com
appId: process.env.BILLING_APP_ID!,
secret: process.env.BILLING_SECRET!,
});
// Is the account entitled at all? (cached; fails open on an outage)
const ent = await billing.getEntitlement('org:42');
if (!ent.active) return paymentRequired();
// Features and usage limits
const c = await billing.check('org:42', 'ai_images');
if (!c.allowed) return limitReached(c.balance);
await billing.track('org:42', 'ai_images', 1); // atomic, idempotent; queued for retry on an outage
// Stripe Checkout and the customer portal
const { url } = await billing.checkout({ accountId: 'org:42', plan: 'pro', successUrl, cancelUrl });
const portal = await billing.portal({ accountId: 'org:42', returnUrl });
Who may act for an account is your app's decision. Check that the signed-in user may manage accountId before
calling checkout, portal or setAutoRenew.
Webhooks
The service POSTs a signed entitlement.changed (and, if you opt in, usage and lifecycle events) to your app.
import { verifyBillingWebhook } from '@hjam91/billing';
const event = await verifyBillingWebhook(request, process.env.BILLING_WEBHOOK_SECRET!, { billing });
// throws BillingWebhookError (answer 400) on a bad or stale signature; `billing` drops the cached entitlement
Hono
import { requireEntitlement, requireFeature, billingRoutes } from '@hjam91/billing/hono';
app.use('/api/pro/*', requireEntitlement(billing, (c) => c.get('orgId'))); // 402 when not entitled
app.post('/api/images', requireFeature(billing, 'ai_images', (c) => c.get('orgId'))); // 402 when over the limit
app.route('/api/billing', billingRoutes(billing, {
getAccountId: (c) => c.get('orgId'),
canManage: (c, accountId) => isOrgAdmin(c.get('user'), accountId), // YOUR rule: e.g. org admins, not members
returnUrl: 'https://app.example.com/billing',
webhookSecret: process.env.BILLING_WEBHOOK_SECRET,
}));
React
The browser talks to your backend (billingRoutes above), never to the billing service.
import { BillingCard, useBilling, useFeature, Gate } from '@hjam91/billing/react';
// A ready-made card (status, Subscribe, Manage, auto-renew) …
<BillingCard basePath="/api/billing" plan="pro" />
// … or your own UI
const { status, subscribe, openPortal } = useBilling({ basePath: '/api/billing' });
const { allowed } = useFeature('ai_images');
<Gate feature="ai_images" fallback={<Upgrade />}><ImageButton /></Gate>
Caching on Workers
import { kvStore } from '@hjam91/billing/kv';
const billing = createBilling({ baseUrl, appId, secret, cache: kvStore(env.BILLING_KV), waitUntil: ctx.waitUntil.bind(ctx) });
Failure behaviour
| Situation |
What checks answer |
| Service slow, down, 5xx, timeout |
The last known answer (up to maxStaleSeconds, default 7 days); with nothing cached, allowed (reason: 'unverified', source: 'fail_open') and a warning. failOpen: false denies instead. |
| 401 / 403 / 404 (wrong secret, wrong app id, revoked key) |
Denied (source: 'error'), logged at ERROR, onError called: a misconfiguration never means free access. failOpenOnAuthError: true restores allow. |
The operator's kill switch: 403 app_disabled, 503 service_locked_down |
onKill: 'fail_open' (default): the last known answer for a cached account, while an account with nothing cached follows failOpen; every check logs !!! KILL SWITCH at ERROR. onKill: 'deny': deny and drop the cache. |
Actions (checkout, portal, changePlan, …) never fail open: they throw BillingError.
There is deliberately no client-side kill or self-destruct: anyone holding a copied secret can edit or skip a
client, so every kill (key revocation, app disable, lockdown) is enforced by the service, and the SDK only chooses what
to serve your users meanwhile.
Config as code
// billing.config.ts
import { defineConfig } from '@hjam91/billing/config';
export default defineConfig({ features: [...], plans: { pro: { price: { amount: 1900, currency: 'usd', interval: 'month' } } } });
BILLING_URL=… BILLING_APP_ID=… BILLING_CONFIG_KEY=… npx billing-cli diff # exit 2 when the service drifted
npx billing-cli push
billing-cli needs a scoped app key with read + config (and pricing to create prices). A billing.config.ts
needs Node >= 22.18; .json / .mjs configs work on any supported Node.
API reference
Full API documentation will be published at a public URL (placeholder: API docs link). Every export carries TSDoc in
its .d.ts.
Durable usage delivery
flushUsage() checks each event's result. Applied and replayed events are acknowledged;
permanent refusals are retained as rejected records, and transient failures retain their
original idempotency key for retry. An HTTP 200 with missing results does not acknowledge
usage. Inspect usageStatus() and rejectedUsage(), correct the cause, then call
retryUsage(recordIds) and flushUsage().
The default queue is bounded and process-local. For Cloudflare D1, apply
USAGE_QUEUE_SCHEMA to your app database once and configure the adapter:
import { createBilling, d1UsageStore } from '@hjam91/billing';
const billing = createBilling({ baseUrl, appId, secret, usageStore: d1UsageStore(env.DB) });
await billing.track(accountId, 'credits', 1, { idempotencyKey: jobId });
ctx.waitUntil(billing.flushUsage());
const { pending, rejected, oldestPendingAt } = await billing.usageStatus();
A configured persistent queue writes the event before attempting its first request.
Schedule flushUsage() in a background job as well, so idle apps recover after an outage.
Storage failures are logged and never reported as successful persistence. Queue scope
includes service URL and app ID. Keep the database server-side: records may contain the
usage properties supplied by your app. Delivery is at least once; service idempotency
prevents duplicate counting. The service retains deduplication keys for 90 days, so recover
or resolve rejected records within that window rather than replaying older records blindly.
Custom stores implement UsageStore from @hjam91/billing/usage: put, remove, list
and status. Resolve each operation only after durable storage succeeds. Operations may
be called concurrently; the application owns retention and access control.
Seat quantities and invoice billing
const preview = await billing.previewQuantity(accountId, 12, { subscriptionId });
await billing.changeQuantity(accountId, 12, {
subscriptionId, prorationDate: preview.proration_date,
});
await billing.cancelScheduledChange(accountId, { subscriptionId });
Quantity changes use the same explicit proration and scheduling options as plan changes.
Scheduled changes appear on SubscriptionView.scheduled_change. The application must
check that the signed-in user can manage the account before invoking these actions.
Business billing is opt-in through app settings or config-as-code: automatic_tax,
collect_tax_id, collection_method and days_until_due. For an app configured with
collection_method: 'send_invoice', use invoiceSubscription(accountId, plan, {email, quantity, customerName}); its result includes the hosted invoice URL and due date.
Automatic card collection remains the default. Configure the relevant Stripe tax settings
before enabling automatic tax.
Support integrations can list admin.purchases(accountId) and call
admin.refundPurchase(accountId, purchaseId, {access: 'keep' | 'revoke', note}). The
service computes the full remaining refundable amount. The explicit access policy controls
remaining credits and lifetime access; it does not reverse already consumed credits.
Complete billing page