# Payments

Stripe, Polar, Pagar.me and RevenueCat feed one server-verified entitlement model.

## Enable providers deliberately [#enable-providers-deliberately]

All providers start off. Set `BILLING_PROVIDERS` to the required comma-separated names: `stripe`, `polar`, `pagarme`, `revenuecat`. Each listed provider must have its complete valid configuration. `BILLING_ENVIRONMENT` distinguishes SANDBOX from PRODUCTION; Stripe and Pagar.me key modes must agree. Payment settings are Worker secrets: `scripts/check-production-config.mjs` refuses them in `wrangler.jsonc` `vars`.

Stripe, Polar and Pagar.me sell on the web. RevenueCat connects store purchases on mobile. If several web providers are enabled, `BILLING_CHECKOUT_PROVIDER` chooses new checkouts (default: Stripe, then Polar, then Pagar.me); existing customers keep their provider. Visibility separately uses `billing.web` and `billing.mobile`.

## Pix, card and boleto with Pagar.me [#pix-card-and-boleto-with-pagarme]

Pagar.me is for Brazil: Pix, credit card with installments and boleto, in BRL. There is no hosted page, so `/billing` opens an in-app checkout: billing details once (CPF or CNPJ, phone and address, which Pagar.me requires; the server keeps only the Pagar.me customer id), then the method.

| Method | Renews   | Notes                                                                                                                                                                               |
| ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Pix    | Never    | QR code and copy-and-paste code, valid `PAGARME_PIX_EXPIRES_IN_SECONDS` (default 30 min). Pays one plan period; the User can pay the next one ahead. Pagar.me has no recurring Pix. |
| Card   | Optional | Tokenized in the browser with `PAGARME_PUBLIC_KEY`, so the number never reaches the server. One period can be split into up to `PAGARME_MAX_INSTALLMENTS` (default 12).             |
| Boleto | Optional | Confirmed by the bank within a few business days; access starts then.                                                                                                               |

