@playstack/billing
Provider-neutral subscription projection, hosted billing actions, and entitlement synchronization.
Reference: @playstack/billing@0.1.0-beta.5 · TypeScript · MIT licence
Free. MIT licensed. Check preview availability before installing. See package access.
@playstack/billing keeps a rebuildable local projection of provider-owned customers and subscriptions. Provider adapters own checkout, customer portals, and normalized webhook translation; entitlements remain the application-facing authorization boundary.
Install
After confirming preview access, install the package at your application's shared Playstack version:
npm install --save-exact @playstack/billing@0.1.0-beta.5Check the peer requirements below before choosing a runtime or provider.
Define plans and compose
import { createBilling, definePlans } from '@playstack/billing'
import Stripe from 'stripe'
import { createStripeBillingClient, stripeBilling } from '@playstack/billing/stripe'
const stripe = createStripeBillingClient(Stripe, {
apiKey: stripeSecretKey, clock,
httpClient: Stripe.createNodeHttpClient(),
configuration: { maxNetworkRetries: 2, timeout: 20_000 },
})
const billing = createBilling({
provider: stripeBilling(stripe, { instance: 'subscriptions', clock }),
persistence,
entitlements,
entitlementConsistency: 'transactional',
events,
clock,
plans: definePlans({
pro: {
prices: {
monthly: {
provider: 'stripe',
instance: 'subscriptions',
id: 'price_pro_monthly',
},
},
entitlements: [{ entitlement: 'packages.pro', value: true }],
trial: {
durationMs: 14 * 24 * 60 * 60_000,
graceMs: 7 * 24 * 60 * 60_000,
graceEntitlements: [{ entitlement: 'workspace.read', value: true }],
},
},
}),
})The provider requires this dedicated client construction. It preserves the actual SDK instance and normal non-Checkout behavior; native Checkout uses a fresh guarded SDK per submission, with one POST admission bound to its original key and replay window. An ordinary SDK client is rejected. Pass the same trusted clock throughout. Custom transports must not retry or follow redirects internally. Native escape-hatch calls remain explicitly unmanaged.
Create checkout and portal sessions only from authenticated routes. Pass only verified, normalized provider events from @playstack/webhooks to handleWebhook().
Configuration
| Property | Required | Purpose |
|---|---|---|
provider | Yes | One provider instance and its native-client escape hatch. |
plans | Yes | Code-defined prices, grants, legacy plans, and optional local trials. |
persistence | Yes | Customers, current subscriptions, immutable revisions, and trial eligibility. |
entitlements | Yes | Replaces independently scoped subscription and trial grant sources. |
entitlementConsistency | Yes | Selects transactional for a shared store or eventual for durable cross-store projection. |
events, clock | Yes | Provider-neutral lifecycle events and deterministic time. |
portalSessions | No | Opt-in durable Portal operations with explicit keys, encrypted receipts and fresh-intent admission. |
customerBootstrap | No | Opt-in permanent single-submission Customer creation; requires actor and qualified composition. |
pastDueGraceMs | No | Access grace applied to past-due subscriptions; defaults to seven days. |
admitSubscriptionSource | No | Transaction-bound admission against the host's current subscription mapping. |
convertTrial | No | Transaction-bound trial-conversion decision over accepted provider facts, independent of paid grants. |
Every provider reference includes { provider, instance }. Compose separate
billing services for multiple Stripe accounts or other providers. Customer,
price, subscription, checkout, webhook, and entitlement-source identities stay
isolated by that instance.
Subscription state and repair
const current = await billing.getSubscription(accountId)
const subscriptions = await billing.listSubscriptions(accountId)
const revisions = await billing.listSubscriptionHistory(accountId)
await billing.reconcileSubscription(accountId, current.id)Each accepted projection stores the provider event ID and occurrence time.
Exact retries and older events are no-ops, while every accepted state is added
to immutable history. Scheduled provider transitions appear as pendingPlan,
pendingProviderPriceId, and pendingChangeAt; the current plan remains
authoritative until a later provider event applies the transition.
For an application-owned current-subscription mapping, configure
admitSubscriptionSource(input, transaction) and return exactly 'admit' or
'ignore'. The callback receives detached incoming facts and the current
cursor/projection after the customer lock and ordering checks. It must resolve
the host mapping on that transaction. An ignored historical subscription event
cannot replace the current subscription, clear grants or append accepted history.
The verified webhook receipt still commits, so redelivery is a duplicate.
Ignored projection-changing imports/reconciliation reject; callback failures roll
back and return a sanitized retryable conflict. Without the callback, source
replacement retains its timestamp-based policy.
Take any earlier account/membership authority locks before the prepared caller-transaction path; do not acquire them in reverse order from inside the callback while Billing's customer lock is held. Keep provider I/O outside it.
Reconciliation fetches the provider’s current subscription and sends it through the same ordering, history, event, and entitlement path. The application cannot write subscription state directly.
Adopt an existing provider projection
const customer = await billing.previewCustomerAdoption({
accountId,
providerCustomerId,
})
const subscription = await billing.previewSubscription(accountId, providerSubscriptionId)
await billing.adoptCustomer({ accountId, providerCustomerId })
await billing.importSubscription(accountId, providerSubscriptionId)Preview operations are report-only and include field-level drift. Import retrieves provider-owned state and runs it through the ordinary ordering, history, events, and entitlement path; callers cannot inject a status or plan. Running previews beside an existing projection is the supported shadow phase, and retaining the old tables until reports remain clean provides the rollback boundary.
Customer and Portal request ownership
ensureCustomer, previewCustomerAdoption and adoptCustomer capture their
original account/email or account/customer bindings before awaited work. The
provider key, local mapping, conflict preview and canonical post-save lookup keep
those values even if caller data changes. Explicit createdAt is retained;
omission still uses the clock when the row is written.
createPortal similarly owns its account, actor and return URL before authority
checks or provider I/O. Final disclosure rechecks that same account/actor; caller
mutation cannot substitute a different allowed account after the original actor
loses access. A created provider capability cannot be rolled back by that denial.
Input snapshots alone do not supply durable admission or lost-acknowledgment recovery. The separate Customer profile below adds opt-in no-replay retention; Portal has its own separate durable profile below. Retain qualified application fences for paths that have not adopted and qualified the selected profile.
Single-submission Customer creation
For restart-safe Customer creation, compose createBillingCustomerBootstrap with
its optional billing.customer-bootstrap.prisma journal, the exact backing
Billing persistence, and stripeCustomerBootstrapProvider from
@playstack/billing/customer-bootstrap/stripe. Pass the resulting service as
Billing's customerBootstrap option and supply actorId to ensureCustomer.
The instance, native client and store must match; there is no raw-creation fallback.
A permanent namespace/account/provider/instance target commits before one guarded POST. It retains the original key and request commitment, not email or request body. Unknown outcomes, lost commit acknowledgements and restarts cannot submit again, even with a new key or after provider idempotency expires. Keep the namespace stable. Native dispatch requires the actual qualified transaction fence/native runner, not a structural transaction handle.
Required host authorize and recordAction hooks keep admission/mapping changes
and evidence atomic. Provider acknowledgements survive revocation, while mapping
installation/disclosure rechecks authority after writes. The host still owns
account incarnation and authorization lock order. inspect is authorized;
reconcile requires the original key/revision, provider Customer ID and reviewed
host evidence. It validates an authoritative GET against original metadata and
body commitment without another POST. Missing/deleted Customers, changed email or
failed reads preserve the barrier. A missing local mapping requires this explicit
review even when the receipt was accepted.
This is an opt-in conservative profile. Unconfigured Customer calls, raw SDK calls and Portal retain their existing boundaries. See the package README for the full composition and adapter contract; application deployment and provider qualification remain required before removing existing safeguards.
Durable Portal sessions
Compose createBillingPortalSessions with the optional billing.portal.prisma
journal, the exact Billing store, authenticated encryption, current authorization,
required durable evidence and explicit fresh-operation admission. The Stripe
provider lives at @playstack/billing/portal/stripe, requires the same qualified
client and a pinned configuration ID, and supports trusted HTTPS custom domains.
Set Billing's portalSessions option; createPortal then requires actorId and
an explicit idempotencyKey, retaining the existing Portal authorization hook.
Admission commits before one guarded POST. Every original key remains a permanent
no-replay receipt after crashes, unknown responses and restarts. New sessions need
deliberate host-approved intent; automatically changing retry keys is unsupported.
Factual IDs persist before encryption and actor disclosure. recover reads the
encrypted local URL under current mapping/authority, required evidence, operation
locks and the original local deadline. inspect exposes safe metadata; close
removes ciphertext permanently without losing a late factual acknowledgement.
Stripe has no Portal retrieval/status/expiry API in this profile. Unknown outcomes and IDs with no saved URL stay unavailable; recovery does not create or retrieve a remote session. Default local disclosure is five minutes (the maximum), and dispatch is bounded to 60 seconds by default. Local closure/deadlines do not revoke already disclosed provider capabilities or prove provider expiry. Hosts own ciphertext cleanup, encryption keys, account policy and qualified deployment. Ordinary unconfigured Portal and raw SDK calls retain their existing behavior.
Period-end subscription commands
Command preparation and submission reauthorize on the same transaction after lock waits and required Audit/event writes, including existing and nondispatch returns. Denial rolls back admission and its evidence together. Callbacks must tolerate repeated checks and preserve the initial authority-lock order. Provider acknowledgments still commit independently of actor authority; disclosure then reauthorizes so revocation cannot erase a real provider outcome.
createBillingSubscriptionCommands() composes an optional durable journal with
the current Billing persistence and required account-user authority checks.
prepare() binds the exact actor/account/provider/subscription generation and
provider request before submission. submit() also recovers the original request
and key; inspect() returns authorized evidence.
inspectUnresolved({ accountId, actorId, context? }) discovers the one unresolved
command in this service's provider/instance. It returns a minimal key/status/
revision/time summary, including accepted unresolved pending payment, without
request, receipt, binding or customer/subscription/original-actor data. Native
persistence uses the existing unique barrier index; settled commands are absent.
The explicit inspect-unresolved operation checks authority initially and finally,
including null, plus command-specific target/schedule authority for a result.
Discovery is an advisory snapshot: it performs no provider call, claim, event or
mutation, and expiry alone does not retire uncertainty. Use the original key with
separately authorized inspection/recovery. Custom journals add the scoped
findUnresolved read; no schema change is required.
redactTerminal({ accountId, actorId, idempotencyKey, expectedRevision, context? }, tx?)
adds explicit terminal request cleanup. Configure ordinary redact-terminal
authority and the separate default-deny authorizeRedaction retention policy;
both repeat after locks/required evidence on the same transaction. Only settled
accepted/rejected commands past their original replay window qualify. Uncertainty
and unresolved pending payments refuse regardless of age.
The explicit redacted record removes prepared, raw request, full source and
original intent binding. Permanent keys/commitments/generations, compact receipt
proof and factual receipt/reviewer evidence remain. Authorized inspect can return
this variant; narrow status before reading prepared. Closed mutation keys refuse
without provider dispatch or replacement, and cleanup never releases newer work.
Identical late acknowledgments remain idempotent without restoring private material;
conflicts cannot overwrite retained facts. Delayed submit disclosure still reauthorizes.
Required evidence, cleanup and joined host writes share rollback. Caller-owned results are provisional until commit and errors must abort that transaction. Custom journals add the mutation and closed-state handling; the JSON schema is unchanged. Product retention permissions/scheduling remain host-owned; factual IDs and reviewer evidence remain retained rather than being completely erased.
Expired preparation retirement
retirePrepared({ accountId, actorId, idempotencyKey, expectedRevision, context? }, tx?)
closes only a replay-expired original prepared record: revision 1, with its
creation timestamp unchanged and no submission claim ever issued. It requires
ordinary retire-prepared authorization plus the separate default-deny
authorizePreparedRetirement(review, tx) hook. Both repeat after journal and
required-evidence waits, with ordinary authorization last. Terminal-redaction
permission alone does not authorize retirement.
Scope-before-row locks serialize claim and retirement. Claim-first refuses cleanup;
retirement-first permanently refuses later claim/submit before provider I/O.
The result is status: 'redacted', outcome: 'not-submitted', not a provider
rejection. It removes preparation/request/source/original actor, retains compact
identity/commitment and first timestamp, releases only that unsubmitted reservation,
and leaves accepted generation unchanged. A new key still needs ordinary source,
authority and generation admission. Exact prior/current revision retries cannot
release newer work or emit another event.
Required Audit/outbox, host cleanup and final authorization share rollback, including
an explicit caller transaction; completion is provisional until commit. Custom
journals add retirePrepared using the same provenance/locking rules and updated
scaffold/hash. The existing schema needs no migration. Keys and factual identifiers
remain retained; there is no TTL, automatic sweep or complete-erasure promise.
Submitting, unknown, reconciliation-required, accepted/pending-payment and rejected states remain ineligible regardless of age. Even an expired failed claim can have moved preparation into reconciliation, which this API does not relabel. Uncertain request retention uses the separate permanent quarantine profile below; authorization and age cannot manufacture evidence that submission never happened.
Permanent uncertainty request quarantine
quarantineUnresolved({ accountId, actorId, idempotencyKey, expectedRevision, context? }, tx?) removes request material only from replay-expired unknown or
reconciliation-required commands, or accepted pending payment without payment
resolution. It requires ordinary quarantine-unresolved
authority and the separate default-deny authorizeQuarantine(review, tx) hook.
Both repeat after journal and required-evidence waits, with ordinary authority
last. Caller cleanup, Audit/outbox and final refusal share rollback; results are
provisional until commit. Retention hooks perform no provider I/O.
Quarantine permanently blocks new subscription commands for the account/provider/ instance. No package API lifts that barrier. If the account must resume commands, retain its normal journal and resolve uncertainty before terminal cleanup instead. This API does not cancel remote work or prove that submission failed.
The quarantined record removes preparation/request/full source/original actor and
retains compact identity/receipt proof/commitment, first quarantine time/revision
and current revision/update time. Unknown quarantine starts without a receipt.
Its first matching late accepted acknowledgment is stored once as outcome: 'accepted',
advancing revision and accepted generation once while keeping the barrier permanent.
Equal repeats are no-ops; conflicting receipts refuse; nonaccepted late finishes
cannot change it. Factual storage is independent of current actor authority;
disclosure still reauthorizes and dispatch material remains closed. Receipt
presence is neither paid projection nor resolution of a pending invoice.
Authorized inspection returns the compact record. Scoped unresolved discovery
still finds the barrier and reports receiptRecorded with key/kind/revision/times,
without a receipt, proof, request or customer/subscription/original-actor data.
The command event uses key/revision/receipt presence, without a terminal/payment
outcome. Exact source, first-quarantine and current revision retries preserve the
first marker and any receipt. Ordinary submit/reconcile/payment resolution,
terminal redaction and preparation retirement cannot reopen quarantined work.
Prepared, submitting, applied acceptance, resolved pending payment, rejected and terminal-redacted records are ineligible. Custom journals add the mutation and compact active variant, including once-only factual acceptance generation; native adapters/scaffold/hash move together. Existing JSON schema/indexes need no migration. There is no TTL, automatic lifting, complete subject erasure or deletion of in-flight copies, retained identifiers, Audit/provider facts, WAL or backups.
For acknowledged pending payment, the compact record keeps the exact receipt and any original operator acceptance evidence. Accepted generation stays unchanged; there is no second acceptance or paid grant. The initial acknowledged form retains its first quarantine revision/time; a late acknowledgment uses the next revision. Only the initial pending form may retain reviewer evidence. The service validates known facts even if a custom journal reports an unchanged concurrent cleanup.
Quarantine and verified payment resolution serialize on the same scope/row locks. Resolution-first preserves its settled evidence and refuses cleanup; quarantine- first makes resolution closed and rolls back the losing caller's joined writes. Matching duplicate acknowledgments remain no-ops. Choose verified resolution, rather than permanent quarantine, when the account must resume commands. Retention never proves that an invoice was paid or canceled.
The Stripe adapter lives at
@playstack/billing/subscription-commands/stripe, with Prisma and memory journals
under the matching /prisma and /testing subpaths. Construct its dedicated
client with createStripeSubscriptionCommandClient(Stripe, { apiKey, httpClient: Stripe.createNodeHttpClient(), configuration: { timeout: 10_000 }, clock }) and pass the same clock to the adapter. Ordinary SDK clients are
rejected: Stripe's zero-retry setting alone still permits some connection retries.
Each explicit submission gets a fresh guard that checks the original key, path
and deadline and admits one POST to the base transport, including after body
failures. The Node HTTP transport is locally qualified; custom SDK constructors
and transports must be trusted and must not retry or follow redirects internally.
The cancellation profile supports cancel-at-period-end and
withdraw-cancellation for qualified classic single-item subscriptions. With the
server plans catalog, change-plan also supports immediate same-interval changes
that preserve quantity and anchor, explicitly selecting always_invoice and
error_if_incomplete or the bounded pending_if_incomplete profile. Prices resolve
from that catalog; callers cannot supply price IDs. Authorization receives the
full resolved target. Provider qualification
requires an active uncanceled source, paid latest invoice and positive flat
licensed prices in the same currency/interval. Paid zero-dollar discounts remain
valid. Item identity and proration time are retained in exact-request recovery.
Pending-payment preparation additionally requires an expanded modern card/Link
default payment method. receipt.planChange.outcome distinguishes applied from
pending-payment; pending receipts retain the exact invoice and expiry without
client secrets or hosted URLs. An acknowledged pending update keeps the
account/provider barrier across restart and local expiry, and submit() never
replays it. Even a paid invoice does not prove that its pending update applied.
resolvePendingPayment(input, transaction?) requires the exact invoice, expected
revision and a separate authorizePaymentResolution callback that verifies
provider evidence on the same transaction. Verified application or discard/expiry
evidence releases the barrier while retaining the original receipt and first
resolution; time alone does not. Caller-transaction results remain provisional
until commit, and errors must abort caller work. Hosts own verified-event mapping,
SCA presentation and any secret transport. Custom journals must implement
resolvePayment using the updated scaffold. Existing JSON receipts require
reviewed adoption before the required outcome discriminator is activated; no
automatic backfill or old-format reader is provided.
Apply the optional journal and BillingSubscriptionCommandScope fragment through
a reviewed application migration and update all writers together. Its accepted
generation prevents preparation from crossing another native completion while
projection lags; permanent keys and scope generations survive cleanup. New
reservation checks the captured generation under scope-before-journal locking.
Unknown outcomes keep an account/provider barrier and the original key. Replay
ends at the earlier of 23 hours and the captured period end; source changes need
review. A separate operator gate receives the exact record/key/decision to bind
reviewed evidence, then an expected revision guards reconcile().
Operator reconciliation rechecks that same trusted gate after journal and required Audit/outbox waits, then checks current command/account authority last on the same transaction. Both operator calls see the original review record and decision, including identical terminal retries. A late denial rolls back the resolution, generation and evidence together. Hooks must support repeated checks and retain their initial authority-lock order; factual provider acknowledgments remain independently persisted.
Command acknowledgment never updates grants or subscription facts. Verified webhooks/authoritative reconciliation remain responsible for those. Provider GET state, elapsed time and arbitrary SDK errors do not prove safe rejection. Configure bounded SDK timeouts and shutdown separately. Native locks do not serialize Portal/Dashboard writers or provide provider-side compare-and-swap; live Stripe qualification remains separate from the local checks. Cross-interval, quantity-changing and other unsupported financial workflows retain the qualified Portal/provider path. Existing provider/Portal compositions remain supported.
A separate withdraw-scheduled-plan-change command accepts an expected schedule
ID and binds the native pending plan terms. Its qualified Stripe profile releases
one attached active, release-ending price/quantity schedule on an uncanceled
single-item subscription. It preserves cancellation dates, retains the original
key and deadline, and records only the released schedule/subscription identity
and time. It does not clear pending state or grant access; verified projection
still owns those changes. Accepted receipts survive later projection changes,
while unresolved changed sources require reconciliation. Schedule creation,
richer phase programs and combined release/reactivation remain separate.
An explicit schedule.cancellation: 'preserve' mode also admits the qualified
active pending-plan source with standard period-end cancellation. Providers must
advertise both schedule-release capabilities, including
supportsCanceledScheduleRelease: true. The mode is committed to the original
key; omission retains the uncanceled-only profile. Stripe still receives exactly
one preserve_cancel_date=true POST and the receipt contains only release facts.
After accepted release, verified provider projection must establish that pending
schedule terms are gone and confirm the actual cancellation state. The existing
withdraw-cancellation command can then run under its own key if cancellation
remains. Unknown release work blocks the next command. Each stage owns its
evidence, authorization and recovery; application orchestration owns a single
user-facing reactivation workflow. Custom cancellation dates, atomic compound
operations, refunds and live provider qualification remain separate.
Withdrawal accepts the unstarted future phase_start anchor produced by native
schedule-plan-change, after verified projection establishes matching pending
terms. It preserves the current anchor/period and refuses at the phase boundary.
Current-phase phase_start and unknown future anchors remain outside the profile.
Release qualification accepts bounded opaque phase/item metadata, including application plan labels. It never treats those fields as account authority or includes them in the command request/receipt. For an uncanceled pending downgrade, withdrawal alone undoes the future program; no redundant false cancellation toggle is needed. Current subscription metadata and access stay separate from the factual release receipt, and verified projection clears the native pending state. Phase-rewriting metadata requirements remain strict.
schedule-plan-change adds or replaces one future price phase on an already
attached qualified active schedule. Server-catalog targets may switch
monthly/annual intervals at the captured period end while preserving quantity
and currency. This profile requires undiscounted, untaxed source evidence,
preserves the supported current phase, and refuses
richer or unobserved future terms, and binds one original-key schedule update.
Its factual future-change receipt never activates paid grants or updates native
pending state. Creating/attaching schedules, immediate cross-interval changes
and combined cancellation reactivation remain separate.
A known renew source can enter the same plan-change command only when it has
one total/current phase, no native pending change and no unqualified renewal
metadata. The prepared request retains the observed source behavior; its existing
POST explicitly sets the release-ending future program. The response must prove
release behavior. Unknown renewal structures and still-renewing acknowledgments
remain unsupported/uncertain, with no extra public command or intermediate POST.
attach-subscription-schedule adds a separate durable from_subscription
operation with no plan change. It accepts one guarded original-key create for a
qualified schedule-free source, then retains the returned schedule ID, creation
time and actual release/renew behavior. Unknown outcomes retain their permanent
barrier across replay expiry; a later GET is not acceptance evidence. Follow-on
plan changes still qualify the resulting schedule independently. Attachment does
not imply a release-ending profile, paid target access or automatic orchestration.
Reading inside a caller transaction
getSubscriptionInTransaction(accountId, transaction),
listSubscriptionsInTransaction(accountId, transaction) and
listSubscriptionHistoryInTransaction(accountId, transaction) read the same
account/provider-scoped projections, cursor and history through the caller's
original physical handle. They include its uncommitted writes, start no nested
transaction and perform no provider I/O. getTrialInTransaction covers trial state.
Known root, wrong-kind and completed native handles refuse; custom persistence
must preserve the matching live-handle guard.
These methods add no authorization locks or stable snapshot: the current lookup still has separate list and cursor statements under the caller's isolation level. Authorize the operation yourself and expose read-dependent results only after the outer commit; a later caller failure must roll all joined work back.
No-card trials
For trials before payment integration, use the price-free capability:
import { createProductTrials, defineProductTrials } from '@playstack/billing'
const trials = createProductTrials({
trials: defineProductTrials({
pro: { trial: { durationMs: 14 * 86_400_000, graceMs: 0 } },
}),
persistence: trialPersistence, events, clock,
entitlementConsistency: 'disabled',
})
await trialPersistence.transaction(async (tx) => {
await trials.startTrialInTransaction({ accountId, plan: 'pro' }, tx)
})No provider, customer or price is required. BillingTrialPersistence contains
only transaction execution/assertion and trial reads/create/cancel/extension.
Existing native adapters satisfy it; a reviewed trial-only Prisma composition
needs the unchanged BillingTrial model and its chosen evidence/grant storage,
without paid Billing tables. Use transactional entitlements when Billing owns
grant projection, or disabled projection when the product owns it. Product
authorization, paid eligibility and other required local effects belong in the
same caller transaction. This profile does not infer provider conversion policy.
Full Billing uses the same trial engine with its subscription eligibility check:
const trial = await billing.startTrial({ accountId, plan: 'pro' })
const currentTrial = await billing.getTrial(accountId)
await billing.extendTrial({ accountId, expectedEndsAt: trial.endsAt, endsAt: reviewedSupportDeadline })
await billing.cancelTrial(accountId)The trial’s full grants expire at endsAt; explicitly smaller grace grants
start then and expire at graceEndsAt. Time-bounded entitlements move the
account from active to grace to expired without a timer. Trial eligibility is
create-once per account, and an active paid subscription cancels its trial
sources. Support extension uses an absolute deadline and expected current
deadline, preserving plan, original start and grace duration. Exact-target replay
does no extra work; stale targets conflict. Canceled trials cannot be revived.
An expired uncanceled trial can be deliberately extended into the future;
support authorization and limits remain application policy.
Explicit startTrialInTransaction, getTrialInTransaction,
extendTrialInTransaction and cancelTrialInTransaction methods join a caller
physical transaction. Mutations require transactional or disabled entitlement
projection, so state, events and local grants share the caller's commit. Return
values remain provisional until that commit; errors must abort it. Standalone
methods retain the existing eventual-projection option and its host-owned
reconciliation requirement.
Full Billing can use an explicit product conversion policy:
const billing = createBilling({
...billingOptions,
convertTrial({ subscription }) {
return subscription.status === 'active' && subscription.pendingUpdate === false
? 'convert'
: 'preserve'
},
})The option receives detached accepted facts/context and the physical transaction for authorized required local effects. Ordering/current-source checks precede it; stale, duplicate and ignored projections skip it. Authoritative rereads supply current facts. Preserve accepts the subscription while retaining trial authority; it does not change paid grants. Failures roll back native state, receipt admission and joined effects. Keep provider I/O outside it and native state writes in Billing. Omission retains active/trialing/past-due-grace conversion, even with grants disabled.
Stripe's pendingUpdate is false for explicit null, true for an object, and unknown
when absent; future scheduled changes remain separate. currentPeriodStart uses
a legacy start or complete aligned item starts, with mixed periods left unknown.
Both facts survive reads, history and previews; missing new facts clear old values.
Adopt the adapter and nullable fields on both current/history models together,
leaving existing rows NULL/unknown. Product access, dunning and refund policy remain
application-owned and require product/provider qualification.
Lifecycle events
Billing emits provider-neutral events for subscription updates and terminal cancellation, cancellation scheduling and resumption, scheduled and applied plan changes, invoice payment, payment failure, provider trial ending, and local trial start/extension/cancellation and durable subscription-command evidence. Notification, audit, and reconciliation code therefore does not need Stripe payload knowledge.
Boundary
The provider remains the subscription source of truth, while product code checks stable entitlements rather than plan or price names. The application owns raw-body webhook routing and verification, redirects, migrations, reconciliation scheduling, and product-specific downgrade behavior. billing.provider.client exposes the exact native billing client.
Durable checkout and usage
Checkout now requires an explicit, globally unique idempotencyKey. Persistence atomically reserves immutable request identity before provider I/O and records completed or unknown outcomes. getCheckoutAttempt() supports reconciliation. Retry ambiguous outcomes with the same key; use a new key only for an intentional new checkout, not to bypass an unknown result.
Trusted server code can include terms: { metadata, expiresAt } in a checkout
request. Terms are copied before asynchronous work, persisted and compared on
exact retries. Stripe applies metadata to both Checkout and the resulting
subscription; accountId and plan are reserved. Use opaque lifecycle/deployment
bindings, never bearer proofs, secrets or personal data. Host customer/checkout
mappings and current account/lifecycle authorization remain required.
expiresAt is an absolute Unix-millisecond deadline with whole-second precision.
Stripe requires 30 minutes–24 hours remaining at creation. When injecting a clock,
pass the same one to Billing and stripeBilling(client, { clock }). Retries and
stored-link reuse retain the original deadline, never a sliding TTL; elapsed
terms cannot admit a fresh checkout or an expired redirect. Prepared recovery can
reconcile the original provider operation within its original replay window;
it does not extend either deadline. Checkout expiry does not replace webhook lifecycle checks or
resolve an unknown provider outcome. These terms use the existing attempt JSON
field rather than requiring new columns.
createBillingUsage() records idempotent usage and claims bounded aggregates for provider reporting. Adopters supply the persistence/reporting seams and product allowance, overage and quota policies. A usage total is not an atomic quota reservation.
The Stripe v1 reporter requires createStripeBillingUsageClient(Stripe, { apiKey, httpClient: Stripe.createNodeHttpClient(), configuration: { timeout: 10_000 }, clock }). Use the same trusted clock on the reporter. Each explicit report has
one guarded POST admission with the original identifier, key and replay window,
including after SDK connection/body failures. Ordinary SDK clients are rejected;
custom transports must not retry or follow redirects internally. Unknown outcomes
remain quarantined for reviewed reconciliation, and submission receipts do not
prove asynchronous invoice inclusion.
Subscription projection holds a customer lock across ordering checks, history and transactional entitlement projection. Stripe period normalization supports subscription-level and item-level period fields; the earliest item boundary is the conservative aggregate end. Refund/dispute policy and resource-license grants are separate from subscription billing. Test shadow/import/reconciliation and rollback against real application data before cutover.
Customer and promotion settings
The Stripe provider's checkout input selects either an existing customerId or
an authorized customerEmail for Checkout-owned customer creation. The latter
preserves Stripe's customer_email behavior without inventing a customer ID.
These profiles are exclusive. The higher-level Billing service retains its
ensureCustomer({ email }) profile and creates/adopts the customer before checkout.
Applications that already own canonical customer/checkout mappings can use the
provider profile with their existing durable journal and reconciliation policy.
terms.allowPromotionCodes explicitly preserves the chosen promotion-code
behavior in the prepared Stripe payload. Omitted, false and true remain
distinct immutable inputs. Fixed coupon selection and an explicit promotion-code
flag cannot be combined in the supported Stripe profile.
Load the original journal entry before applying fresh-request defaults. The
provider's pure assertCheckoutReplay(prepared, input) checks the original
commitment, key, customer selection, email, promotion settings and complete
canonical request before submission. It performs no provider I/O and does not
apply creation-time expiry rules to an existing request. Recovery submits the
original prepared bytes; changed same-key input requires refusal rather than a
new provider operation.
The provider does not own a key registry or authorize retries. The host journal must serialize reservation, recheck live account/lifecycle authority, retain permanently closed keys and reconcile uncertain/expired operations. Treat the email-bearing prepared body as private retained material: erase it when eligible while preserving its commitment and closed tombstone. Native closed-key rejection and URL redaction remain part of the Billing service's mapped-customer profile.
API entry points and requirements
Reference snapshot: @playstack/billing@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.
| Public entry point | Declaration file |
|---|---|
@playstack/billing | ./dist/index.d.ts |
@playstack/billing/errors | ./dist/errors.d.ts |
@playstack/billing/prisma | ./dist/prisma.d.ts |
@playstack/billing/testing | ./dist/testing.d.ts |
@playstack/billing/subscription-commands/prisma | ./dist/subscription-command-prisma.d.ts |
@playstack/billing/subscription-commands/testing | ./dist/subscription-command-testing.d.ts |
@playstack/billing/subscription-commands/stripe | ./dist/subscription-command-stripe.d.ts |
@playstack/billing/usage/prisma | ./dist/usage-prisma.d.ts |
@playstack/billing/usage/stripe | ./dist/usage-stripe.d.ts |
@playstack/billing/usage/testing | ./dist/usage-testing.d.ts |
@playstack/billing/stripe | ./dist/stripe.d.ts |
@playstack/billing/webhooks | ./dist/webhooks.d.ts |
@playstack/billing/package.json | No TypeScript declaration (asset or metadata export). |
@playstack/billing/customer-bootstrap/prisma | ./dist/customer-bootstrap-prisma.d.ts |
@playstack/billing/customer-bootstrap/testing | ./dist/customer-bootstrap-testing.d.ts |
@playstack/billing/customer-bootstrap/stripe | ./dist/customer-bootstrap-stripe.d.ts |
@playstack/billing/portal/prisma | ./dist/portal-prisma.d.ts |
@playstack/billing/portal/testing | ./dist/portal-testing.d.ts |
@playstack/billing/portal/stripe | ./dist/portal-stripe.d.ts |
Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.
Peer dependencies
This package declares no peer dependencies. Its ordinary dependencies are resolved by the package manager.
For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.