# 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.

## 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.
