# Mobile subscriptions with RevenueCat

Step-by-step setup of App Store and Google Play subscriptions through RevenueCat: store products, entitlements, offerings, webhook, env vars and sandbox testing.

The template already carries the code: the server verifies purchases with RevenueCat (`/api/billing/revenuecat`, `billing.sync`, the cron reconciliation) and the app has the Subscription screen behind the `billing.mobile` flag. A project adds store products, a RevenueCat project, keys and a webhook. How the pieces fit is in [Payments](/docs/features/payments) and [ADR-0004](/docs/adr/0004-payments-providers).

<Callout title="The device never grants access">
The app shows store prices and runs the purchase, then asks the server (`billing.sync`). The
server reads the customer from RevenueCat's REST API and writes `billing_entitlement`. Only that
row, in the server's `BILLING_ENVIRONMENT` and verified recently, is Paid Access.
</Callout>

## How identity works [#how-identity-works]

The RevenueCat App User ID is our User id. After sign-in the app configures the SDK (or calls `logIn`) with `user.id` and keeps it identified for the whole session; sign-out calls `logOut`. Nobody buys while signed out, so purchases never start on an anonymous RevenueCat user.

A store account (Apple Account, Google account) can still be used by two Users of the app. What happens then is RevenueCat's **Restore behavior** (Project settings → General):

- **Transfer to new App User ID** (RevenueCat's default): Restore on the second User moves the subscription. RevenueCat sends `TRANSFER`, the server re-reads both Users, and the first one loses access.
- **Keep with original App User ID**: the purchase stays with the first User. Restore on the second one fails, and the app says the purchase belongs to another account.

Choose before launch. RevenueCat's own table recommends the default for apps that require an account; pick "Keep" only if a purchase must never move between accounts.

## Set up [#set-up]

<Steps>
<Step title="Pick the entitlement ids">
An entitlement is what a purchase unlocks. The template's default is `pro`. Use the same id in RevenueCat and in the web plan catalog (`packages/api/src/features/billing/billing.plans.ts`), so a Stripe or Polar purchase and a store purchase unlock the same Paid Access.
</Step>

<Step title="Create the store products">
Bundle id and package name are in `apps/mobile/app.config.ts` (`BUNDLE_IDENTIFIER`, `PACKAGE_NAME`). The development build adds `.dev` to both.

**App Store Connect:**

1. Sign the Paid Apps agreement (Business).
2. Create the app with the bundle id.
3. Add a subscription group with one auto-renewable subscription per plan (for example `pro_monthly` and `pro_yearly`), each with a price and a localization.
4. Create an In-App Purchase key (Users and Access → Integrations → In-App Purchase). RevenueCat needs it.

**Google Play Console:**

1. Create the app with the package name.
2. Upload a build to the internal or closed testing track. Play only lists products for an app that has a build with the billing permission, which `react-native-purchases` adds.
3. Create one subscription per plan, each with a base plan and a price.
4. Create a Google Cloud service account with access to the Play Console's financial data, and download its JSON key for RevenueCat.

Keep the product ids at hand: RevenueCat asks for them when you attach products.
</Step>

<Step title="Create the RevenueCat project">
In the RevenueCat dashboard:

1. Create a project.
2. Add an App Store app (bundle id and In-App Purchase key) and a Play Store app (package name and service account JSON).
3. Optionally set up App Store Server Notifications and Google real-time developer notifications with the URLs RevenueCat shows. Events then arrive within minutes, not hours.
4. Note each app's id (Project settings → Apps, `app…`); these go in `REVENUECAT_APP_IDS`.
5. Copy each app's public SDK key: `appl_…` for iOS, `goog_…` for Android.
6. Create the entitlement (`pro`) and attach every product to it.
7. Create an offering (for example `default`), mark it **Current**, and add one package per product (`$rc_monthly`, `$rc_annual`, …). The app shows the current offering, with the store's localized prices.
8. Create a **secret API key** (Project settings → API keys, `sk_…`) for the server. The server calls REST API v1 (`GET /v1/subscribers/{app_user_id}`), so use a v1 key; RevenueCat says v1 keys do not work with API v2.

The public keys go in the app; the secret key and the app ids go on the server.
</Step>

<Step title="Register the webhook">
Project → Integrations → Webhooks → add one per server:

- **URL:** `https://<origin>/api/billing/revenuecat`.
- **Authorization header value:** 32 to 512 random characters. RevenueCat sends it verbatim as `Authorization`; it goes in `REVENUECAT_WEBHOOK_AUTHORIZATION`.
- **HMAC webhook signing:** turn it on and copy the secret into `REVENUECAT_WEBHOOK_SIGNING_SECRET`. RevenueCat shows the secret once; rotating it invalidates the old one right away. When the variable is set, the server refuses unsigned deliveries. Without it, only the Authorization header authenticates them.
- **Environment:** production purchases for the production server, sandbox for preview or staging servers.

Send a test event. The endpoint answers `200`. RevenueCat counts any other status as a failure and retries five times over about 80 minutes. The server also answers `200`, and does nothing, for an event from another store environment or from an app that is not in `REVENUECAT_APP_IDS`.
</Step>

<Step title="Configure the server">
Locally in `apps/web/.dev.vars`; in production as Worker secrets (see [Payments](/docs/features/payments) and the `payments` skill for `wrangler secret bulk`):

```bash
BILLING_PROVIDERS="revenuecat"              # add stripe/polar for the web
BILLING_ENVIRONMENT="SANDBOX"               # PRODUCTION only when going live
REVENUECAT_SECRET_API_KEY="sk_…"            # v1 secret key, never in the app
REVENUECAT_WEBHOOK_AUTHORIZATION="…"        # the header value from the webhook
REVENUECAT_WEBHOOK_SIGNING_SECRET="…"       # optional, when HMAC signing is on
REVENUECAT_APP_IDS="app…,app…"              # iOS and Android apps (and .dev apps)
REVENUECAT_ENTITLEMENT_IDS="pro"
# BILLING_MAX_VERIFIED_AGE_SECONDS="7200"   # 300 to 86400
```

A store purchase counts only in its own environment: in `SANDBOX` the server accepts sandbox transactions from the App Store and Google Play, in `PRODUCTION` only real ones. RevenueCat Test Store, promotional grants and web stores never grant Paid Access through this provider.
</Step>

<Step title="Configure the app">
In `apps/mobile/.env`:

```bash
EXPO_PUBLIC_REVENUECAT_IOS_API_KEY="appl_…"
EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY="goog_…"
# Optional: RevenueCat's own screens instead of the template's rows
# EXPO_PUBLIC_REVENUECAT_PAYWALL="true"          # the Paywall of the current offering
# EXPO_PUBLIC_REVENUECAT_CUSTOMER_CENTER="true"  # Customer Center (RevenueCat Pro plan)
```

Without the Paywall flag the screen lists the current offering's packages with our own rows. Design a Paywall for the offering in the dashboard before turning it on: RevenueCat shows a default one otherwise. Without the Customer Center flag, "Manage subscription" opens the store's subscription settings.

The SDKs are native modules, so the app needs a development build that includes them (`pnpm --filter mobile exec expo run:ios`, or an EAS build). An older build without them shows "This version of the app can't open the store" and grants nothing.
</Step>

<Step title="Turn on the screen">
In `/admin/flags`, turn on `billing.mobile`. Profile → Subscription appears. The store connects only while the flag is on and the server lists `revenuecat`.
</Step>
</Steps>

## Test in the sandbox [#test-in-the-sandbox]

A real purchase needs a device or simulator, store test accounts and the products above. CI cannot do it.

**iOS on a device:** create a sandbox tester in App Store Connect (Users and Access → Sandbox), then sign in on the device under Settings → Developer → Sandbox Apple Account (iOS 18 and later). The products must belong to the bundle id of the build you run. The development build uses `….dev`, so either add that app to App Store Connect and RevenueCat (and its id to `REVENUECAT_APP_IDS`), or test with a production build.

**iOS on the simulator:** use a StoreKit configuration file.

1. `pnpm --filter mobile exec expo prebuild --platform ios`, then open the workspace in Xcode.
2. Add a StoreKit Configuration File with the same product ids.
3. Select it in the scheme (Run → Options).
4. Upload its public certificate to the RevenueCat app (StoreKit testing framework).
5. Run the app from Xcode. RevenueCat notes that StoreKit testing only works when Xcode launches the app, and that cancellations and refunds made in Xcode produce no events.

**Android:** add the Google account as a license tester (Play Console → Settings → License testing) and as a tester on the closed track, open the opt-in link, and install the build from that track.

Then:

1. Buy a package. The screen shows "Subscription active" once the server has verified it. With a webhook pointing at your server, its log shows the `INITIAL_PURCHASE` delivery answered with `200`.
2. Restore on a second device signed in to the same account.
3. Cancel in the store. Access continues until the period ends ("Access ends on …").
4. Wait for the sandbox renewal or expiry (minutes in sandbox).

## How the server stays current [#how-the-server-stays-current]

- **Webhook:** every authenticated event, of any type, queues a re-read of every known User it names: `app_user_id`, `original_app_user_id`, `aliases`, both sides of a `TRANSFER`, and the users a `PURCHASE_REDEEMED` names. The event is not trusted for its content; the re-read decides. A refund arrives as `CANCELLATION` with `cancel_reason` `CUSTOMER_SUPPORT`. The re-read sees `refunded_at` and removes access.
- **Purchase in the app:** `billing.sync` re-reads at once. The SDK's customer info listener also asks for a sync when the device and the server disagree, for example after a renewal or an approved Ask to Buy.
- **Cron:** a User with access is re-read at half of `BILLING_MAX_VERIFIED_AGE_SECONDS` (one hour by default) and just after a period ends, in case its renewal webhook was lost. A User without access is re-read only on an event, a sync, or weekly. Access ends when the last verification is older than `BILLING_MAX_VERIFIED_AGE_SECONDS`.
- **Capacity:** each one-minute tick re-reads up to 24 Users, four at a time, about 1,400 an hour. With the default age limit that covers roughly 1,400 active subscribers. For more, raise `BILLING_MAX_VERIFIED_AGE_SECONDS`, for example to 86400, which re-reads each subscriber every 12 hours. RevenueCat documents 480 requests per minute per key for customer reads.

## Key files [#key-files]

- [`packages/api/src/features/billing/billing.webhook.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.webhook.ts): webhook authentication and the event subjects.
- [`packages/api/src/features/billing/billing.reconcile.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.reconcile.ts): the re-read and its schedule.
- [`packages/api/src/features/billing/billing.revenuecat-payload.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.revenuecat-payload.ts): which transactions grant access.
- [`packages/api/src/features/billing/billing.fixture-revenuecat.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/billing/billing.fixture-revenuecat.ts): RevenueCat's documented sample events, used by the tests.
- [`apps/mobile/src/features/billing/billing.hooks.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/mobile/src/features/billing/billing.hooks.ts): the session connection and the screen's actions.
- [`packages/purchases/src/index.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/purchases/src/index.ts): the SDK wrapper.