The checkout answer and a poll (`billing.payment`, re-reading Pagar.me at most every 10 seconds) apply the same way a webhook does. `/api/billing/pagarme` verifies `X-Webhook-Asymmetric-Signature` (RS256 over the raw body, Pagar.me's JWKS) when present and always re-reads the order or subscription by id before granting, so a refund or chargeback revokes access. Set `PAGARME_WEBHOOK_SIGNATURE=required` once a test delivery shows the header. Pagar.me cancels a subscription at once; the template keeps access through the paid cycle. Split and recipients are not implemented.

<Callout title="Monthly Pix">
Pix every month needs Pix Automático, which neither Pagar.me nor (for Brazilian accounts) Stripe
offers today. If monthly fees must be paid by Pix, compare a provider that has it before choosing
Pagar.me.
</Callout>

## Entitlements and webhooks [#entitlements-and-webhooks]

Paid Access belongs to the User, not an Organization. The server's entitlement read model projects enabled-provider rows in the current environment. Device-reported purchases alone grant nothing. RevenueCat reconciliation replaces only its provider rows; Stripe, Polar and Pagar.me apply verified, deduplicated events in transactions, and Stripe and Pagar.me re-read the subscription or order from their API first.

| Provider   | Webhook path              | Server secrets                                                                                                                     |
| ---------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| Stripe     | `/api/billing/stripe`     | STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_IDS                                                                         |
| Polar      | `/api/billing/polar`      | POLAR_ACCESS_TOKEN, POLAR_WEBHOOK_SECRET, POLAR_PRODUCT_IDS                                                                        |
| Pagar.me   | `/api/billing/pagarme`    | PAGARME_SECRET_KEY, PAGARME_PUBLIC_KEY, PAGARME_PLAN_IDS                                                                           |
| RevenueCat | `/api/billing/revenuecat` | REVENUECAT_SECRET_API_KEY, REVENUECAT_WEBHOOK_AUTHORIZATION, REVENUECAT_WEBHOOK_SIGNING_SECRET (optional, when HMAC signing is on) |

Configure RevenueCat app and entitlement IDs too. Public platform SDK keys belong in the mobile environment; server keys do not. The store products, RevenueCat project, webhook and sandbox testing are a step-by-step page of their own: [Mobile subscriptions with RevenueCat](/docs/features/revenuecat). Raw webhook verification precedes payload parsing. A replay is a no-op, and a failed write rolls back its dedupe record so the provider can retry.

## On Workers or on a Node server [#on-workers-or-on-a-node-server]

Billing is the same code on both production targets ([Run on a Node server](/docs/production#run-on-a-node-server-instead)): the same routes, the same variable names, Web Crypto for the signatures, `fetch` with `redirect: "manual"` for every provider call.

|                                                     | Cloudflare Workers                        | Node server (`build:node`)                                                                                  |
| --------------------------------------------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Webhook URLs                                        | `https://<origin>/api/billing/<provider>` | The same paths on the server's public origin (through the Tunnel or proxy)                                  |
| Billing variables                                   | Worker secrets (`wrangler secret bulk`)   | The service's environment file (`EnvironmentFile=`), same names                                             |
| RevenueCat re-reads and deleted accounts' customers | The Worker's one-minute Cron Trigger      | `pnpm jobs:run --once --production` every minute ([systemd timer](/docs/production#scheduled-jobs-on-node)) |
| Pagar.me webhook keys (JWKS)                        | Cached per isolate                        | Cached per process                                                                                          |

Signatures cover the exact request bytes: on a VPS, do not put a proxy that rewrites, re-encodes or decompresses request bodies in front of `/api/billing/*`.

`pnpm test:billing:runtimes` proves the two targets agree. It builds both, starts each against a disposable PostgreSQL with local stubs for every provider API (no real provider, no real key), and sends each the same signed Stripe, Polar, Pagar.me and RevenueCat deliveries (applied, replayed, forged, redirected re-read), the same checkout, portal and Pix calls, an account deletion and a scheduled tick. It fails if the Worker and the Node server answer, call a provider or write billing rows differently. The e2e workflow runs it on every pull request.

## Go-live checklist per provider [#go-live-checklist-per-provider]

What a project sets for each provider it lists in `BILLING_PROVIDERS`. Secrets go in Worker secrets or the Node service's environment file, never in `wrangler.jsonc` or the repository. `<origin>` is the public origin: the Worker's custom domain, or the Node server's domain.

| Provider   | Keys (server)                                                                                                     | Webhook                                                                                                                                               | Plan ids                                                                                         | Test mode first                                                                                                     |
| ---------- | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| Stripe     | `STRIPE_SECRET_KEY` (`sk_live_…`, or a restricted `rk_live_…`)                                                    | Live endpoint `https://<origin>/api/billing/stripe`, API version `2026-09-30.endive`, the events in the `payments` skill → `STRIPE_WEBHOOK_SECRET`    | `STRIPE_PRICE_IDS` with live `price_…` ids; Customer Portal set up in live mode                  | `sk_test_…` with `BILLING_ENVIRONMENT=SANDBOX`; `stripe listen` locally                                             |
| Polar      | `POLAR_ACCESS_TOKEN` of the production organization                                                               | `https://<origin>/api/billing/polar`, raw JSON, API version `2026-10` → `POLAR_WEBHOOK_SECRET`                                                        | `POLAR_PRODUCT_IDS`                                                                              | A sandbox.polar.sh organization with `SANDBOX` (the server then calls `sandbox-api.polar.sh`)                       |
| Pagar.me   | `PAGARME_SECRET_KEY` and `PAGARME_PUBLIC_KEY` without `_test_`; the app's domain registered for card tokenization | `https://<origin>/api/billing/pagarme`; once a delivery shows `X-Webhook-Asymmetric-Signature`, `PAGARME_WEBHOOK_SIGNATURE=required`                  | `PAGARME_PLAN_IDS`, BRL prices equal to the catalog                                              | `sk_test_…`/`pk_test_…` with `SANDBOX`; Pix up to R$ 500 pays itself                                                |
| RevenueCat | `REVENUECAT_SECRET_API_KEY` (v1 secret); `REVENUECAT_APP_IDS`; app keys `EXPO_PUBLIC_REVENUECAT_*_API_KEY`        | `https://<origin>/api/billing/revenuecat`, production environment → `REVENUECAT_WEBHOOK_AUTHORIZATION`, HMAC on → `REVENUECAT_WEBHOOK_SIGNING_SECRET` | `REVENUECAT_ENTITLEMENT_IDS` (same ids as the web catalog); store products in a current offering | Sandbox testers or StoreKit with a `SANDBOX` server and a sandbox webhook ([RevenueCat](/docs/features/revenuecat)) |

For every provider:

- `BILLING_ENVIRONMENT=PRODUCTION` only on the production server; previews and staging stay `SANDBOX` with test keys.
- `BETTER_AUTH_URL` is the public origin; checkout return URLs are built from it.
- Migrations are applied (`db:apply-pending`) and, on a Node server, the jobs timer runs.
- `billing.web` and `billing.mobile` go on in `/admin/flags` after one real test purchase and one cancellation.

## Extend and test [#extend-and-test]

Add plans to the leaf `billing.plans.ts`, map provider product IDs in env, and add name/description translations. Checkout return URLs come from the server, never a client-supplied redirect. Test purchases in sandbox and verify `billing.status`, cancellation and webhook replay before enabling production visibility.

Stripe, Polar and Pagar.me rely on webhooks plus the grace window (and, for a pending Pagar.me payment, the checkout's poll); no scheduled pull reconciles their subscriptions. Stripe Checkout offers the methods enabled in the Dashboard for the price's currency; `STRIPE_PAYMENT_METHOD_CONFIGURATION` pins a set, such as card and boleto for BRL prices on a Brazilian account. RevenueCat verification has a freshness bound; the cron re-reads each subscriber at half of it, and deletes a deleted account's RevenueCat customer ([RevenueCat](/docs/features/revenuecat#when-an-account-is-deleted)). Native purchases require a development build with the SDK, not just a successful TypeScript check. See [ADR-0004](/docs/adr/0004-payments-providers).

## Key files [#key-files]

- [`packages/api/src/features/billing/billing.settings.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.settings.ts)
- [`packages/api/src/features/billing/billing.pagarme.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.pagarme.ts)
- [`packages/api/src/features/billing/billing.web-http.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.web-http.ts)
- [`packages/api/src/features/billing/billing.webhook.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.webhook.ts)
- [`packages/api/src/features/billing/billing.status.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.status.ts)
- [`packages/api/src/features/billing/billing.plans.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.plans.ts)
- [`apps/mobile/src/features/billing/billing.purchases-sdk.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/mobile/src/features/billing/billing.purchases-sdk.ts)
- [`docs/billing.md`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/docs/billing.md)
