Skip to content
Docs
Changelog

Payments: one entitlement read model, three provider modules

The repository's architectural decision, rationale and consequences.

Markdown

Status: accepted · Date: 2026-10-12

The template already verified RevenueCat purchases on the server (billing_event, billing_refresh, billing_entitlement, pull reconciliation). The web app needed Stripe and Polar checkout, and the mobile app never registered the RevenueCat SDK. Each provider must be optional, everything off by default, and the app must boot and pass its tests with no payment keys.

Decision

One read model. billing_entitlement is the only thing that answers "does this User have Paid Access". It gained a provider column (existing rows are revenuecat) and its key became (user_id, provider, entitlement_id). Each provider replaces only its own rows: RevenueCat reconciliation deletes provider = 'revenuecat'; a web event rebuilds that provider's rows for that User. billing.status projects all rows of enabled providers in the current BILLING_ENVIRONMENT, so a Stripe purchase unlocks the mobile app and a store purchase shows on the web Billing page. RevenueCat rows also expire when their verification is older than BILLING_MAX_VERIFIED_AGE_SECONDS; web rows are push-updated and get a 24-hour grace after the period end so a late renewal webhook does not cut access.

Per User, not per Organization. CONTEXT.md defines an Entitlement as belonging to a User, and Paid Access as not granting Organization membership. ADR-0003 makes Organizations the tenant for shared data, not for billing. Organization billing (seats, one payer per Organization) is a follow-up that would add a reference column, not a second model.

Webhooks are notifications, verified before parsing. /api/billing/stripe and /api/billing/polar are Worker routes. They bound and read the raw body, verify with Web Crypto (crypto.subtle.verify, constant time), then dedupe on billing_event (provider, id) inside the same transaction that applies the change. A replay is a no-op; a failed write rolls back the event row so the provider retries. Stripe signs ${t}.${body} with the whole whsec_… string; Polar follows Standard Webhooks and both key derivations it has used are accepted. Stripe does not order events, so the handler re-reads the subscription from the API (Stripe-Version pinned) and fences on that read time; Polar payloads carry modified_at, which fences directly. Every applied change queues a billing.subscription_changed audit event targeting the User.

No Better Auth payment plugins. @better-auth/stripe 1.7.7 and @polar-sh/better-auth 2.1.0 are compatible with better-auth 1.7.7 and contain no Node-only code. We still do not use them: each adds its own subscription state (a subscription table and user.stripeCustomerId, or Polar's customer sync) that would compete with billing_entitlement; registering them conditionally changes the inferred auth type that createAuth exports; and they bring the stripe and @polar-sh/sdk packages into the Worker for five REST calls. The provider modules are fetch-based (packages/api/src/features/billing/billing.{stripe,polar}.ts) and run through the same bounded, redirect-free request helper as the RevenueCat client.

Configuration. BILLING_PROVIDERS lists the enabled providers (stripe,polar,revenuecat); it replaces BILLING_ENABLED, which only meant RevenueCat. Each listed provider is validated as a whole and errors never echo values. Stripe keys must match the environment (sk_test_/rk_test_ for SANDBOX, *_live_ for PRODUCTION); Polar uses the sandbox API in SANDBOX. The plan catalog (packages/api/src/features/billing/billing.plans.ts) is a leaf module shared with the web client; provider price/product ids come from env (STRIPE_PRICE_IDS, POLAR_PRODUCT_IDS) because they differ per mode. BILLING_CHECKOUT_PROVIDER picks the web checkout when both web providers are on (for example while migrating), otherwise Stripe wins over Polar.

Visibility is a flag, capability is env. billing.web shows the Billing navigation entry and billing.mobile shows the subscription screen. A flag cannot enable a provider the server has not configured, and a configured provider stays invisible until its flag is on. The mobile app registers react-native-purchases through a lazy loader, so the SDK only initializes when billing is used and an older dev client degrades to "store unavailable".

Consequences

  • Checkout and portal URLs are built on the server from BETTER_AUTH_URL (or the request origin); the client never supplies a redirect target. A second checkout for an active entitlement is refused; plan changes go through the provider portal.
  • Web subscriptions are only as fresh as their webhooks plus the grace window. There is no scheduled pull for Stripe/Polar yet; billing.sync only reconciles RevenueCat.
  • scripts/remove-server-billing.mjs removes all three providers, the Billing page and its navigation together.
  • Removing a provider from BILLING_PROVIDERS hides its entitlements immediately but keeps its rows, so turning it back on restores access without data loss.

Amendment 2026-11-27: RevenueCat as documented today

Checked against RevenueCat's webhook, event and REST v1 documentation (read 2026-11-27):

  • Acknowledge with 200. RevenueCat counts any other status, 204 included, as a failed delivery and retries it five times. /api/billing/revenuecat answers 200 when an event is applied or replayed, and also when it is authentic but for the other store environment or an app outside REVENUECAT_APP_IDS (ignored, nothing journaled). Rejections stay 401, 400 and 503.
  • HMAC signing is optional. X-RevenueCat-Webhook-Signature (t=<unix>,v1=<HMAC-SHA256 hex of "<t>.<raw body>">) is an opt-in toggle per webhook. The Authorization header is always required; the signature is required only when REVENUECAT_WEBHOOK_SIGNING_SECRET is set. Both comparisons are constant time.
  • Every event type parses. Identity fields are optional, because TRANSFER, PURCHASE_REDEEMED, EXPERIMENT_ENROLLMENT and TEMPORARY_ENTITLEMENT_GRANT each carry a different subset. Every User an event names is re-read; the event's content is never trusted. A refund is a CANCELLATION. REST API v1 stays: it carries no deprecation notice, and its keys do not work with v2.
  • Verification follows access. A User with access is re-read at half of BILLING_MAX_VERIFIED_AGE_SECONDS, or just after a period ends. A User without access is re-read on an event, a sync or weekly. The cron batch grew from 10 Users, two at a time, to 24 Users, four at a time. Before, every User ever queued was re-read hourly at most 600 times an hour, so past that size verifications aged out and paying Users lost access.
  • The SDK identity lives for the session. The app connects RevenueCat after sign-in, once the flag and the server provider allow it, and logs out only on sign-out. Before, leaving the Subscription screen logged the SDK out: a renewal or an approved Ask to Buy delivered later would have been posted for an anonymous user, and RevenueCat's default restore behavior could then transfer the subscription away from the User.

Amendment 2026-11-27: RevenueCat owner decisions, and both runtimes

The owner's answers to the RevenueCat questions (PR #217), checked against RevenueCat's docs on 2026-11-27:

  • Account deletion deletes the RevenueCat customer. The Better Auth delete hook queues it in billing_customer_erasure inside the deletion's transaction; the cron calls DELETE /v1/subscribers/{app_user_id} (200, or 404 when already gone), retries with a capped backoff and never blocks the deletion; success is audited as billing.customer_erased. Store subscriptions are not cancelled by it.
  • Promotional entitlements grant Paid Access. Store promotional counts in both environments (RevenueCat: grants work in sandbox and production apps, their transactions always count as production) and never renews; their webhook is accepted on a sandbox server too.
  • Restore behavior stays "Transfer to new App User ID", RevenueCat's default: with the SDK identified by the User id for the whole session, a transfer always moves access between two signed-in Users.
  • Workers and Node run the same billing code. scripts/test-billing-runtimes.mjs sends the same signed deliveries, checkouts and ticks to the built Worker and the build:node server with local provider stubs and requires identical results.

Amendment 2026-11-27: Pagar.me as a fourth provider

Status: accepted · Date: 2026-11-27

Brazilian projects need Pix, boleto and card with installments, which Stripe offers only partly (boleto needs a Brazilian Stripe account; Stripe documents Pix Automático as unavailable to Brazilian accounts) and Polar not at all. Pagar.me (Stone) is added as a web provider under the same rules, off until pagarme is listed in BILLING_PROVIDERS.

  • Module. billing.pagarme.ts calls the Pagar.me API v5 (https://api.pagar.me/core/v5, Basic auth with the secret key) over the same bounded, redirect-free request helper; no SDK (the official one is APIMatic-generated over axios). PAGARME_API_URL changes the root and only accepts an https *.pagar.me host, because Pagar.me's Checkout pages name sdx-api.pagar.me for test keys while its API reference lists only api.pagar.me.
  • Read model. Pagar.me writes billing_subscription and billing_entitlement rows with provider = 'pagarme' like Stripe and Polar. Plan ids come from PAGARME_PLAN_IDS. A subscription (card or boleto) grants through the latest cycle whose invoice is paid and not refunded or charged back, also after a cancellation, which Pagar.me applies at once. A One-off Period (Pix, or card or boleto without renewal) is an order stored as a subscription that never renews, active for one plan interval from the payment, or from the end of the current period when the User pays ahead. Its amount is the Pagar.me plan's fixed BRL price, read at checkout. Pagar.me has no recurring Pix, so Pix is always one-off.
  • Webhooks. /api/billing/pagarme verifies X-Webhook-Asymmetric-Signature (alg=RS256; kid; signature, RSASSA-PKCS1-v1_5 SHA-256 over the raw body, public keys from https://hubapi.pagar.me/.well-known/jwks.json, cached per isolate) whenever the header is present. Pagar.me's public v5 docs do not describe the header; its own ecommerce module verifies it, and whether dashboard-created hooks always send it is not confirmed, so an absent header is accepted unless PAGARME_WEBHOOK_SIGNATURE=required. Either way the payload only names what to re-read: access comes from the order, charge or subscription read by id (the Stripe fence), deduped on the hook_… id in billing_event inside the applying transaction. Refunds and chargebacks revoke through that read. The route answers 200 when an event is applied or replayed: Pagar.me does not document which status counts as delivered, and RevenueCat (amendment above) retries every status but 200.
  • Checkout. There is no hosted checkout or portal. billing.pay creates the Pagar.me customer once (Tax Document, phone and address, required by PSP accounts for every method; only the customer id is kept), saves a card token made in the browser with the public key as a customer card and pays with its id (which PSP and Gateway accounts both accept), then creates the order or subscription. That answer is read with the secret key and applied at once through the same fence and projection. billing.payment lets the Pix and boleto screens poll, re-reading Pagar.me at most every 10 seconds; billing.cancel stops renewal.
  • Not built. Split and recipients (commission) and 3-D Secure are design space only: split rules (recipient_id, flat/percentage) travel with the payment at authorization and with the subscription, and recipients go through KYC; both would add configuration and a recipient table without changing the read model.

Consequences: a fourth set of env vars (PAGARME_*), validated as a whole and never echoed; check-production-config.mjs refuses payment settings in wrangler.jsonc vars; remove-server-billing.mjs removes them with the rest. The Stripe and Polar review of the same date is recorded in docs/billing.md.

Edit on GitHubDocumentation is in English.
Cookie settings
We use essential cookies to make our app work. With your consent, we also use optional cookies to improve your experience.

Read our Cookie Policy and Privacy Policy.