Skip to content

Google Play Billing for new Android subscriptions, behind ANDROID_BILLING (default off) - #26078

Merged
kodjima33 merged 27 commits into
mainfrom
feat/android-play-billing
Nov 23, 2026
Merged

kodjima33 merged 27 commits into
mainfrom
feat/android-play-billing

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

New Android subscription purchases go through Google Play Billing in every country, behind a server switch that is off by default. Google has rejected the Android app since Oct 24 (last on version code 1605) because it sells Omi Pro through a Stripe Checkout webview with a US$ price shown to non-US users. The app is enrolled in no alternative-billing program, so Play Billing is required. Stripe stays for iOS, web, desktop and existing Stripe subscribers.

Design (posted first for early review)

Switch and version gate

  • ANDROID_BILLING=stripe|play (unset or any other value = stripe).
  • ANDROID_PLAY_BILLING_MIN_BUILD=<Play version code>. Unset means no build qualifies. Only X-App-Platform: android with X-App-Build >= min is told to use Play. Older Android builds keep today's Stripe flow until they update.
  • The answer rides GET /v1/users/me/subscription as an optional play_billing block: {product_id, base_plans:[{id, interval}], trial_offer_id, obfuscated_account_id}. The block is omitted when the switch is off, for older builds, on iOS, web and desktop, so those responses are byte-identical (tested).
  • Per-user or cohort switch, so a license tester can buy through Play in prod while everyone else stays on Stripe: ANDROID_PLAY_BILLING_COHORT=uid:<uid>[,uid:<uid>][,pct:<n>] (or all), or a member doc in the android-play-billing rollout cohort (config/rollout_cohorts.py, Firestore rollout_cohorts). The build gate still applies to cohort members. No uid is in source.
  • Fixed names (env overrides, defaults shown): PLAY_PACKAGE_NAME=com.friend.ios, PLAY_SUBSCRIPTION_PRODUCT_ID=omi_pro, PLAY_MONTHLY_BASE_PLAN_ID=monthly, PLAY_YEARLY_BASE_PLAN_ID=yearly, PLAY_TRIAL_OFFER_ID=trial-7d. The legacy products com.omi.app.lite, com.omi.app.plus and com.omi.app.unlimited_v2 are never offered. A restore or notification that returns one is refused as 400 legacy_product and logged as a warning (play_billing legacy product refused). It is never granted.
  • Credentials: Application Default Credentials with the androidpublisher scope. There is no JSON key in env or in the repo. Prod backend (Cloud Run, based-hardware, us-central1) runs as [email protected] (gcloud run services describe backend on 2026-11-22; backend/deploy/runtime_env/prod.overlay.yaml:1015). No GOOGLE_APPLICATION_CREDENTIALS is set there, so ADC resolves to that account.
  • RTDN/reconcile auth env: PLAY_RTDN_OIDC_AUDIENCE, PLAY_RTDN_PUSH_SA, PLAY_RECONCILE_OIDC_AUDIENCE, PLAY_RECONCILE_INVOKER_SA. When unset, the routes return 403.

Data model

  • play_subscription_purchases/{sha256(purchase_token)}: uid (written once by an exclusive create), purchase_token, product_id, base_plan_id, offer_id, state, expiry_time, auto_renewing, acknowledged, obfuscated_account_id, linked_token_key, test_purchase, revoked, next_check_at, updated_at.
  • users/{uid}.play_current_purchase = token key that owns the user's current Play entitlement. A late event for an older token never downgrades a newer one or a Stripe row.
  • The entitlement is the same users/{uid}.subscription row Stripe writes: plan=unlimited_v2, status=active, current_period_end=expiryTime, cancel_at_period_end=!autoRenewEnabled, no stripe_subscription_id, plus a new provider: "play" field. provider is omitted for Stripe and legacy rows, so their wire and stored shape is unchanged.
  • Entitlement writes reuse the Stripe upgrade path: users_db.update_user_subscription + set_credits_invalidation_signal + unlock conversations/memories/action items + clear_fair_use_on_upgrade (same sequence as routers/monthly_switch._store). Limits come from get_plan_limits(unlimited_v2). Without a Stripe price id, resolve_subscription_entitlements resolves the plan's default entitlement version (the same path as pre-current_price_id Stripe rows).

Endpoints

  • POST /v1/payments/play/purchases (Firebase auth) {purchase_token, product_id} → 200 {status: active|pending|inactive, subscription?}. Errors are {detail: <code>, message}: 400 invalid_purchase|unknown_product|legacy_product, 409 purchase_owned_elsewhere|stripe_subscription_active|account_deletion_pending|purchase_refunded, 429 (rate limit), 503 play_unavailable|billing_check_unavailable (the client retries).
    Steps: purchases.subscriptionsv2.get → package/product/base plan check → obfuscatedExternalAccountId must match this uid when present → deletion fence → token (and linkedPurchaseToken) not bound to another uid → refuse when a live Stripe subscription exists → purchases.subscriptions.acknowledge → exclusive bind → grant.
  • POST /v2/internal/play-billing/rtdn (not in the schema): Pub/Sub push, Google-signed OIDC verified with the existing verify_configured_cloud_tasks_oidc (audience plus push service-account email). The notification only names the token; state is always re-read from subscriptionsv2. Non-2xx makes Pub/Sub retry.
  • POST /v2/internal/play-billing/reconcile (not in the schema): Cloud Scheduler OIDC. Re-reads open purchases whose next_check_at (min(expiry + 60s, now + 24h)) has passed. Covers missed notifications and expiries.

