# Payments: one entitlement read model, three provider modules

The repository's architectural decision, rationale and consequences.

# Payments: one entitlement read model, three provider modules

**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 [#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 [#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.
- Each web subscription row keeps the entitlement it resolved to while its product was in the catalog (`billing_subscription.entitlement_id`), so rotating a price or product id does not drop a paying subscriber on the next webhook. A projection rebuild holds a transaction advisory lock per User and provider, so two webhooks cannot write a stale projection over a newer one (2026-12-01).

## Amendment 2026-11-27: RevenueCat as documented today [#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 [#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 [#amendment-2026-11-27-pagarme-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. A Pagar.me User can hold periods that do not touch (one paid ahead after one that was refunded), so each Pagar.me subscription row also keeps its paid intervals (`paid_periods`: start, end, and the end of access) and the entitlement keeps them merged (`periods`); `billing.status` grants only inside one of them, so a period paid ahead never covers a refunded one. Periods merge only where they touch, or across the `23:59:59 → 00:00:00` cycle edge. A cycle without `cycle.start_at` begins where the listed cycle before it ended, else it counts as started: nothing is inferred from the calendar. Only the last paid cycle of a renewing subscription gets the 24-hour grace, and not when a reversed cycle follows it; a One-off Period gets none. Rows written before these columns existed keep granting as they did (started, until the period end plus the grace). Stripe and Polar keep one period per row. Plan ids come from `PAGARME_PLAN_IDS`. A One-off Period (Pix, or card or boleto without renewal) is an order stored as a subscription that never renews, starting after every period the User already paid for. 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` requires a verified `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) by default. `PAGARME_WEBHOOK_SIGNATURE=optional` is an unsafe opt-out for accounts whose hooks omit the header: no-op events are dropped, a per-IP edge limit and then the per-IP and aggregate database limits are spent before any Pagar.me call, `GET /hooks/{id}` must return the same event, and the delivery is applied to a resolved User without writing `billing_event`, so an unsigned replay never takes a genuine delivery's dedup slot. Any shared limit can be spent by anonymous traffic, which is why signed delivery is the default. Either way the payload only names what to re-read: access comes from the order, charge or subscription read by id (the Stripe fence), with signed deliveries 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). Each payment is a `billing_checkout_attempt` (system only, ADR-0009 default deny). A unique partial index allows one open attempt per User, provider and environment, and it is taken before eligibility and the start date are decided. The exact request body and a server-generated key (sent as the idempotency key and as `metadata.attemptKey`) are stored before the body is sent once; every state change is a compare-and-set on `status`. A lost answer leaves the attempt `uncertain`: it is never sent again, and only the provider object carrying its key (read by stored id, found in the customer's orders or subscriptions, or delivered by a webhook) or an operator resolves it. A 404, an empty list and elapsed time prove nothing, so until then the User cannot start another payment. The object must name the attempt's customer, User and key before it is applied. Each client key that reached an attempt is recorded in `billing_checkout_key` for that User, provider and environment. The key lookup and assignment use the same transaction lock before eligibility, so a retry under the original or a replacement key is answered from that attempt after it leaves the checkout slot. That answer is 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`.
