Billing
Configure web billing and optional mobile IAP with server-authoritative entitlements.
The application supports Polar, Stripe, and Dodo Payments behind one provider-neutral application
boundary. A deployment selects exactly one adapter for web billing with BILLING_PROVIDER, and can
optionally enable MOBILE_IAP_PROVIDER=revenuecat as an orthogonal native store channel (with
optional Superwall paywalls on iOS and Android). Web providers are not combined, and only verified
webhooks or reconciliation for enabled channels can change local entitlements.
This is billing for the SaaS built from the foundation. It is separate from the seller's own
purchase and fulfillment design in docs/commercial/fulfillment.md.
Modes and provider selection
| Mode | Configuration | Expected behavior |
|---|---|---|
| Local zero-key | selected provider credentials/products all unset | app trial works; plans are empty; checkout/portal are unavailable; no provider IO |
| Automated test | normalized fake provider plus disposable Postgres | ordering, replay, rollback, and entitlement run without external calls |
| Sandbox/test | complete selected-provider test configuration | hosted checkout, portal, and signed lifecycle events without a real charge |
| Production | complete selected-provider live configuration | real lifecycle; release smoke and incident ownership are required |
Choose one:
BILLING_PROVIDER=polar # or stripe or dodoConfiguration is atomic for the selected provider. Leave every selected-provider credential and product/price ID unset for zero-key development. Once any is set, provide its API credential, webhook secret, and at least one unique plan mapping:
| Provider | Credentials | Plan identifiers | Environment |
|---|---|---|---|
| Polar | POLAR_ACCESS_TOKEN, POLAR_WEBHOOK_SECRET, POLAR_ORGANIZATION_ID | POLAR_*_PRODUCT_ID | POLAR_ENVIRONMENT=sandbox|production |
| Stripe | STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET | STRIPE_*_PRICE_ID | determined by the Stripe key |
| Dodo Payments | DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_SECRET | DODO_PAYMENTS_*_PRODUCT_ID | DODO_PAYMENTS_ENVIRONMENT=test_mode|live_mode |
Each provider has monthly and yearly display-price variables matching its identifier prefix. Displayed price is application configuration, not provider authority. Compare identifier, interval, currency, and charged amount during the release smoke.
Inactive-provider variables are ignored. This permits deliberate provider switching without allowing
two providers to mutate the same entitlement. Switching an application that already has customers
requires a migration and reconciliation plan; changing BILLING_PROVIDER alone is not a
live-customer migration.
Boundaries
packages/billing
provider.ts provider-neutral methods
types.ts normalized customers/subscriptions/payments/events
providers/polar.ts Polar SDK and normalization
providers/stripe.ts Stripe SDK and normalization
providers/dodo.ts Dodo SDK and normalization
providers/revenuecat.ts RevenueCat webhook auth, event normalization, and REST API v2
apps/server/src/domains/billing
routes.ts session endpoints and selected web/mobile webhook routes
service.ts plan mapping, event transaction, notifications, app trial
repository.ts provider-neutral customers/subscriptions/event ledger
entitlements.ts sole paid-access policyMobile in-app purchases (RevenueCat)
Web deployments continue to select exactly one web adapter through BILLING_PROVIDER. Native iOS
and Android apps can optionally enable RevenueCat as an orthogonal store-billing channel:
MOBILE_IAP_PROVIDER=revenuecat # or disabled (default)Configuration is atomic when MOBILE_IAP_PROVIDER=revenuecat. Leave all REVENUECAT_* variables
unset for zero-key development (POST /webhook/revenuecat returns 503). Once any variable is set,
provide:
REVENUECAT_WEBHOOK_SECRET(sharedAuthorizationheader secret verified withcrypto.timingSafeEqual);REVENUECAT_API_KEY_V2andREVENUECAT_PROJECT_ID(Bearer credentials for RevenueCat REST API v2 reconciliation);REVENUECAT_ENTITLEMENT_ID(the RevenueCat entitlement identifier granted by store plans);- at least one of
REVENUECAT_MONTHLY_PRODUCT_IDorREVENUECAT_YEARLY_PRODUCT_ID(single ID or comma-separated store SKUs, unique across plans).
When MOBILE_IAP_PROVIDER=disabled, POST /webhook/revenuecat fails closed with 404. Missing or
invalid Authorization headers fail closed with 403.
Single-owner-per-subscription isolation keeps web and mobile store billing from colliding:
- RevenueCat writes into
subscriptionsandbilling_webhook_eventsunderprovider = 'revenuecat'keyed byoriginal_transaction_id; provider_customersis unique on(user_id, provider)so a RevenueCat customer correlation never overwrites a Polar, Stripe, or Dodo customer ID used for web portal sessions;users.is_premiumand effective subscription selection evaluate all rows for a user, preferring an entitled subscription over an expired one;- client SDK state on iOS/Android never mutates server entitlements, only verified webhooks and server-side REST API v2 reconciliation persist changes;
- mobile paywalls can optionally render through Superwall (
apps/mobile/lib/paywall.ts, routed throughlib/purchases.tsviaCustomPurchaseControllerProvider) and fall back cleanly to RevenueCat Paywalls when Superwall keys are unset.
Supported RevenueCat webhook events:
INITIAL_PURCHASE(period_type=TRIAL→trialing, otherwiseactive),NON_RENEWING_PURCHASE→subscription.created;RENEWAL→subscription.active;PRODUCT_CHANGE(readsnew_product_id) →subscription.updated;UNCANCELLATION→subscription.uncanceled;CANCELLATIONwithcancel_reason=CUSTOMER_SUPPORT→ immediatesubscription.revoked; all other cancellations → scheduledsubscription.canceledretaining access untilexpiration_at_ms;BILLING_ISSUE→payment.failed(past_due);EXPIRATION→subscription.revoked;SUBSCRIPTION_PAUSED→subscription.updated(paused);TRANSFER→ reassigns RevenueCat subscriptions between correlated Better Auth users and recomputesusers.is_premiumon both accounts.
Anonymous RevenueCat IDs ($RCAnonymousID:*) and unmapped store product IDs fail the transaction
and roll back the event claim. Reconcile RevenueCat subscriptions against REST API v2 with:
vp run --filter @app/server billing:reconcile -- --provider=revenuecat --limit=100
vp run --filter @app/server billing:reconcile -- --provider=revenuecat --apply --limit=100Raw SDK payloads stop inside their provider adapter. Hono routes, repositories, web code, and public contracts never accept a provider SDK object.
Checkout and portal
Authenticated users can list configured plans, create a hosted checkout for a configured plan, open the selected provider's portal after a provider customer exists, and fetch server-derived subscription/trial/entitlement state.
Checkout derives the user and email from Better Auth. It sends user_id and plan_type as
provider-side metadata. The return URL is UX/recovery information only and never grants access.
Stripe receives its own checkout-session placeholder; Dodo receives a plain return URL; Polar
receives its native checkout placeholder. Polar also receives the buyer address resolved by the
selected TRUSTED_PROXY_PROFILE so its hosted checkout can localize currency and calculate tax from
the buyer rather than from the API server. Keep the application origin inaccessible around that
trusted ingress.
Portal creation uses the provider customer ID stored from a verified webhook. Stripe and Dodo require that provider-side ID; Polar uses the application external customer ID. Portal-session creation remains rate-limited.
Trials and entitlements
The application has a 14-day local product trial starting at users.created_at. This is separate
from any provider-side trial.
Paid access is decided only in entitlements.ts:
| Local status | Paid access | New checkout blocked | Recovery behavior |
|---|---|---|---|
active | yes | yes | portal available |
trialing | yes | yes | provider trial |
canceled, period end still in future | yes | yes | access until exact period boundary |
past_due | no | yes | update payment method; do not double-buy |
unpaid | no | no | provider state is inactive |
paused, incomplete, incomplete_expired | no | no | no paid entitlement |
| absent or expired cancellation | no | no | app trial may still grant product access |
Provider statuses are normalized fail-closed. For example, Dodo on_hold maps to past_due and
failed maps to unpaid; Stripe and Polar lifecycle states map to the same application policy. A
scheduled cancellation remains entitled only before its provider period end.
Webhook contract
Register the endpoint matching the selected web provider (and revenuecat when
MOBILE_IAP_PROVIDER=revenuecat is enabled):
https://<api-origin>/webhook/<polar|stripe|dodo|revenuecat>The route returns 404 when the path provider is not the selected provider. It returns 503 when the selected webhook integration is intentionally unset and 403 for a missing or invalid signature.
Each adapter verifies the raw body before normalization:
- Polar uses Standard Webhooks headers and its SDK verifier.
- Stripe requires
Stripe-Signatureand constructs the event with Stripe's verifier. - Dodo requires its Standard Webhooks ID/timestamp/signature headers and official verifier.
After verification, the application:
- normalizes the provider event;
- claims
(provider, event_id)and mutates subscription/customer/access state in one transaction; - orders state using provider event time in
provider_modified_at; - commits before best-effort email/in-app notification.
Duplicate committed events are no-ops. A failed mutation rolls back the claim so the provider can retry. An older event may be claimed without overwriting newer state. Unknown products, contradictory plan metadata, and missing user correlation fail the transaction instead of defaulting to a paid plan.
Subscribe only to lifecycle events handled by the selected adapter:
- Polar: subscription created/active/updated/canceled/uncanceled/revoked/past-due and order paid.
- Stripe: customer subscription created/updated/deleted and invoice payment succeeded/failed.
- Dodo: payment succeeded/failed and subscription active/renewed/plan-changed/updated, update-payment-method, cancelled/expired/on-hold/failed/paused.
Provider-valid unrelated events are acknowledged and recorded as unhandled. Treat a newly required event as an adapter/version change with a regression fixture.
Notifications, deletion, and failure semantics
Billing state commits before lifecycle notification delivery. A notification failure must not make the provider retry an already-committed financial mutation. The current implementation is not backed by an outbox, so an operator resend must not replay billing state.
Deleting local application data does not cancel a remote subscription. Account deletion returns
409 CONFLICT while billing can renew or paid time remains. The customer cancels through Billing
and waits for the period boundary before local account deletion.
Never manually toggle users.is_premium, delete event claims, or grant access from a checkout
redirect. Check State machines and run billing:reconcile to repair drifted
provider state.
Provider verification
Before production, run the same lifecycle in the selected provider's sandbox/test mode:
- create every enabled recurring product/price;
- configure the complete selected provider;
- register the exact webhook route and events;
- run checkout with a fresh verified application user and a deliverable email address accepted by the provider sandbox;
- confirm customer correlation, subscription, event claim, entitlement, and portal;
- replay the same event and deliver an older lifecycle event;
- fail and recover a payment;
- schedule cancellation and verify the exact access boundary;
- reject an invalid signature;
- verify account deletion remains blocked until billing is resolved.
See State machines for every legal subscription transition and guard.
Reconciliation and alerting
Run a bounded dry-run against the selected provider:
vp run --filter @app/server billing:reconcile -- --limit=100Apply remote subscription state only after reviewing that report:
vp run --filter @app/server billing:reconcile -- --apply --limit=100The compiled deployment artifact supports the same operator command:
./server billing:reconcile --apply --limit=100The command exits non-zero for unresolved drift, provider errors, or a locally stored subscription that no longer exists remotely. Configure scheduled-job failure alerts on the selected host around that exit status. Missing remote subscriptions are never silently deleted or revoked; investigate them in the provider dashboard first. This explicit bounded command is the v1 recovery mechanism, not a generic worker or queue.
Known limits
- Only one web billing provider can be active per deployment (optional
MOBILE_IAP_PROVIDER=revenuecatruns alongside it for native App Store and Google Play subscriptions). - Plan currency and amount are not reconciled into the application plan response.
- There is no generic coupon, tax display, usage, seat, or refund UI.
- Reconciliation is bounded and operator-triggered; each deployment must schedule it and route a non-zero exit to its platform alerting channel.
- Adapter unit/integration tests do not replace a real Polar sandbox, Stripe test-mode, or Dodo test-mode checkout-to-webhook proof.