States (Google's subscriptionState decides; the notification type only matters for revoke):

Google state / event Access
ACTIVE (purchase, renewal, recovered, restarted) Omi Pro to expiryTime
IN_GRACE_PERIOD keeps access through grace (Google extends expiryTime; never less than 24 h ahead)
CANCELED (auto-renew off) keeps access to expiryTime, cancel_at_period_end=true
ON_HOLD, PAUSED, EXPIRED, PENDING_PURCHASE_CANCELED Free
PENDING (slow payment) bound, not acknowledged, no access until Google reports ACTIVE
SUBSCRIPTION_REVOKED (12), voidedPurchaseNotification (refund/chargeback) Free now, next_check_at cleared
Resubscribe (new token with linkedPurchaseToken) must belong to the same uid; pointer moves to the new token

Never both Stripe and Play

  • Binding refuses with 409 stripe_subscription_active when the stored row is a live paid non-Play plan, or when Stripe lists an active|trialing|past_due subscription for the customer. The purchase stays unacknowledged, so Google refunds it automatically after 3 days.
  • can_user_make_payment refuses Stripe Checkout while a live Play row exists. Every Stripe checkout path calls it.
  • The app shows the Play purchase UI only to a user with no active paid plan. A Stripe subscriber on Android keeps today's Stripe management UI. A Play subscriber sees only "Manage subscription", which opens Play's subscription center.
  • iOS, web and desktop read subscription.plan=unlimited_v2 + provider=play as an active plan and do not offer a second purchase.

What a Play-billed Android user no longer sees (hidden for them only, unchanged for everyone else): the Stripe Checkout webview, the promo/prepaid code field and the "Have an Omi Pro code?" hint, the 30-day downsell, the cancel-flow stay offer, the yearly switch, the Stripe customer portal and any server or USD price string. The file:line list is under "Stripe-only surfaces" below.

RTDN, credentials and names (for the Play-side setup)

Item Value
Package com.friend.ios
Product / base plans / offer omi_pro; monthly (P1M, US$29.99), yearly (P1Y, US$269.91); offer trial-7d on each base plan (7-day free trial, new subscribers)
Never offered or granted com.omi.app.lite, com.omi.app.plus, com.omi.app.unlimited_v2 (refused as legacy_product, logged)
Publisher API identity (ADC, no key) [email protected] (prod backend Cloud Run service)
RTDN push endpoint POST https://api.omi.me/v2/internal/play-billing/rtdn
RTDN JWT audience (PLAY_RTDN_OIDC_AUDIENCE) https://api.omi.me/v2/internal/play-billing/rtdn
RTDN push identity (PLAY_RTDN_PUSH_SA) [email protected] (exists). The token must carry email = this value and email_verified=true; verified with Google's certs by verify_configured_cloud_tasks_oidc
Reconcile endpoint POST https://api.omi.me/v2/internal/play-billing/reconcile (Cloud Scheduler OIDC; audience PLAY_RECONCILE_OIDC_AUDIENCE, caller PLAY_RECONCILE_INVOKER_SA)

Notification type → result (Google's subscriptionsv2 state is re-read every time; tested in test_every_notification_type_maps_to_access_without_the_app):

RTDN notificationType Google state read Omi access
1 RECOVERED, 2 RENEWED, 4 PURCHASED, 7 RESTARTED, 8 PRICE_CHANGE_CONFIRMED, 9 DEFERRED, 11 PAUSE_SCHEDULE_CHANGED ACTIVE Omi Pro, period end = new expiryTime (a renewal extends it with no app involved)
3 CANCELED CANCELED keeps Omi Pro to expiryTime, cancel_at_period_end=true
6 IN_GRACE_PERIOD (even if expiryTime has not been extended yet) IN_GRACE_PERIOD Omi Pro to max(expiryTime, now + 24 h), re-read every 6 h
5 ON_HOLD, 10 PAUSED, 13 EXPIRED, 20 PENDING_PURCHASE_CANCELED ON_HOLD / PAUSED / EXPIRED / PENDING_PURCHASE_CANCELED Free
12 REVOKED any Free immediately, even if Google still reads ACTIVE
voidedPurchaseNotification (refund, chargeback) any Free immediately, no further reconcile
testNotification, other package none acknowledged, ignored

Outside-the-repo setup

Already done by the parent (2026-11-22/23): omi_pro with base plans monthly and yearly and offer trial-7d on each (DRAFT, Google's converted prices for 174 regions, US 29.99 / 269.91, eligibility "never had any subscription in this app"); topic projects/based-hardware/topics/play-billing-rtdn with Google Play as publisher; [email protected] has Play Console financial-data and orders access; service accounts play-billing-rtdn-push@ and [email protected] exist. This PR changed nothing outside the repo.

Still to do, after merge and deploy:

  1. Activate the omi_pro base plans and the trial-7d offers (they are DRAFT).
  2. Push subscription play-billing-rtdn-push on play-billing-rtdn: endpoint https://api.omi.me/v2/internal/play-billing/rtdn, authentication on, service account [email protected], audience https://api.omi.me/v2/internal/play-billing/rtdn; the Pub/Sub service agent needs roles/iam.serviceAccountTokenCreator on that account.
  3. Play Console → Monetization setup → Real-time developer notifications: topic projects/based-hardware/topics/play-billing-rtdn (replaces superwall-playstore), content "Subscriptions, voided purchases and all one-time products"; "Send test notification" must log play_billing rtdn outcome=test.
  4. Cloud Scheduler, hourly: POST https://api.omi.me/v2/internal/play-billing/reconcile, OIDC [email protected], audience https://api.omi.me/v2/internal/play-billing/reconcile.
  5. Prod backend env: PLAY_RTDN_OIDC_AUDIENCE, PLAY_RTDN_PUSH_SA, PLAY_RECONCILE_OIDC_AUDIENCE, PLAY_RECONCILE_INVOKER_SA (values above); ANDROID_PLAY_BILLING_MIN_BUILD=<first version code with this PR>; ANDROID_PLAY_BILLING_COHORT=uid:<tester uid> (or the android-play-billing rollout cohort). Keep ANDROID_BILLING unset.
  6. Confirm the Android Publisher API is enabled in based-hardware, and that backend-runtime@ also has "Manage orders and subscriptions" (needed to acknowledge and, on account deletion, cancel).
  7. License testing: tester Google account in Settings → License testing and in the internal track's testers; open the opt-in link on the phone.

Manual internal-track test script

Expected result after each step. Steps 0-16 need the tester account; 17-27 come from review round 1.

  1. Before opening the app: base plans and offers Active, build on the internal track, RTDN push subscription and Scheduler job live, backend env set (setup 1-7). Expected: GET /v1/users/me/subscription as the tester with X-App-Platform: android and X-App-Build: N has play_billing; as anyone else, or with build N-1, or from iOS, it has no play_billing key.
  2. Install build N from the internal track (signed in to Play as the license tester), sign in to Omi as the tester. Expected: no Play connection is made before the subscription read (Play loads only after play_billing arrives).
  3. Settings → Plan. Expected: a loading skeleton first, then "Yearly" / "Monthly" with Play's local prices, "7 days free, then …", "Renews automatically at the price shown until you cancel. Manage or cancel anytime in Google Play.", "Billed by Google Play", Terms · Privacy. No code field, no yearly switch, no US$ unless the account is US.
  4. Tap Terms, then Privacy. Expected: each opens in the browser.
  5. Pick Yearly, tap Subscribe. Expected: Play's sheet with "Test card, always approves", the 7-day trial and the local yearly price.
  6. Confirm. Expected: "7-day free trial started", the sheet closes, Settings shows Omi Pro. Backend log: POST /v1/payments/play/purchases 200. Firestore users/<uid>.subscription: plan unlimited_v2, provider play, current_period_end ≈ now + 7 days; users/<uid>.play_billing_customer = true; play_subscription_purchases/<sha256(token)>: uid, base_plan_id yearly, acknowledged true.
  7. Same user on iOS, web and desktop. Expected: Omi Pro active, no purchase offered. iOS and web show "Billed by Google Play" with "Manage in Google Play" (web: link to Play's subscriptions page); macOS/Windows "Manage billing" opens Play's subscriptions page in the browser; Cancel on web/released clients gets the 409 "billed through Google Play" message, not a Stripe error.
  8. Android Settings → Plan again. Expected: "Omi Pro", renew date, "Billed by Google Play", "Manage subscription" → Play's subscription center on Omi Pro.
  9. Wait for an accelerated renewal. Expected: RTDN 2 (play_billing rtdn outcome=active) and a later current_period_end, app closed.
  10. Cancel in Play. Expected: RTDN 3, Pro kept, cancel_at_period_end true, the sheet says "Your Omi Pro plan ends …".
  11. Resubscribe from Play. Expected: RTDN 7, cancel_at_period_end false.
  12. Switch the test card to "declined" before a renewal. Expected: RTDN 6 (grace), Pro kept for the whole grace period (current_period_end follows Google's extended expiryTime, never earlier than a day ahead); when grace ends without payment, RTDN 5 (on hold) and Free.
  13. Play Console → Order management → Refund (and Revoke). Expected: voided notification or RTDN 12, plan basic within a minute, revoked true on the purchase doc; a later Restore of that token returns "This Google Play purchase was refunded…" and never re-grants.
  14. Buy with "Test card, approves after a delay". Expected: the plans sheet shows "Your payment is pending…" and disables Subscribe; the server already has the token (users/<uid>.play_pending_purchase set, plan Free); Stripe Checkout from web is refused ("Your Google Play purchase is still being processed"); when Play approves, RTDN 4 grants Pro and acknowledges with the app closed.
  15. Airplane mode right after confirming a purchase, kill the app, network back, reopen. Expected: the stored token is re-sent on launch; Pro appears; one charge.
  16. Sign out, sign in as a different Omi account on the same phone, tap Restore. Expected: "This Google Play purchase belongs to another Omi account." and no grant.
  17. A second tester with a live Stripe subscription. Expected: Android shows the Stripe management sheet, not Play buttons; a forced Play purchase gets 409 stripe_subscription_active and is never acknowledged (Google refunds it within 3 days).
  18. Fresh account, fresh install, record the first frame on video for every paywall-variant arm forced one by one (control, outline, web, trial). Expected: never a Stripe or US$ price; the web arm opens the outline paywall instead of the hosted page.
  19. Walk every opener: first-tap, free-cap, chat quota, on-phone banner, Usage → Upgrade, Settings → Plan, held-recording Upgrade, settings search. Screenshot each. Expected: Play prices plus the renewal line and Terms/Privacy on every purchase screen.
  20. A Google account Play will not give the trial to (one that already had it). Expected: the trial paywall turns into the plans view with the base plan and no "free" wording; buying buys the base plan.
  21. Play unavailable: airplane mode before opening Plans, and an account in an unsupported country. Expected: "Unable to load plans" with Retry, no Stripe fallback.
  22. Open a paid Marketplace app on the Play-billed build. Expected: "Not available on Android" (disabled), no payment link.
  23. Usage page. Expected: the chat allowance shows a percentage, no US$.
  24. Stripe checkout completed on web while Play is live (open a web checkout before buying on Play, finish it after). Expected: the new Stripe subscription is cancelled at once and its first charge refunded; the user gets a push "You already have Omi Pro … we canceled the new card subscription and refunded it"; the log line play_billing double billing refused names both ids; the Play row is unchanged.
  25. Delete the Omi account while the Play subscription is live. Expected: deletion calls subscriptionsv2:cancel (DEVELOPER_REQUESTED_STOP_PAYMENTS); Play shows the subscription as cancelled with no further charge; if Google refuses, the deletion task reports a billing failure and retries instead of finishing.
  26. Reinstall or clear app data on the same Omi account. Expected: Pro is still there (server-side).
  27. PostHog: Upgrade Billing Provider arrives with provider=play for selected, pending, cancelled, succeeded and failed.
  28. A non-US license tester. Expected: local currency in the plans sheet and the trial paywall, matching Play's own sheet.

Play reviewer: the review build must be the Play build N with the switch ON for the reviewer's account (cohort or ANDROID_BILLING=play); otherwise the reviewer sees Stripe. License-tester accelerated renewals and trials differ from what a real reviewer sees.

Review round 1 fixes

Money and entitlement:

  1. Account deletion cancels Google billing: backend/services/users/account_deletion.py:699 → backend/utils/play_publisher.py:95 (subscriptionsv2:cancel, DEVELOPER_REQUESTED_STOP_PAYMENTS, :75). A Google error raises DeletionBillingError('google_play', …) so the wipe retries and never reports success.
  2. Day-3 auto-refunds: the app sends the token on pending (app/lib/services/billing/play_billing.dart:267) and listens from launch when Play config is present (:119). The server records pending without granting and grants and acknowledges on the notification (backend/utils/play_billing.py:282). A token no client delivered binds through linkedPurchaseToken, else through the stored obfuscated-account map play_billing_accounts (:360, :372); with neither it is logged and never granted.
  3. No double billing: a Stripe checkout.session.completed or customer.subscription.created/updated for a user with a live Play row cancels the new Stripe subscription, refunds its first charge, logs both ids and sends a push (``backend/utils/play_stripe_guard.py, called from the webhook in backend/routers/payment.py`; `backend/utils/stripe.py` `cancel_and_refund_checkout_subscription`). The user is told: "Your Omi Pro is billed through Google Play, so we canceled the new card subscription and refunded it." The pointer exemption is gone: a live Stripe row is never overwritten by a Play renewal (`play_billing.py:299`, logged as double billing). Stripe Checkout is refused while a Play purchase is pending (`backend/utils/subscription.py:1327`) or live.
  4. A refunded or revoked token never grants again: sticky revoked (play_billing.py:388), verify refuses with 409 purchase_refunded (:343).
  5. POST /v1/payments/play/purchases is rate limited per uid, payments:play_verify 30/hour (backend/routers/play_billing.py:56). Trials: any Play subscription sets play_billing_customer; trial_eligible (backend/routers/users.py:1644) and Stripe trial_days (payment.py:853) both read it. A former Stripe customer is not trial-eligible, so the app buys the base plan without trial-7d.

Play reviewer build:

  • B1 PlayBilling.androidPlayPlatform registers InAppPurchaseAndroidPlatform lazily on first Play use, never at startup (app/lib/services/billing/play_billing.dart:109); test/unit/play_billing_platform_test.dart goes through the real registration.
  • B2 the web variant opens the outline paywall for Play-billed or provider-unknown readers (app/lib/pages/paywall/paywall_router.dart:54).
  • B3 PlayBillingDisclosure (renewal at the shown price until cancelled, managed and cancelled in Google Play, Billed by Google Play, Terms · Privacy) on the plans sheet and the outline paywall (play_plans_content.dart:216, outline_paywall_page.dart:297). New string playRenewalTerms through scripts/l10n.py.
  • B4 Android shows a loading state until the provider is known (plans_sheet.dart:781, paywall_checkout.dart:200, usage_provider.dart:144).
  • B5 paid Marketplace apps: a disabled "Not available on Android" for Play-billed readers (app/lib/pages/apps/app_detail/app_detail.dart:881). Other external links found: Omi hardware shop links in onboarding (pages/onboarding/complete_screen.dart, variants/yinka/connect_omi_step.dart; physical goods, outside Play's digital-goods rule) and creator payout setup (pages/payments/stripe_connect_setup.dart; receiving money). Left unchanged.
  • B6 PaywallCheckoutOutcome.pending (paywall_checkout.dart:156); no monthly upsell after it; the plans sheet shows "Your payment is pending…" and disables Subscribe.
  • B7 no Play trial offer for this account → the trial paywall becomes the plans view with the base plan and no trial wording (trial_paywall_page.dart:254).
  • B8 Restore shows the refusal, e.g. "belongs to another Omi account" (play_plans_content.dart:74, outline_paywall_page.dart:69, trial paywall).
  • B9 Usage page chat allowance is a percentage for Play readers (app/lib/pages/settings/usage_page.dart:835).
  • B10 Play subscriber elsewhere: Flutter iOS shows the Play subscriber view (plans_sheet.dart:782); web shows "Billed by Google Play" with the Play link (web/app/src/components/settings/PlansSheet.tsx). The server answers released clients with typed results: /v1/payments/customer-portal returns Play's subscriptions URL (payment.py:2260), so released macOS/Windows/iOS "Manage billing" opens Play; DELETE /v1/payments/subscription returns 409 with a "billed through Google Play" detail (payment.py:1201).

Grace period: Google's lifecycle doc says "Google Play dynamically extends the expiryTime value until the grace period has expired" and "During a grace period, the user should retain access". So expiryTime normally sits at the end of grace. The server now keeps access for any SUBSCRIPTION_STATE_IN_GRACE_PERIOD read, sets the period end to max(expiryTime, now + 24 h) and re-reads every 6 h. A notification that races Google's extension (past expiryTime) keeps access; ON_HOLD after grace removes it (test_grace_keeps_access_*).

Android build check (local, prod release variant): the merged AndroidManifest.xml contains <uses-permission android:name="com.android.vending.BILLING" /> plus com.android.billingclient.api.ProxyBillingActivity/V2, and prodReleaseRuntimeClasspath resolves com.android.billingclient:billing:9.1.0 (via in_app_purchase_android 0.5.5). Ran :app:processProdReleaseMainManifest and :app:dependencies with a throwaway placeholder google-services.json (the real prod file is not in the repo), deleted afterwards with all build output.

Stripe-only surfaces on Android and what a Play-billed user sees

Surface Where Play-billed user sees
Stripe Checkout webview (plans sheet) app/lib/pages/settings/widgets/plans_sheet.dart:781 PlayPlansContent: Play prices, Play sheet, Restore
Paywall variants' Checkout (trial, outline, web, monthly fallback) app/lib/pages/paywall/paywall_checkout.dart:55 Play purchase flow through _startPlay
Paywall prices app/lib/pages/paywall/paywall_checkout.dart:199 (PaywallOffer.forUsage) Play's formattedPrice strings
30-day downsell app/lib/pages/paywall/trial_upsell_sheet.dart:23 hidden (Play sells only trial-7d)
First-tap offer app/lib/pages/home/page.dart:144 mirrored: the same 7-day trial paywall with Play prices; shown only while Play lists the trial (trialEligible follows Play)
"Have an Omi Pro code?" hint app/lib/pages/paywall/trial_paywall_page.dart:218 hidden
Promo / prepaid code field app/lib/pages/settings/widgets/plans_sheet.dart:1121 not rendered (Play content replaces the sheet)
Cancel-flow stay offer app/lib/pages/settings/widgets/plans_sheet.dart:193 → cancel_subscription_sheet.dart not reachable; cancel is in Play's subscription center
Yearly switch (plans + home quiet-payer row) app/lib/pages/settings/widgets/yearly_switch.dart:57, app/lib/pages/home/widgets/quiet_payer_row.dart:91 hidden: a Play row has no stripe_subscription_id
Stripe customer portal / payment-issue row app/lib/pages/settings/widgets/plans_sheet.dart:701, app/lib/pages/home/widgets/payment_issue_row.dart:44 not shown: payment_issue is only built from Stripe
Referral rewards app/lib/pages/referral/referral_page.dart:46, app/lib/pages/settings/settings_drawer.dart:167 still shown: a reward is a free promotional grant, not a payment. While a Play subscription is live the grant waits (utils/referral_billing.billing_allows_claim). Follow-up: defer the Play renewal instead.

Money-safety review list (every changed line near grants and purchase starts)

  • Grants: backend/utils/play_billing.py:207 _grant (the only Play entitlement write; same calls as routers/monthly_switch._store), called at :344 (verify) and :386 (notification/reconcile).
  • Revokes: backend/utils/play_billing.py:219 _revoke (writes Free only when this token owns the row and the row is provider=play), called at :347 and :388.
  • Grant preconditions: :300-344 (product/base plan, obfuscatedExternalAccountId, deletion fence, token and linked-token ownership, live Stripe check :244, acknowledge :284 before bind), :351-388 (deletion fence, not_current guard :233).
  • Exclusive binding: backend/database/play_subscriptions.py bind_purchase (create(); uid never overwritten).
  • Stripe Checkout refusal for Play subscribers: backend/utils/subscription.py:1324.
  • Switch: backend/config/play_billing.py client_uses_play; backend/routers/users.py:1376.
  • Purchase starts (app): app/lib/pages/paywall/paywall_checkout.dart:55 (branch), _startPlay in the same file, app/lib/services/billing/play_billing.dart purchase (offer token + obfuscated account id), app/lib/pages/settings/widgets/plans/play_plans_content.dart _subscribe.

Analytics

The existing purchase events fire unchanged on the Play path: Upgrade Plan Selected, Subscription Plan Changed, Upgrade Succeeded Attributed, Upgrade Succeeded, Upgrade Cancelled. Released events cannot gain properties (registry rule), so the provider rides a new registered event, Upgrade Billing Provider {provider: play, stage: selected|succeeded|cancelled|pending|failed, billing_interval}. It is emitted only on the Play path. The name contains "upgrade", so it matches the PostHog keep rules. Registered in contracts/analytics/events.json + subscription-funnel consumer.

Stripe-only revenue/LTV/churn code (listed, not rewritten): web/admin/lib/stripe-subscriptions.ts, web/admin/lib/services/plan-economics.ts, web/admin/lib/wall-metrics.ts, web/admin/lib/wall-finops.ts, web/admin/lib/wall-rollup-sql.ts, contracts/product-telemetry/bigquery/plan-revenue-mrr.sql, backend/utils/billing_reconciliation.py (drift report; Play rows will look like paid_in_firestore_no_stripe_entitlement), backend/utils/observability/billing_webhook.py, backend/utils/observability/subscription_events.py, backend/utils/observability/renewal_observations.py, backend/utils/metrics.py.

Follow-ups (not in slice 1)

  • Play equivalents for the 30-day downsell, cancel-flow stay offer (Play retention offers), yearly switch (Play plan change with ChangeSubscriptionParam), promo codes (Play promo codes) and referral reward deferral.
  • Scheduler job wiring in backend/deploy/scheduler/jobs.yaml for reconcile (left out so merging adds no prod infra).
  • Account-deletion policy for play_subscription_purchases (kept as a billing ledger, like promotion_code_redemptions).
  • funded_processing backlog hook on Play grants (Stripe calls processing_backlog_worker only behind its flag).
  • Teach billing_reconciliation and revenue dashboards about provider=play.
  • Google Play's in-app messages for payment-declined (showInAppMessages).

Product invariants affected

INV-MEM-3 — backend/services/users/account_deletion.py gains a Play cancel inside the existing billing step (_cancel_subscription_for_account_deletion). Memory and privacy deletion order and behaviour are unchanged; a Play cancel failure keeps the deletion retryable exactly like a Stripe cancel failure, and never lets the wipe report success.

How it was verified

  • Backend: test_play_billing.py (60) and test_play_billing_money.py (25) pass. The 205 backend suites that touch payment webhooks, checkout, portal/cancel, the subscription route, account deletion, trials or Play billing pass one by one, including tests/routers/test_users.py (330) and the lifecycle, authority-writer and notification-dispatch guards. backend/scripts/typecheck.sh: 0 errors. Locally, test_cloud_run_metrics_egress_workflow, test_empty_capture_recovery, test_integration_canary_workflow and test_projection_pump_deploy_target fail identically on a clean origin/main checkout (environmental, not this diff).
  • App: test/unit/play_billing_test.dart (14), test/unit/play_billing_platform_test.dart (1, real registration path) and test/widgets/play_billing_plans_sheet_test.dart (18) pass. The 160 existing test files that touch paywall, plans, usage provider, subscription model, analytics, app detail and usage page pass, after one fix (app_install_flow_test's host has no UsageProvider).
  • Web: PlansSheet.play.test.tsx plus the existing PlansSheet tests (7) pass; tsc --noEmit clean.
  • Android build (local): the prod release merged manifest has com.android.vending.BILLING; com.android.billingclient:billing:9.1.0 is linked.
  • export_openapi.py --app-client regenerated; app-client compatibility checked against main; Dart, Swift and TypeScript clients regenerated. scripts/pr-preflight --pr-body-file green (74 checks).
  • UNVERIFIED: no real Play purchase, RTDN delivery, Publisher acknowledge/cancel call or Stripe refund was made, and the full Android APK was not compiled locally (the prod Firebase options file is not in the repo; CI's Android emulator job compiles it).

Tests

Backend: backend/tests/unit/test_play_billing.py, backend/tests/unit/test_play_billing_money.py. App: app/test/unit/play_billing_test.dart, app/test/unit/play_billing_platform_test.dart, app/test/widgets/play_billing_plans_sheet_test.dart, fakes in app/test/support/fake_play_billing.dart. Web: web/app/src/components/settings/__tests__/PlansSheet.play.test.tsx.

UI evidence

UI-Evidence: none -- the Play purchase sheet only renders with a Play-signed build on the internal track; widget tests cover the sheet and the manual script above covers the device.

Failure class (fixes)

Failure-Class: none

Line-count exceptions

Line-Count-Exception: backend/routers/users.py | 2861 -> 2875 | the subscription route reads X-App-Build, attaches play_billing, records the account map; trial eligibility reads Play history
Line-Count-Exception: backend/utils/subscription.py | 1874 -> 1880 | can_user_make_payment refuses Stripe Checkout for a live or pending Play purchase
Line-Count-Exception: backend/routers/payment.py | 2372 -> 2395 | webhook, portal, cancel and trial guards for Play subscribers; the guard itself lives in utils/play_stripe_guard.py
Line-Count-Exception: app/lib/utils/analytics/analytics_manager.dart | 3140 -> 3155 | one typed emitter for the registered Upgrade Billing Provider event

…ID_BILLING

Adds the Play purchase verify/bind endpoint, the RTDN Pub/Sub push handler and a
reconcile entry point. Play rows reuse the Stripe entitlement write path and carry
provider=play. ANDROID_BILLING (default stripe) and ANDROID_PLAY_BILLING_MIN_BUILD
gate which Android builds are told to buy through Play; with the switch off every
response is unchanged.
Avoids adding google-api-python-client to the runtime image lock.
…products

ANDROID_PLAY_BILLING_COHORT and the android-play-billing rollout cohort put
named users on Play while ANDROID_BILLING stays stripe. The trial offer is
trial-7d, credentials are ADC only, and the three retired Play products are
refused instead of granted.
…e server says so

Play-billed readers see Play's prices in their currency on the plans sheet and
every paywall, buy through Play's sheet (base plan plus the trial-7d offer when
Play lists it), and the server confirms before the success state. Pending,
cancel, already-owned, restore and token retry on next launch are handled.
Play subscribers manage in Play. iOS and Stripe subscribers are unchanged.
…detail

The server's Play refusal body carries the stable code in detail (bounded machine
code the typed client reads) and the user text in message.
@kodjima33 kodjima33 added the mux-proposal Mobile UX improver (MUX) proposal; waits for Nik's ship label Nov 23, 2026
@mintlify

mintlify Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
omi 🟢 Ready View Preview Nov 23, 2026, 8:18 AM

💡 Tip: Enable Automations to automatically generate PRs for you.

…es in config

routers/users.py imported utils.play_billing, which pulls the fair-use and LLM
stack; import-isolated router tests that stub openai failed to import it.

Failure-Class: none
Account deletion cancels the Play subscription (subscriptionsv2 cancel) and
fails loudly if Google refuses. Pending and notification-only tokens are bound
(linked token, then the stored account-id map) and acknowledged. A Stripe
subscription created for a live Play subscriber is cancelled and refunded, and
a Play renewal never overwrites a live Stripe row. Refunded tokens never grant
again. Verify is rate limited per uid, and Play history counts against Stripe
trials and vice versa. Grace keeps access while Google extends expiryTime.

Failure-Class: none
…Play

Register the Android in_app_purchase platform lazily when the server sends Play
config (B1). Send pending tokens to the server and listen from launch. Play
readers never get the hosted web paywall, see a loading state until the
provider is known, get renewal, cancel-in-Play, Terms and Privacy on every Play
purchase screen, a pending state that offers nothing else, a base-plan view when
Play has no trial for them, and Restore refusals. Paid Marketplace apps and the
US$ chat allowance are hidden for them. Play subscribers on iOS and web see
Managed in Google Play instead of Stripe actions.

Failure-Class: none
@kodjima33
kodjima33 marked this pull request as ready for review November 23, 2026 11:08
@kodjima33
kodjima33 merged commit 4fa06e2 into main Nov 23, 2026
80 of 82 checks passed
@kodjima33
kodjima33 deleted the feat/android-play-billing branch November 23, 2026 11:08
kodjima33 added a commit that referenced this pull request Nov 23, 2026
…ods, keyed account id), Play reviewer app fixes (trial disclosure, hardware-only store, paywall Retry, Play prices), prod deploy config (#26129)

## What changed and why

Follow-up to #26078 (merged as 4fa06e2), based on `main`. Money
review round 2 made three fixes conditions for turning Play Billing on
for all Android users. The general review said the build is not ready
for a Play reviewer without four app fixes. Nothing can be turned on in
prod until the Play settings are declared in the deploy config. Play
Billing stays off for every user: `ANDROID_BILLING=stripe`, empty cohort
env, and the minimum build is 1617. Only a uid in the
`android-play-billing` rollout cohort, on Android build 1617 or later,
uses Play.

## Round 2 (review of 77f0481)

Backend (money):
1. **No Google credentials for non-Play deletions.** The publisher is
built only after a Play purchase record of the user is found
(`backend/utils/play_publisher.py:161`). A Stripe or iOS user's deletion
never calls `google.auth.default`.
2. **Grace-mode deletion no longer swallows a failed Play cancel.** The
Play cancel now propagates exactly like a Stripe failure
(`backend/services/users/account_deletion.py:706`); the round-1
`defer_play_failure` path is gone. In grace mode the delete request
fails and `grace_actions_complete` is never written, so the reconciler
re-runs the admission steps every cycle until Google confirms
(`:938-946`, unchanged). In immediate mode the request fails the same
way a Stripe failure does. I picked propagation because it is what
Stripe already does; a separate `play_cancel_pending` marker field would
be new schema.
3. **RTDN transport errors never carry the token.** `apply_token` wraps
every non-`PurchaseNotFound` read error as `PlayBillingError(503,
'play_unavailable')` with only the type name logged, `from None`
(`backend/utils/play_billing.py:432`). Pub/Sub retries on the 503.
4. **User-cancelled subscription with time left.** CANCELED with a
future expiry now gets the developer cancel too, best effort: a failure
is logged with the status only and does not park the wipe, since nothing
is due (`play_publisher.py:118`, `:173`). This stops the user
un-cancelling in Google Play after the account is gone.
5. **Voided notification without Google's order ids revokes** (fail
closed; `_latest_order_ids` returns an empty set, `play_billing.py:406`,
`:439`).
6. **Nits:** `hmac.compare_digest` on bytes at `play_billing.py:354` and
`:394`; `route_policy_manifest.yaml:116` now states the verify route's
real limiter (`payments:play_verify`, uid, fail-open, dependency; 30/h
in `utils/rate_limit_config.py`).
7. **Retention on wipe.** The account wipe has a new step,
`play_billing_records`, after the billing step confirmed Google stopped
charging and before the Firestore user-data wipe
(`backend/services/users/account_deletion.py:525`). It deletes every
`play_subscription_purchases` doc and `play_billing_accounts` entry
whose `uid` is the user (`backend/database/play_subscriptions.py:136`,
through `backend/utils/play_publisher.py:190`); a failure keeps the wipe
retryable. No uid + purchase token is left behind. A later notification
for a dropped token finds no owner and is recorded unbound (token-hash
id, token, no uid), never granted. The query is registered in the
Firestore query driver registry (single-field `uid` equality, built-in
index). About 20 lines of code, no schema change. The grace admission
path never purges, so Restore during grace keeps the subscription.

App (reviewer-facing):
8. **Shop on the `app-hardware` template, fail closed.** The store opens
`https://www.omi.me/products/omi?view=app-hardware&_ref=<source>`
(`app/lib/pages/shop/omi_shop.dart:24`). Any allowed main-frame
navigation to `/products/omi` without `view=app-hardware` (or with
another view) is replaced by the same URL with it. After a device page
finishes loading in the restricted view, the app runs
`document.getElementById('omi-app-hardware') !== null`; the page stays
behind the loading state until it passes, and if the marker is missing
(template removed, Shopify fell back to the normal page) the reader sees
"This page isn't available in the app." with Close instead
(`omi_shop.dart:74-81`,
`app/lib/pages/apps/widgets/omi_web_page.dart:136`, `:149`, `:219`). iOS
and non-restricted readers are untouched (no policy, no check).
9. **Allow-list shape** (`omiHardwareNavigation`, `omi_shop.dart:48`):
- `www.omi.me` / `omi.me`: `/products/omi` (forced to the template),
`/cart`, `/cart/*` (permalinks such as `/cart/<variant>:<qty>`, used by
the page's own Get Omi button), `/checkout`, `/checkouts/*`,
`/<digits>/checkouts/*`, `/policies/*`. Everything else is blocked
(home, `/pages/*`, other products, collections, search).
- Off-site https pages are allowed only when the current page is a
`/checkouts/` page (any host) or already an off-site page reached that
way. That covers Shop Pay (`accounts.shop.app` etc.), PayPal, Klarna,
Afterpay, Amazon Pay, bank redirects and top-level 3-D Secure without a
host list. From the product, cart and policy pages, off-site navigation
stays blocked. A return to omi.me goes through the path allow-list
again.
   - Subframes are not filtered.
10. **Blocked navigation is not silent:** a SnackBar says "This page
isn't available in the app." (new l10n key `pageNotAvailableInApp`, 49
locales). A `post-purchase` / `post_purchase` hop (payment already
taken) **closes the web view** and shows "Order placed. Check your email
for the confirmation." (`shopOrderPlacedCheckEmail`,
`omi_shop.dart:119`). I did not try to derive the thank-you URL:
Shopify's new checkout paths are not documented enough to build one
safely. UNVERIFIED against a live order.
11. **Trial copy follows Play.** The trial page uses the selected plan's
Play trial length (`PaywallPrice.trialDays` from
`PlayPlanOffer.trialDays`) for the "In N days" row, its date, the price
terms and the monthly fallback sheet (`trial_paywall_page.dart:310`,
`:130`, `:164`). If any listed Play plan has no free-trial phase for
this account (trial used, or not eligible), the reader gets the plain
Play plans instead: price, Subscribe, renewal disclosure, no trial
promise and no "free until" row (`:276`). The plans sheet and the
outline paywall already used `PlayPlanOffer.trialDays` per plan and show
no trial when it is null; unchanged.
12. **Paid apps:** `app_detail.dart:867` hides the app's own payment
link for `playBilledPurchaser || billingProviderUnknown` (Android-only
getter), as the store does.
13. **Play query timeout:** `isAvailable()` and `queryProductDetails`
time out after 10 s
(`app/lib/services/billing/play_billing.dart:158-159`); the provider's
catch ends loading and the paywalls show Retry.

CI note: `backend/docs/people-generation-writers.json` re-pins
`chat_edits.py:apply_update`. Main has failed
`test_people_generation_inventory` since ccb9670 (David Zhang,
today), which changed only which `ValueError` subclass `apply_update`
raises for an unsupported field, before any write. The People write and
generation bump path is unchanged; `test_chat_edits_firestore` and
`test_chat_edit_tools` pass.

Not changed, as agreed: the shop restriction while the provider is
unknown, Android creators pricing apps, and `apply_token`'s
read-then-write without a transaction.

## Money fixes

1. **Account deletion can no longer park forever on a Play cancel.**
- `backend/utils/play_publisher.py:130` re-reads `subscriptionsv2`
first. Not found, or any state that can no longer charge (EXPIRED,
CANCELED, PENDING_PURCHASE_CANCELED), is already done.
- If the cancel call fails, it re-reads once more (`:117`) and accepts a
state that can no longer charge.
- Anything else raises `PlayCancelPending` (`:44`). It is not a
`DeletionBillingError`, so the wipe marks the marker `failed`, which the
deletion reconciler retries with backoff (max 1 h, no terminal state)
instead of `billing_failed` (`services/users/account_deletion.py:706`).
Admission no longer fails the delete request on it; the wipe repeats the
cancel at its irreversible boundary (`:725`).
- Failures parked by the first Play release are re-claimed
(`database/account_deletion_policy.py:53`).
- Publisher errors are now `PublisherHTTPError(status)` (`:36`). No
exception text, log or stored `billing_error` carries a request URL or
the purchase token: only the HTTP status and the first 12 characters of
the token's SHA-256.
2. **Refund without revoke.**
- A voided notification or REVOKED records `revoked_through` = the
expiry Google showed at that moment
(`backend/utils/play_billing.py:438`) and removes access.
- The token grants again only when Google shows a later period in a paid
state, ACTIVE or CANCELED with expiry > `revoked_through` (`:171`,
`:367`). Grace is a failed charge, so it never re-grants.
- A refund of an earlier order (voided `orderId` is not the latest
order) keeps the current paid period (`:430`).
- A real revoke ends the subscription at Google (EXPIRED), which never
returns to a paid state, so it never re-grants.
- Refund-only tokens stay on the reconcile schedule so the renewal is
seen.
- Records written by #26078 with the old `revoked: true` flag keep never
re-granting (`:163`).
3. **Account id is a keyed HMAC.**
- `obfuscated_account_id = HMAC-SHA256(PLAY_ACCOUNT_ID_HMAC_KEY, uid)`
(`backend/config/play_billing.py:132`). The key comes from Secret
Manager (secret `PLAY_ACCOUNT_ID_HMAC_KEY`, at least 32 characters).
Without it no Play config is issued (`:75`) and verify answers `503
play_not_configured`.
- The account map is written once per id (exclusive create), only by the
server, only for the uid it issued the id to. Binding through it
re-checks `HMAC(uid) == id` (`backend/utils/play_billing.py:391`) and
never moves an existing binding.
- No migration: there are no Play purchases in prod yet (#26078 is off
and the product is in DRAFT).

## Play reviewer build

4. **Trial paywall disclosure:** `PlayBillingDisclosure` (renewal at the
shown price until cancelled, managed and cancelled in Google Play,
Billed by Google Play) replaces "Cancel anytime" for Play-billed readers
(`app/lib/pages/paywall/trial_paywall_page.dart:221`). Terms and Privacy
stay in the page footer.
5. **Store web view.** For Android readers on a Play-billing build (Play
config issued, or provider not known yet), the store opens only the
device page; round 2 items 8-10 above give the current URL and
allow-list (the round-1 fixed host list is replaced).
- The Connect page's "Get Omi" opened the browser, which cannot be
restricted. Play-billing readers now get the same restricted in-app
store there (`app/lib/pages/capture/connect.dart:30`). Everyone else
keeps the browser.
   - The web store itself is unchanged.
6. **Retry:** `PlayPlansError` (the plans sheet's `OmiErrorState` with
Retry, `play_plans_content.dart:267`) replaces the dead "Unable to load
plans" on the trial (`trial_paywall_page.dart:380`) and outline
(`outline_paywall_page.dart:240`) paywalls. Retry re-reads the
subscription when that failed, otherwise reloads Play's offers. A failed
subscription read ends the outline skeleton
(`UsageProvider.billingProviderFailed`).
7. **Play prices on the trial cards:** the cards use `price.formatted`,
which is Play's string for Play readers and the same string as before
for Stripe (`trial_paywall_page.dart:397`, `:409`). The computed "was"
(12 × monthly) and "Save" amounts are hidden for Play readers. The CTA
uses Play's own trial-phase string ("Try for Free" / "Try for ₹0.00")
instead of an app-formatted zero (`:457`). The outline yearly card's
computed per-month is replaced by "Billed yearly" for Play readers
(`outline_paywall_page.dart:251`); its "Save N%" is computed from Play's
two prices in the same currency.

## Deployment configuration (item 8)

Declared on the prod Cloud Run `backend` service
(`backend/deploy/runtime_env/prod.overlay.yaml`, composed into
`backend/deploy/runtime_env.yaml`):

| Key | Value |
|---|---|
| `PLAY_RTDN_OIDC_AUDIENCE` |
`https://api.omi.me/v2/internal/play-billing/rtdn` |
| `PLAY_RTDN_PUSH_SA` |
`[email protected]` |
| `PLAY_RECONCILE_OIDC_AUDIENCE` |
`https://api.omi.me/v2/internal/play-billing/reconcile` |
| `PLAY_RECONCILE_INVOKER_SA` |
`[email protected]` |
| `PLAY_ACCOUNT_ID_HMAC_KEY` | Secret Manager secret
`PLAY_ACCOUNT_ID_HMAC_KEY`, version `latest` |
| `ANDROID_PLAY_BILLING_MIN_BUILD` | `'1617'` (`prod.overlay.yaml:655`):
the last internal build, 1616, predates these fixes; every later build
is cut from main after this PR |
| `ANDROID_PLAY_BILLING_COHORT` | `''` (members come from the rollout
cohort below) |
| `ANDROID_BILLING` | `stripe` (only `play` sends every new Android
purchase to Google) |

- **Order matters.** Create the secret `PLAY_ACCOUNT_ID_HMAC_KEY` in
project `based-hardware` (for example `openssl rand -hex 32`) and grant
`[email protected]`
`roles/secretmanager.secretAccessor` on it **before the first backend
deploy that includes this PR**. Cloud Run refuses a revision whose
secret does not exist.
- **Routing:** `gcloud compute url-maps describe custom-domains-49a4`
sends `api.omi.me/*` (so `/v1/payments/play/*` and
`/v2/internal/play-billing/*`) to backend service
`custom-domains-api-omi-me-backend-49a4-be`. That is the serverless NEG
`custom-domains-api-omi-me-backend-49a4-neg`, i.e. Cloud Run `backend`.
Only `/v1/sync-local-files`, `/v2/sync-local-files`,
`/v1/users/migration/batch-requests` and `/v1/sync/audio/*` go to
backend-sync, `/v3|v4/listen` to backend-listen, and
`/v2/integrations/*` and `/v1/mcp*` to backend-integration. `backend`
has no `OMI_ROLE`, so it mounts every router. No other service needs
these keys.
- **Staging** keeps the four RTDN/reconcile values empty on its
`backend` (routes answer 403) and drops the secret (unmapped).
`PLAY_RTDN_PUSH_SA` is added to the staging diff allow-list next to
`*_INVOKER_SA`.
- **Classification and flags:** the new keys are classified in
`config/deployment-setting-classification.json` (secret / config), and
the flag registry doc is regenerated.
- **Checks run:** `scripts/pre-deploy-check.sh` (704 passed);
`test_render_backend_runtime_env.py` (the approved prod secret bindings
now include `PLAY_ACCOUNT_ID_HMAC_KEY` on `backend`);
`test_runtime_env_sources.py`; `test_backend_runtime_env_validator.py`;
`cross_service_contract.py --all` (0 new violations).

**Putting the test account on Play Billing (no uid in Git):**
1. Write the tester's uid to a private file (one line), e.g.
`/tmp/play-tester-uid`. The tool never prints it.
2. With the prod operator tier (`GCP_AGENT_TIER=prod-operator`,
`GOOGLE_APPLICATION_CREDENTIALS` set), from `backend/`:
`python scripts/rollout_cohort.py --uid-file /tmp/play-tester-uid
--cohort android-play-billing --project based-hardware --environment
prod --add --apply`
This merges `cohorts.prod["android-play-billing"] = true` into
`rollout_cohorts/{uid}` in the **default** Firestore database of
`based-hardware` (the customer data plane,
`docs/runbooks/rollout-cohorts.md`). It is not the `omi-flags` database:
`OMI_FLAGS_SOURCE=omi` / `omi-flags` is the separate flag store used by
the LLM gateway and does not hold cohorts.
3. It takes effect within 60 s (the per-process cohort cache TTL) with
**no redeploy**. Remove with `--remove --apply`.

`ANDROID_PLAY_BILLING_MIN_BUILD` is read from the environment only (not
from Firestore), so it is set here to `1617` to save a second config
deploy. With `ANDROID_BILLING=stripe` and an empty cohort env,
`client_uses_play` is still False for every client; a test uid is then
enabled by the `android-play-billing` rollout cohort alone, with no
redeploy.
`test_deployed_prod_values_send_nobody_to_play_without_the_rollout_cohort`
(`backend/tests/unit/test_play_billing.py:654`) reads the rendered prod
values and proves: False on Android 1617 and 9999 without the cohort;
True for the cohort uid on 1617, False on 1616; the switch-off
subscription response is byte-identical on 1617 and 9999.

## Correction to #26078's description

macOS and Windows desktop changed only generated files in #26078. They
do **not** show "Billed by Google Play"; their Manage billing button
calls the portal endpoint, which now returns Google Play's subscriptions
URL, and that opens in the browser. Flutter (iOS) and the web app show
"Billed by Google Play" with the Play link.

## Product invariants affected

INV-MEM-3 — `backend/services/users/account_deletion.py`: the Play
cancel moves out of the Stripe billing wrapper and fails as a retryable
wipe error instead of a parked billing failure, and a failed admission
cancel keeps grace actions incomplete. The wipe also drops the user's
Play purchase records and account-map entries (new
`play_billing_records` step). Memory and privacy deletion order are
unchanged; the wipe never reports success while Google can still charge.

INV-MEM-4 — named because `account_deletion.py` is under its glob.
Memory intake, consolidation and promotion are untouched.

## How it was verified

- Backend:
  - `test_play_billing.py` (62) and `test_play_billing_money.py` (49).
- Account wipe suites touching `purge_user_subtree`, the Firestore query
shape and outside-query guards, route policy inventory and preflight:
3802 + 663 passed.
- Every `test_*account_deletion*`, `test_delete_account*` and
`test_rollout_cohort*` suite.
- `tests/routers/test_users.py` (330), checkout, webhook and trial
suites.
- `pre-deploy-check.sh` (704) and the runtime-env, render, validator and
cross-service checks: all pass.
- App:
- `play_billing_plans_sheet_test.dart`, `play_billing_test.dart`,
`play_billing_platform_test.dart`, `omi_shop_hardware_test.dart` and
`connect_device_get_omi_test.dart` pass.
- The 84 existing test files touching paywalls, plans, usage provider,
shop and web page: 1019 passed (round 1); round 2: the 26 paywall,
plans, shop, web page, app detail, connect and Play test files: 270
passed. `scripts/l10n.py check` ok; analyzer clean on the changed files.
- UNVERIFIED:
- a real Publisher `subscriptionsv2:cancel`, including which error
Google returns for an already-ended subscription (handled either way by
the re-read);
  - a real refund-only renewal;
- the store allow-list against a live Shopify checkout (wallet hosts and
the post-purchase path naming);
  - a real deploy with the new secret;
- Google's answer to a developer cancel of an already user-cancelled
subscription (best effort either way);
- the in-app store on a device: the `app-hardware` marker check, the
off-site rule with Shop Pay, PayPal and a 3-D Secure card, and the
post-purchase close, against a live order;
- the 10 s Play query timeout on a real device with a stuck Play client.

## Tests

- Backend: `backend/tests/unit/test_play_billing_money.py` (deletion
re-read, failed-cancel re-read, 400/403/503 retryable without the token,
wipe-not-parked, legacy re-claim; refund then renewal, refund and
revoke, refund then re-post, grace after refund, earlier-order refund;
forged id, tampered map, missing key, write-once map),
`backend/tests/unit/test_play_billing.py` (HMAC id, key-gated switch),
`backend/tests/unit/test_render_backend_runtime_env.py`.
- Backend round 2 (`test_play_billing_money.py`): deletion without ADC
for a user with no Play fields; grace admission with Google 503 then a
reconciler run that cancels and completes; RTDN transport error whose
message holds the token (absent from `str(e)` and the traceback);
cancelled-with-time-left is cancelled, its failure does not park, an
ended one needs no cancel; voided without order ids revokes; the wipe
drops purchase docs and map entries. `test_play_billing.py`: deployed
prod values.
- App: `app/test/widgets/play_billing_plans_sheet_test.dart` (trial
disclosure, Play price strings, no computed was/save, Play trial CTA,
Retry on outline and trial, failed subscription read recovers; round 2:
3-day Play trial, a plan with no trial phase, a Play client that never
answers ends in Retry), `app/test/unit/omi_shop_hardware_test.dart`
(template forcing, allowed and blocked URLs, off-site only from
checkout, post-purchase closes, marker present shows / missing blocks).

## UI evidence

UI-Evidence: none -- these Play screens only render with Play config
from the server; widget tests cover each state.

## Failure class (fixes)

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Dec 1, 2026
…), default off (#26841)

> **Revives #26074** (kodjima33, closed 2026-11-23 in favour of Play
Billing) on current `main`, **as written**, at David's request
(2026-12-01): try currency localization through Stripe before turning on
Play Billing (#26826, left as a draft). Original author credited on the
commit.
>
> **On top of #26074 @ `aec826ee9c0`:** resolved conflicts with main
(Play Billing's `is_play_customer` checkout check and `http_request`
parameter in `payment.py`, the `prepaid_code_redeem` import in
`retention_offer.py`, `playMinorUnits` in `billing_price.dart`, the
`trialDays` local in `trial_paywall_page.dart`); stubbed
`is_play_customer` in the new checkout test helper; registered
`STOREFRONT_LOCAL_CURRENCY` and `STOREFRONT_LOCAL_CURRENCY_TABLE` in
`config/feature-flags.yaml` with the ramp plan below. No behaviour
change against the original PR.
>
> **Review round 1** (omi-panel review-20261201t012244-67c6): F1
accepted. Android now sends only the Play billing country: no locale
fallback, and a failed read is retried (luna's fix check). F4 accepted:
a malformed table falls back to USD. F2 accepted: test that the region
header is sent. F5 deferred to ramp step 5. F3 and F6 deferred (minor).
>
> **Merging changes nothing for buyers.** The switch is on, but both
live Omi Pro Prices are USD-only (read 2026-12-01T00:4xZ with the
read-only key: `price_1TuIa8…` 2999 usd/month and `price_1TuIap…` 26991
usd/year, `currency_options` = `usd` only), so every path falls back to
today's USD.

## On by default (David, 2026-12-01)

Prod serves `STOREFRONT_LOCAL_CURRENCY=android` and the full price table
(`backend/deploy/runtime_env/prod.overlay.yaml`). **Kill switch: set
`STOREFRONT_LOCAL_CURRENCY=off`.** David chose on by default so a later
release, config cleanup or rollback cannot drop local prices silently
and reopen the Play Subscriptions finding.

What a buyer sees after this merges, step by step:

| Step | Who | Effect |
|---|---|---|
| 1. Merge; backend serves the switch and the table | David (billing
class) | **None.** Both Omi Pro Stripe Prices are USD-only, so every
buyer falls back to USD (logged as `local currency <cur> unavailable`) |
| 2. Stripe write: `scripts/local_currency_options.py --table <prod
table> --apply --confirm` | David approves the dry-run output first |
New Android buyers on a build with the region header, whose **Play
billing country** is in the table, see and pay the local price |
| 3. New Android build replaces the held 1605 at 1% in Play production
(agent through the Play API); David clicks Send for review | agent,
David | Play reviewer sees local prices |
| 4. `all` (iOS, desktop, web) | billing owner | Only after web and
desktop send `X-Omi-Storefront-Region` (panel F5) |

Clean metric: `local currency <cur> unavailable` lines fall to zero
after step 2. Checkout sessions charge the displayed amount, and there
are no currency refunds or tickets. Rollback: `off`. New buyers go back
to USD, and subscribers already billed in a local currency keep it
(Stripe fixes a customer's currency).

### Price table: 63 countries, 43 currencies

This is #26074's 53-country, 33-currency first rollout (below), plus
**the ten it dropped**. They're priced from open.er-api.com USD rates of
2026-12-01 00:02Z, using the existing table's rounding: x.99 under
1,000, nearest 50 up to 9,999, nearest 5×10ⁿ above. All pass
`_valid_amount`, and a test loads the rendered prod value whole.
**#26074 did not record why these ten were removed** (volatility, card
acceptance or something else). David approves the full table with this
PR.

| Currency | Country | Monthly | Annual | Stripe minor units (monthly /
annual) | USD rate |
|---|---|---|---|---|---|
| INR | IN | ₹2,750.00 | ₹25,000.00 | 275000 / 2500000 | 92.3848 |
| PKR | PK | PKR 8,300.00 | PKR 74,500.00 | 830000 / 7450000 | 276.7613
|
| EGP | EG | EGP 1,650.00 | EGP 14,500.00 | 165000 / 1450000 | 54.4072 |
| NGN | NG | NGN 41,000.00 | NGN 370,000.00 | 4100000 / 37000000 |
1370.8915 |
| ARS | AR | ARS 48,000.00 | ARS 435,000.00 | 4800000 / 43500000 |
1608.4695 |
| TRY | TR | TRY 1,500.00 | TRY 13,500.00 | 150000 / 1350000 | 50.8373 |
| UAH | UA | UAH 1,350.00 | UAH 12,000.00 | 135000 / 1200000 | 45.0979 |
| BDT | BD | BDT 3,750.00 | BDT 34,000.00 | 375000 / 3400000 | 125.5905
|
| KES | KE | KES 3,900.00 | KES 35,000.00 | 390000 / 3500000 | 130.1779
|
| ISK | IS | ISK 3,800 | ISK 34,000 | 380000 / 3400000 | 125.9020 |

ARS and TRY lose value fast against USD. Their amounts need a periodic
review, and a change is a new `currency_options` amount plus a table
edit.

---

## What changed and why

Google Play rejected Android (com.friend.ios) again on Nov 21 for
version code 1605: "Currency differences with prominent display price
... appropriately localized for each country". Its evidence is the trial
paywall priced in US$ for a reviewer outside the US. The three earlier
fixes (#23852 adaptive pricing off, #25494 pinned `CHECKOUT_LOCALE`)
made the Stripe cart match the app's USD price; the offer page itself
still showed US$ to a non-US buyer, which Google's Subscriptions policy
lists as a violation ("language and currency are not localized to the
user's country").

This adds a local-currency offer for buyers with no paid subscription.
**It is off by default and changes nothing until both a switch and a
price table are set.**

- A buyer whose country has an approved local price sees that currency
and amount on every price surface (trial paywall, Plans sheet,
`/v1/users/me/subscription` price strings, the Stripe cart and its trial
line), and Checkout charges the same Stripe `currency_options` entry on
the same Price ID.
- A US buyer, a buyer in a country outside the table, and every released
build (they send no region) get today's responses byte for byte: US$, as
Google Play itself prices where it has no local currency. Nothing hides
the purchase UI.
- A table currency the live Price does not carry in `currency_options`,
or whose amount differs from the table, is logged (`local currency <cur>
unavailable on <price> ...`) and that buyer gets USD, so a config
mistake cannot open a Checkout in a currency the Price lacks.
- A subscriber's billed currency is decided from Stripe alone (the
subscription's `currency` and the Price's `currency_options[that
currency]`, `utils/local_currency.py` `billed_option_amount`), never
from the switch or the table, so a rollback or table edit cannot tell a
GBP subscriber "US$269.91 a year" while Stripe bills £. That subscriber
keeps the currency in available plans, interval change (schedule phases
pinned to it), the Plans current card, the trial-ending push, promo
redemption, the retention offer and billing analytics. If the Price
cannot be read the surface shows no amount (no push, no current price, a
503 on plan management), never a guessed one. The yearly and monthly
switch offers refuse non-USD subscriptions, as before.
- An existing Stripe customer's currency is fixed, so it wins over the
region on every new-buyer surface and at Checkout (`buyer_currency`,
`new_buyer_offer`): a lapsed USD customer in a table country stays in
US$; a lapsed GBP customer who moved to the US sees and pays £ when the
Prices carry GBP, independent of the switch; a customer currency the
Prices lack keeps today's US$ path. First-time buyers with the switch
off read nothing new; the customer read happens only once an offered
Price carries a non-USD option.
- Promo codes on a subscription billed through a currency option
(`utils/promotion_redemption.py` `_check_local_currency_eligible`): a
minimum stated in the subscription currency (directly or in
`restrictions.currency_options`) is compared with the option amount; a
minimum stated only in the Price's own currency (the USD-only bundle and
prepaid codes) is compared with the same Price's USD amount, because it
is the same plan, so those buyers can redeem and are not charged at
trial end because the code was refused; a minimum in any other currency
is refused; a fixed `amount_off` coupon needs an amount in the
subscription currency (Stripe cannot apply a USD amount there);
percent-off codes, including 100%, always apply.

### Turning it on (operator steps, not part of this PR)

1. Nik approves amounts (proposal below).
2. `backend/scripts/local_currency_options.py --table table.json` prints
the exact `stripe.Price.modify(... currency_options=...)` calls for the
two Omi Pro prices. It is a dry run; only `--apply` writes, and that was
not run.
3. Set on the backend service:
- `STOREFRONT_LOCAL_CURRENCY=android` (first rollout; `all` adds
iOS/desktop/web, `off` or unset is today).
- `STOREFRONT_LOCAL_CURRENCY_TABLE` = one JSON object: `{"countries":
{"<ISO 3166-1 alpha-2, upper>": "<ISO 4217, lower>", ...}, "currencies":
{"<iso 4217>": {"monthly": <int>, "annual": <int>}, ...}}`, e.g.
`{"countries": {"JP": "jpy", "GB": "gbp", "DE": "eur", "FR": "eur"},
"currencies": {"jpy": {"monthly": 4800, "annual": 43200}, "gbp":
{"monthly": 2299, "annual": 20699}, "eur": {"monthly": 2699, "annual":
24299}}}`. Amounts are Stripe minor units: zero-decimal currencies in
whole units (JPY 4800 = ¥4,800, KRW, VND, CLP and the rest of Stripe's
list), three-decimal in thousandths, HUF/TWD/ISK/UGX in hundredths and
whole hundreds. Many countries may share a currency; a country mapped to
`usd` is the US price. Entries Stripe or the cart cannot represent (not
a Stripe currency, not whole hundreds for HUF/TWD/ISK/UGX, a fraction
ISK/UGX cannot display) are dropped with a warning at read time.
4. Ship the Android build from this branch. The server shows a local
price only when Stripe's `currency_options` amount equals the table
amount for both intervals; otherwise USD (logged), never mixed.

## Investigation

**Every price string that reaches a client**

| Surface | Where | Before | Now (switch on, local buyer) |
|---|---|---|---|
| Trial paywall, paywall variants, Plans sheet (old catalog) | `GET
/v1/payments/available-plans`, `backend/routers/payment.py:497` | USD
`unit_amount`, `price_string`, `billing_total` from `format_money` |
same Price IDs in the local currency (`_localized_pricing_options`,
`payment.py:684`) |
| Plans sheet v2 (new buyer Omi Pro sheet, Free card) | `GET
/v2/payments/plans`, `routers/storefront.py:119`, `utils/storefront.py`
`build_single_plan_storefront` | US$ headline/subline; Free card
`headline_free` = "US$0" (`config/storefront_copy_v1.json`) | local
headline/subline and Free card in the local currency |
| Plans current card for a subscriber | `utils/storefront.py`
`build_storefront`, `current_line` (`utils/storefront_copy.py`) | price
row's base currency | subscription currency option |
| `/v1/users/me/subscription` `available_plans[].prices[].price_string`
| `routers/users.py:1296` | US$ (not rendered by the Flutter app) |
local |
| Stripe cart, trial terms line, "All amounts are in" |
`utils/stripe.py:213`, `utils/trial_reminder.py` `checkout_trial_terms`
| price currency; `CHECKOUT_LOCALE='en-GB'` | `currency` = local, locale
`en` (renders the same glyph as the app), local trial line |
| Trial-ending push | `utils/trial_reminder.py`
`trial_ending_reminder_body` | item price `unit_amount` (base USD on a
multi-currency Price) | subscription currency option |
| Retention (cancel) offer | `utils/retention_offer.py` `evaluate` |
item price | subscription currency option |
| Yearly switch / monthly switch | `utils/yearly_switch.py:30`,
`utils/monthly_switch.py:40` | `SWITCH_CURRENCIES={'usd'}` | unchanged:
a non-USD subscription is refused (`reason='currency'`) |
| Hardcoded "US$" in the app | `app/lib/utils/billing_price.dart` (only
formatter; every surface calls it with the server's currency),
`app_en.arb` descriptions only (examples, not values) | `US$`, `¥`, else
`CODE 1.00` | generated table, the exact Checkout render for all 138
Stripe currencies; USD and JPY strings unchanged |

`app/lib/models/subscription.dart`, `yearly_switch.dart`,
`trial_paywall_page.dart`, `storefront_plans_content.dart`,
`paywall_checkout.dart`, `monthly_switch_sheet.dart`,
`payment_issue_row.dart` and `cancel_subscription_sheet.dart` already
format through `formatBillingPrice(amount, currency)` with a `usd`
fallback only when the server sends no currency, so no other app surface
hardcodes US$. Server-side copy (`format_money`) is unchanged for every
existing response; the local path uses `local_currency.display_money`,
the same string the app renders.

**Existing subscribers' strings with the switch off (review item 7).**
`formatBillingPrice` now renders every currency as Checkout does, which
changes the string for currencies other than USD and JPY (for example
`CAD 29.99` becomes `CA$29.99`). That is intended, because it is the
cart's own text, and it cannot reach anyone today: the plan catalog and
the management bindings contain only USD and JPY Prices
(`test_released_currencies_reach_the_app_unchanged_with_the_switch_off`),
and USD and JPY render byte for byte as before (`US$29.99`, `¥4,800`;
app test "USD and JPY render exactly as before"). Keeping two formatters
for a switch the app cannot see would be the larger change.

**Display string = the Checkout render.** Stripe Checkout formats
amounts with the browser's `Intl.NumberFormat` in the session locale,
which the server pins: `en-GB` for USD (US$, #25494), `en` for every
other currency (`local_currency.checkout_locale`).
`backend/scripts/generate_checkout_currency_format.py` renders all 138
Stripe presentment currencies through Node's ICU (77.1, CLDR 47) at that
locale and writes the symbol prefix, display decimals, Stripe exponent
and a sample to `backend/config/checkout_currency_format.json` and
`app/lib/utils/checkout_currency_format.dart`. The server
`display_money` and the app `formatBillingPrice` are both tested against
every sample character for character, NBSP included (`AED\u00a0109.99`,
`¥4,800`, `₩39,000`, `CLP\u00a027,990`, `HUF\u00a010,990.00`,
`NT$990.00`, `ISK\u00a03,999`, `UGX\u00a0110,000`, `KWD\u00a01.234`).
`--check` fails when either output is stale. The generator refuses to
run on anything but Node v22.22.0 with ICU 77.1 (ICU 78 renders HUF,
COP, IDR, PKR and RSD differently) and is registered in
`.github/checks-manifest.yaml` (`checkout-currency-format`, local and ci
lanes); the CI hygiene job installs exactly Node 22.22.0.

**Country signal.** Read, not guessed: the backend never reads a client
IP or geo header (`routers/public_shared_conversation_chat.py:165`,
`pusher/main.py:130`), `backend/charts` and `backend/deploy` declare no
load-balancer request headers, and the live prod backend services behind
api.omi.me (`custom-domains-api-omi-me-backend-*`,
`prod-omi-backend-api`) have no `customRequestHeaders` (`gcloud compute
backend-services list`, read-only). So there is no trustworthy
server-side country today. The primary signal is the device region the
new app sends as `X-Omi-Storefront-Region` (system locale country,
`app/lib/utils/storefront_region.dart`, added in
`app/lib/backend/http/shared.dart`). It needs no permission or native
code and every build after this one sends it. An old app sends nothing
and gets today's behaviour. It is user-settable, so it can only choose
among prices Nik approved; the follow-up that would make it match where
the reviewer physically is would be a GCP LB `X-Client-Region:
{client_region}` header, a prod infra change outside this PR.

**Stripe price shape.** The live Omi Pro prices
(`STRIPE_UNLIMITED_V2_MONTHLY_PRICE_ID` 2999 USD/month,
`..._ANNUAL_PRICE_ID` 26991 USD/year) carry `currency_options={'usd'}`
only (pipeline snapshot fetched with `expand[]=currency_options`).
`currency_options` is returned only when expanded, so every local read
uses `expand=['currency_options']`
(`local_currency.retrieve_with_options`). Checkout already pins
`currency` to the session and disables adaptive pricing
(`utils/stripe.py`); with a multi-currency Price, `currency=<local>`
selects that option, so the cart charges exactly the option amount.

**What else assumes USD**

- A subscription on a multi-currency Price carries the base Price (USD)
on `items[0].price`; the subscription's own `currency` is the billed
one. Every reader of `items[0].price.unit_amount` therefore needs the
option amount: trial reminder, retention offer, promo redemption,
analytics MRR, Plans current card. All handled behind
`local_currency.billed_in_option`, which is false unless the
subscription currency is in the approved table, so older Adaptive
Pricing conversions keep today's handling.
- Promo codes (#23299): `utils/promotion_redemption.py` compared
`minimum_amount` against the base USD amount. For an option-billed
subscription it now requires the minimum in that currency
(`minimum_amount_currency` or `restrictions.currency_options`) against
the option amount, and refuses a fixed `amount_off` coupon without an
amount in that currency. At Checkout, Stripe evaluates the code in the
session currency.
- Upgrade/interval change: `routers/payment.py` refused any target whose
`currency` differs from the subscription. It now accepts the same
multi-currency Price when it has the subscription's option and pins both
schedule phases to that currency. `price_for_currency(...,
allow_options=...)` only offers options when the current item itself is
option-billed, so legacy JPY subscribers (JPY-native prices) are
unaffected.
- Analytics: `utils/observability/subscription_events.py` emits
`mrr_cents` only for USD; an option-billed subscription now reports its
own currency and no USD MRR. `backend/scripts/finops/pull_stripe.py`
still books by `price.currency` and would count an option subscription
at its base USD list price; not changed here (offline finops,
follow-up).
- Receipts/emails: Stripe sends them in the subscription currency.
`routers/users.py` legacy `price_string` is not rendered by the Flutter
app.

## Not handled (revenue reporting books local subscribers as USD)

These read the subscription item's Price (`currency`, `unit_amount`),
which is the base USD Price for a subscription billed through a currency
option, so a £/¥ subscriber is counted as US$29.99 / US$269.91 and never
in a non-USD bucket. Left for a follow-up; they should read
`subscription.currency` and, when it differs, the Price's
`currency_options[subscription.currency]`:

- `backend/scripts/finops/pull_stripe.py:123-126` (`monthly_amount`) and
`:313-333` (`currency = p.get("currency")`, `mrr_usd`), feeding
`contracts/product-telemetry/bigquery/plan-revenue-mrr.sql`.
- `web/admin/lib/stripe-subscriptions.ts:105-132` (`monthlyAmount`,
`isNonUsd` on the item price) and `:318-349` (wall metrics, FX by item
currency).
- `web/admin/app/api/omi/subscriptions/route.ts:93-96` (item price
amount and currency).

Handled here: `backend/utils/observability/subscription_events.py` emits
no USD `mrr_cents` and the subscription's own currency whenever the
subscription currency differs from its item Price.

## Money-safety review (changed lines near price selection, checkout and
entitlement)

- `backend/utils/local_currency.py` (new): `offer_for`,
`approved_amount` (Stripe option must equal the table),
`billed_in_option`, `option_amount_for`, `checkout_locale`,
`display_money`.
- `backend/utils/stripe.py` `create_subscription_checkout_session`: new
`local_currency_code`; retrieves with options, raises
`ValueError('local_currency_unavailable')` when the Price lacks that
option (the router decided approval or customer currency), sets
`currency`, `locale`, trial terms amount, "All amounts are in". USD path
unchanged.
- Review round 1: `billed_option_amount` / `OptionLookupFailed` /
`UNKNOWN_CURRENCY` (Stripe-only subscriber currency), `buyer_currency` /
`new_buyer_offer` / `customer_currency` (customer currency first),
`cached_price_with_options` (5-minute cache for the new-buyer and
subscriber gates; Checkout re-reads live).
- `backend/routers/payment.py`: `CreateCheckoutRequest.currency`;
`_new_buyer_checkout_currency` (same rule as the offer pages, read live)
and the displayed-currency check before session creation (400 when the
currency the app showed differs from the one the server would charge;
503 on Stripe read failure); `checkout_options['local_currency_code']`
only when local. Available plans: `billed_in_option`, `allow_options`,
new-buyer localize (USD otherwise). Upgrade: option-currency gate and
schedule `currency`. Trial-will-end webhook: Stripe read moved to
`stripe_executor` for option-billed trials only.
- `backend/utils/billing_currency.py`
`price_for_currency(allow_options=...)`.
- `backend/routers/storefront.py`: new-buyer sheet via `new_buyer_offer`
(USD otherwise); `_subscription_billing_currency` reads the subscription
currency (cached 30 days, it never changes) only once the current Price
carries a non-USD option, and returns `UNKNOWN_CURRENCY` on a read
failure so the current card shows no price.
- `backend/utils/storefront.py`: `offer_currency`/`money` threading;
`build_single_plan_storefront(local_currency_code=...)` returns None
when any price lacks its option.
- `backend/utils/promotion_redemption.py`, `utils/retention_offer.py`,
`utils/trial_reminder.py`, `utils/observability/subscription_events.py`:
option-billed branches.
- No entitlement code changed: plan identity, price-ID → plan mapping
and `config/plan_catalog.json` are untouched; the same Price IDs are
sold.
- App: `createCheckoutSession(currency:)` sends the currency the reader
saw from every paywall and the Plans sheet.

## First-rollout price table (#26074's 53 countries, now committed as
part of the prod table)

Loaded through `utils.local_currency.load_table()` from
`~/mobile-ux-agent/runs/2026-11-22/play/storefront_local_currency_table.first_rollout.json`:
53 countries, 33 currencies (INR, ARS, TRY, NGN, EGP, PKR, UAH, BDT, KES
and Iceland removed), **0 entries dropped**
(`scripts/local_currency_options.py` `dropped_entries`). Display strings
are `display_money`, identical to the app and the Checkout render (NBSP
after letter codes):

| Currency | Countries | Monthly | Annual | Stripe minor units (monthly
/ annual) |
|---|---|---|---|---|
| AED | AE | AED 109.99 | AED 990.99 | 10999 / 99099 |
| AUD | AU | A$44.99 | A$406.99 | 4499 / 40699 |
| BRL | BR | R$177.99 | R$1,600.00 | 17799 / 160000 |
| CAD | CA | CA$42.99 | CA$386.99 | 4299 / 38699 |
| CHF | CH | CHF 24.99 | CHF 226.99 | 2499 / 22699 |
| CLP | CL | CLP 30,500 | CLP 275,000 | 30500 / 275000 |
| COP | CO | COP 105,000.00 | COP 930,000.00 | 10500000 / 93000000 |
| CZK | CZ | CZK 667.99 | CZK 6,000.00 | 66799 / 600000 |
| DKK | DK | DKK 203.99 | DKK 1,850.00 | 20399 / 185000 |
| EUR | AT BE BG CY DE EE ES FI FR GR HR IE IT LT LU LV MT NL PT SI SK |
€26.99 | €245.99 | 2699 / 24599 |
| GBP | GB | £22.99 | £205.99 | 2299 / 20599 |
| HKD | HK | HK$234.99 | HK$2,100.00 | 23499 / 210000 |
| HUF | HU | HUF 10,000.00 | HUF 92,000.00 | 1000000 / 9200000 |
| IDR | ID | IDR 550,000.00 | IDR 4,950,000.00 | 55000000 / 495000000 |
| ILS | IL | ₪100.99 | ₪904.99 | 10099 / 90499 |
| JPY | JP | ¥4,750 | ¥43,000 | 4750 / 43000 |
| KRW | KR | ₩40,500 | ₩365,000 | 40500 / 365000 |
| MXN | MX | MX$572.99 | MX$5,150.00 | 57299 / 515000 |
| MYR | MY | MYR 122.99 | MYR 1,100.00 | 12299 / 110000 |
| NOK | NO | NOK 291.99 | NOK 2,650.00 | 29199 / 265000 |
| NZD | NZ | NZ$54.99 | NZ$492.99 | 5499 / 49299 |
| PEN | PE | PEN 102.99 | PEN 928.99 | 10299 / 92899 |
| PHP | PH | ₱1,900.00 | ₱17,000.00 | 190000 / 1700000 |
| PLN | PL | PLN 121.99 | PLN 1,100.00 | 12199 / 110000 |
| QAR | QA | QAR 108.99 | QAR 981.99 | 10899 / 98199 |
| RON | RO | RON 145.99 | RON 1,300.00 | 14599 / 130000 |
| SAR | SA | SAR 111.99 | SAR 1,000.00 | 11199 / 100000 |
| SEK | SE | SEK 306.99 | SEK 2,750.00 | 30699 / 275000 |
| SGD | SG | SGD 38.99 | SGD 347.99 | 3899 / 34799 |
| THB | TH | THB 1,000.00 | THB 9,150.00 | 100000 / 915000 |
| TWD | TW | NT$990.00 | NT$8,900.00 | 99000 / 890000 |
| VND | VN | ₫775,000 | ₫6,950,000 | 775000 / 6950000 |
| ZAR | ZA | ZAR 524.99 | ZAR 4,750.00 | 52499 / 475000 |

### Dry run of the Stripe write (no `--apply`; nothing sent)

```
cd backend && STRIPE_UNLIMITED_V2_MONTHLY_PRICE_ID=price_1TuIa81F8wnoWYvw0iX0j5M8 STRIPE_UNLIMITED_V2_ANNUAL_PRICE_ID=price_1TuIap1F8wnoWYvwHWq0EvNU \
  python scripts/local_currency_options.py --table storefront_local_currency_table.first_rollout.json
```

Offline, no key, prints `dropped entries: none`. It would make exactly
these two calls, adding 33 currencies to each Price:

```
stripe.Price.modify('price_1TuIa81F8wnoWYvw0iX0j5M8', currency_options={"aed":{"unit_amount":10999},"aud":{"unit_amount":4499},"brl":{"unit_amount":17799},"cad":{"unit_amount":4299},"chf":{"unit_amount":2499},"clp":{"unit_amount":30500},"cop":{"unit_amount":10500000},"czk":{"unit_amount":66799},"dkk":{"unit_amount":20399},"eur":{"unit_amount":2699},"gbp":{"unit_amount":2299},"hkd":{"unit_amount":23499},"huf":{"unit_amount":1000000},"idr":{"unit_amount":55000000},"ils":{"unit_amount":10099},"jpy":{"unit_amount":4750},"krw":{"unit_amount":40500},"mxn":{"unit_amount":57299},"myr":{"unit_amount":12299},"nok":{"unit_amount":29199},"nzd":{"unit_amount":5499},"pen":{"unit_amount":10299},"php":{"unit_amount":190000},"pln":{"unit_amount":12199},"qar":{"unit_amount":10899},"ron":{"unit_amount":14599},"sar":{"unit_amount":11199},"sek":{"unit_amount":30699},"sgd":{"unit_amount":3899},"thb":{"unit_amount":100000},"twd":{"unit_amount":99000},"vnd":{"unit_amount":775000},"zar":{"unit_amount":52499}})
stripe.Price.modify('price_1TuIap1F8wnoWYvwHWq0EvNU', currency_options={"aed":{"unit_amount":99099},"aud":{"unit_amount":40699},"brl":{"unit_amount":160000},"cad":{"unit_amount":38699},"chf":{"unit_amount":22699},"clp":{"unit_amount":275000},"cop":{"unit_amount":93000000},"czk":{"unit_amount":600000},"dkk":{"unit_amount":185000},"eur":{"unit_amount":24599},"gbp":{"unit_amount":20599},"hkd":{"unit_amount":210000},"huf":{"unit_amount":9200000},"idr":{"unit_amount":495000000},"ils":{"unit_amount":90499},"jpy":{"unit_amount":43000},"krw":{"unit_amount":365000},"mxn":{"unit_amount":515000},"myr":{"unit_amount":110000},"nok":{"unit_amount":265000},"nzd":{"unit_amount":49299},"pen":{"unit_amount":92899},"php":{"unit_amount":1700000},"pln":{"unit_amount":110000},"qar":{"unit_amount":98199},"ron":{"unit_amount":130000},"sar":{"unit_amount":100000},"sek":{"unit_amount":275000},"sgd":{"unit_amount":34799},"thb":{"unit_amount":915000},"twd":{"unit_amount":890000},"vnd":{"unit_amount":6950000},"zar":{"unit_amount":475000}})
```

Operator sequence (parent runs it; read-only first):

1. `STRIPE_READ_API_KEY=<read key> python
scripts/local_currency_options.py --count-non-usd-subscriptions` counts
live (active, trialing, past_due, unpaid, paused) subscriptions on the
two Prices whose currency is not USD, by currency (older Adaptive
Pricing conversions; a manual option overrides Adaptive Pricing for that
currency).
2. `STRIPE_API_KEY=<write key> python scripts/local_currency_options.py
--table <file> --apply --confirm` reads both Prices with
`expand=currency_options`, prints the existing options, and exits 2
before any write if the table dropped an entry or a table currency
already exists on a Price with a different amount; otherwise it adds
only the missing currencies.

## Earlier proposed price table (superseded by the table above)

Omi Pro is US$29.99/month and US$269.91/year (9 × monthly). Rates:
open.er-api.com, 2026-11-23 00:02 UTC. Converted, then rounded to Play's
local price patterns (x.99; JPY to ¥100; MXN to whole pesos ending in
9), with annual = 9 × local monthly re-rounded so the yearly saving
stays "3 months free". The JPY row equals the existing JPY Omi Pro
management prices (¥4,800 / ¥43,200). Play's own template prices include
VAT/GST where prices are tax-inclusive (EU, GB, AU, JP); Stripe Checkout
here collects no tax, so these are tax-exclusive like the US price.
Nothing below is in the default config.

| Countries (top non-US Android upgraders, 30 d) | Currency | Rate per
US$ | Monthly | Annual | Table entry (minor units) |
|---|---|---|---|---|---|
| JP (34) | JPY | 158.70 | ¥4,800 | ¥43,200 | `"jpy": {"monthly": 4800,
"annual": 43200}` |
| GB (29) | GBP | 0.7636 | £22.99 | £206.99 | `"gbp": {"monthly": 2299,
"annual": 20699}` |
| AU (21) | AUD | 1.5070 | A$44.99 | A$404.99 | `"aud": {"monthly":
4499, "annual": 40499}` |
| CA (20) | CAD | 1.4332 | CA$42.99 | CA$386.99 | `"cad": {"monthly":
4299, "annual": 38699}` |
| MX (15) | MXN | 19.113 | MX$569.00 | MX$5,119.00 | `"mxn": {"monthly":
56900, "annual": 511900}` |
| AE (12) | AED | 3.6725 | AED 109.99 | AED 989.99 | `"aed": {"monthly":
10999, "annual": 98999}` |
| ES (10), NL (9), DE (8), other euro countries | EUR | 0.9111 | €26.99
| €242.99 | `"eur": {"monthly": 2699, "annual": 24299}` |
| BR (7) | BRL | 5.9453 | R$177.99 | R$1,601.99 | `"brl": {"monthly":
17799, "annual": 160199}` |

## Verification (this revival, on main @ `0736f7075d0`)

- Backend: `bash test.sh` on the 73 billing-related unit files (payment,
checkout, storefront, Stripe, promotion, retention, trial reminder, Play
Billing, currency, subscription events and more) under `omi-heavy`: all
pass except, at first,
`test_local_currency_offer.py::test_checkout_currency_equals_the_displayed_currency`.
Main's checkout now calls `play_subscriptions_db.is_play_customer`,
which the PR's helper did not stub. After the stub, the file passes 48
of 48.
- App: `flutter analyze` on every changed Dart file: no issues. `flutter
test` on the billing, paywall, Plans sheet, storefront and Play Billing
tests: all pass after one fix. Main's
`play_billing_plans_sheet_test.dart` fake `createUserCheckoutSession`
lacked the new `currency` parameter and did not compile; that test now
passes 92 of 92.
- Local manifest checks (`run_checks.py --lane local --base
origin/main`): all pass except two.
- `checkout-currency-format` needs Node 22.22.0 with ICU 77.1. This host
has 22.23.2 with ICU 78.2. Rerun with the checksum-verified pinned Node:
`--check` passes.
- `feature-flag-registry` blamed this PR for
`LADDER_V1_PRO_GATES_ENABLED`'s overdue deadline because of a checker
bug. Adding `REGION_HEADER` to `routers/storefront.py` made the checker
count that file's unchanged LADDER read as new. **This branch carries
the fix commit (`fix(flags): count a Python flag read as added only when
the base file did not read it`), which is also its own PR,
`fix/flag-registry-base-scan-gate`.** Whichever merges second picks it
up from main. With the fix: `feature-flag registry: OK`.
- The original PR's verification and its iOS simulator evidence follow.


- Backend: `bash test.sh` on the 22 touched/related suites (payment,
checkout trial, promo/adaptive pricing, currency changes, JPY
recognition, storefront x3, trial reminder, retention, promo redemption,
yearly switch, billing events, available plans, users subscription
boundary, referral checkout) plus the new
`tests/unit/test_local_currency_offer.py` (48 tests): all pass. New
tests cover: switch off / empty / malformed table byte-identical
(available plans, v2 sheet, users subscription); JP, GB, DE paths;
country outside the table keeps USD on Android and iOS; table currency
missing from the Price falls back to USD and logs; old app (no region);
US and USD-country buyers; Stripe option missing or not equal to the
table; checkout currency equals displayed currency and refuses a
mismatch; table validation for zero-decimal and whole-hundreds
currencies; every Stripe currency's display string; a local trial keeps
its currency through Checkout, an in-trial interval change and the
reminder; cart currency, locale, adaptive pricing off and trial line;
promo minimum and amount-off in GBP; yearly switch refusal in GBP;
retention offer in GBP; local subscriber available plans + interval
change with schedule `currency`; local subscriber Plans card; legacy JPY
subscriber sheet unchanged; dry-run script prints and never writes;
review round 1: rollback with switch off and empty table keeps a GBP
subscriber in GBP on available plans, the Plans card, the retention
offer, the trial push and promo redemption (and shows no price when
Stripe is unreadable); a lapsed USD customer in GB stays USD on the page
and at Checkout; a lapsed GBP customer in the US gets GBP with the
switch on and off; a customer currency the Prices lack keeps USD;
USD-only promo minimum compared with the USD Price; `--apply` needs
`--confirm`, prints existing options, refuses a different amount or
dropped entries before writing and adds only missing currencies;
read-only non-USD subscription count; released currencies unchanged with
the switch off.
- Pyright on the touched backend modules: 0 errors (it caught a variable
collision in `build_storefront` during development).
- App: `flutter test` full suite (10,045 passed; the two visual-audit
files failed to compile on a missed fake and pass after the fix;
`capture_cold_mute_test` failed once under load and passes alone), new
`test/unit/local_currency_price_test.dart`, `flutter analyze` on changed
files (one pre-existing info).
- Simulator (iOS, pipeline lane `sim`, local backend + Stripe stub with
a GBP option, switch `all` because the simulator is iOS):

| | Trial paywall | Plans |
|---|---|---|
| US, switch on (unchanged) |
![](https://raw.githubusercontent.com/BasedHardware/omi/efd9e05157e7e88bafe88d5e7656478befaecb46/.agent-artifacts/ui-evidence/play-local-currency-storefront/001-mobile-ios-trial-paywall-us-switch-on.png)
|
![](https://raw.githubusercontent.com/BasedHardware/omi/efd9e05157e7e88bafe88d5e7656478befaecb46/.agent-artifacts/ui-evidence/play-local-currency-storefront/002-mobile-ios-plans-us-switch-on.png)
|
| GB, switch off (today) |
![](https://raw.githubusercontent.com/BasedHardware/omi/efd9e05157e7e88bafe88d5e7656478befaecb46/.agent-artifacts/ui-evidence/play-local-currency-storefront/003-mobile-ios-trial-paywall-gb-switch-off.png)
|
![](https://raw.githubusercontent.com/BasedHardware/omi/efd9e05157e7e88bafe88d5e7656478befaecb46/.agent-artifacts/ui-evidence/play-local-currency-storefront/004-mobile-ios-plans-gb-switch-off.png)
|
| GB, switch on (£22.99 / £206.99 approved) |
![](https://raw.githubusercontent.com/BasedHardware/omi/efd9e05157e7e88bafe88d5e7656478befaecb46/.agent-artifacts/ui-evidence/play-local-currency-storefront/005-mobile-ios-trial-paywall-gb-switch-on.png)
|
![](https://raw.githubusercontent.com/BasedHardware/omi/efd9e05157e7e88bafe88d5e7656478befaecb46/.agent-artifacts/ui-evidence/play-local-currency-storefront/006-mobile-ios-plans-gb-switch-on.png)
|

## UNVERIFIED

- The display strings are ICU's render at the pinned locale, the engine
Checkout's browser formatter uses, not a live Checkout page: creating a
session writes to Stripe. A browser on an older ICU could differ in rare
symbols. Check one test-mode session per table currency before turning
the switch on.
- Whether Google's reviewer device locale names their country. If their
device reports `en-US`, they still see USD (as Play would for a US
account). An LB `X-Client-Region` header would remove that dependency.
- Android build not run on a device or emulator here; the iOS simulator
exercises the same Dart paths.
- Trial conversion and renewal in the local currency rest on Stripe's
rule that a subscription's currency is fixed at creation and every
invoice bills that currency's option of the item Price. The tests prove
Checkout creates the trial in the local currency and that no later path
(interval change during the trial, schedule, upgrade) changes it; they
cannot run Stripe's invoicing.
- Stripe accepting `currency` on SubscriptionSchedule phases for an
option-billed subscription is from the API reference, exercised only
against fakes.
- That Stripe refuses a Checkout whose currency differs from the
customer's `currency`, and that `Customer.currency` is set after a
trial-only subscription, are from the API reference; the
customer-currency rule avoids both cases but was not run against Stripe.
- A new buyer entering a USD-minimum or USD `amount_off` code in a
local-currency Checkout: Stripe evaluates it in the session currency and
may refuse it there. The in-app path for bundle and prepaid codes is
redemption after the trial starts (`promotion_redemption.py`, handled
above); list the live codes' `restrictions` read-only before turning on.
- Whether existing `currency_options` can be edited or removed after
`--apply` (the docs disagree); the script never edits one, and the
5-minute cache assumes they do not change.

- **Reviewer region (the risk that matters most for Play).** Since panel
F1, the Android app sends **Google Play's billing country** for the
account (`InAppPurchasePlatform.countryCode`), read before a price
screen loads. If Play doesn't answer within 3 s, the app sends **no
region**, so the buyer gets today's USD; it never guesses from the
locale. The next price screen retries. This matches the market Play
itself prices the reviewer in, even when the phone's locale names
another country. The table leaves out INR, PKR, EGP, NGN, ARS, TRY, UAH,
BDT, KES and ISK. A reviewer whose Play country is one of those still
sees US$. This PR is as written at David's request; widening the table
is a follow-up decision.
- **Play Payments policy.** Selling a digital subscription through
Stripe in the Android app, without an alternative-billing program, is a
separate Play Payments exposure (#25494, #26078). Google has not cited
it so far. Play Billing (#26826) remains the fallback.

## Line-count exceptions

Line-Count-Exception: backend/routers/payment.py | 2546 -> 2648 | the
checkout currency check and available-plans localization sit on the
routes that create Checkout; the decision logic itself lives in
utils/local_currency.py
Line-Count-Exception: backend/routers/users.py | 2923 -> 2945 |
/v1/users/me/subscription must localize its own price strings for the
same buyer

## Product invariants affected

- INV-MEM-4: cited because `backend/deploy/runtime_env.yaml` is a locked
path for it. This PR adds only two billing settings to the prod backend
service (`STOREFRONT_LOCAL_CURRENCY`, `STOREFRONT_LOCAL_CURRENCY_TABLE`)
and changes no memory intake, consolidation or promotion setting.

## Failure class (fixes)

Failure-Class: FC-subscription-price-presentment-drift

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mux-proposal Mobile UX improver (MUX) proposal; waits for Nik's ship

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant