21 — Stripe Live-Mode Switchover Playbook
The step-by-step operational playbook for moving the running LynCareOS production environment from Stripe Sandbox/Test mode to Stripe Live mode so the first paying customer can complete a real transaction.
This doc does not re-explain the pricing model — that lives in 18-STRIPE-GLOBAL-PRICING.md. This is the switchover runbook: pre-flight, the flip, verification, and rollback.
Audience: The operator/founder, running this sequence on the
production host (repo root, e.g. D:\Projects\LynCareOS, with
docker compose --env-file .env.production --profile production). Assumes the stack in
20-PRODUCTION-DEPLOYMENT-GUIDE.md
is already deployed.
Version: 1.8
Last Updated: 2026-06-04
Production status (2026-05-27): Live Stripe keys are on the VPS. The live
catalog holds three tier Products only (Essential, Family, Complete), each
with seven fixed local-currency Prices (USD, AUD, NZD, GBP, EUR, CAD, INR).
Non-tier Products (à la carte modules, condition packs, extra-person add-ons)
were archived via stripe_archive_non_tier_catalog. In-app billing is
tier-plans-only (BILLING_TIER_PLANS_ONLY defaults to true when
ENVIRONMENT=production). Care Profile product spec: Palliative Care Archetypes.md v2.0. Paid pack checkout stays 503 until §4.1b checklist is signed off.
1. Why this is its own document
Section titled “1. Why this is its own document”Doc 18 §3.4 describes the Stripe-side steps (“toggle live mode, copy the new keys, rerun the seeder”). On the production host, the switch-over is a production change event with:
- A user-visible brownout window (Stripe-related endpoints return 5xx between key swap and backend restart).
- Webhook re-registration that can silently misroute events if
APP_PUBLIC_URLis wrong. - Price-ID drift between Stripe catalogue and the
stripe_tiersmirror table that, if unnoticed, will cause400 Unknown or unseeded tierat Checkout. - A new live
whsec_secret that Stripe shows only once.
All of that needs a runbook.
2. Pre-flight — do this at least 48 h before the flip
Section titled “2. Pre-flight — do this at least 48 h before the flip”Each item is independent. Tick them off in any order.
2.1 Business & compliance
Section titled “2.1 Business & compliance”- Stripe business details complete and verified. Dashboard → Business settings. The ABN/EIN, bank account, statement descriptor, refund policy, support email, and URL must all be in place. Live mode refuses to accept charges until Stripe has verified.
- Bank account has completed a test deposit (Stripe does a ~$0.01 verify-deposit + withdraw on first linkage).
- Terms of Service + Privacy Policy URLs configured on the dashboard and cited by the Checkout page (Stripe will refuse certain card networks if these are absent).
- Adaptive Pricing currencies re-confirmed (Settings → Currencies → Adaptive Pricing). Same list as test mode.
- Customer statement descriptor set to something users will
recognise (e.g.
LYNCAREOS.COM).
2.2 Backup & safety
Section titled “2.2 Backup & safety”-
Copy the Postgres volume or take a full host backup (Veeam, Windows image, or your standard) before the flip.
-
Run a fresh
pg_dumpto the repobackups\folder and copy the file off-box:```powershellcd D:\Projects\LynCareOSdocker compose --env-file .env.production --profile production exec -T postgres `pg_dump -U lyncare -d lyncareos -Fc -f /tmp/pre_stripe_live.dumpdocker compose --env-file .env.production cp "postgres:/tmp/pre_stripe_live.dump" `"D:\Projects\LynCareOS\backups\pre_stripe_live.dump"``` -
Verify the
stripe_tiersmirror matchestiers.jsonin test mode — if they disagree now, they will still disagree after the flip:```bashdocker compose --env-file .env.production --profile production \exec postgres \psql -U lyncare -d lyncareos -c \"SELECT slug, stripe_price_id, usd_cents, activeFROM stripe_tiers ORDER BY usd_cents;"```Expect three rows, all `active = t`, `stripe_price_id` populatedwith **`price_…` test IDs**.
2.3 Observability prepped
Section titled “2.3 Observability prepped”-
Open the Stripe dashboard, Live mode in one browser tab — Developers → Events, Developers → Webhooks, Payments, Customers. You will watch these live during the flip.
-
Tail app logs on the production host:
```powershellcd D:\Projects\LynCareOSdocker compose --env-file .env.production --profile production logs -f --tail=200 app``` -
Announce the change window to pilot users. Expected impact: the signup flow and Billing Portal will be unavailable for approximately 5 minutes. Existing in-app actions (login, dispensings, patient data) are unaffected.
2.4 Communicate the window
Section titled “2.4 Communicate the window”Template (put in your channel of choice):
LynCareOS will swap to Stripe live mode at 10:00 AEST. Expected impact: no one can start a new subscription or open the Billing Portal for ~5 minutes. Existing users can keep using the app.
2.5 PHI encryption readiness (B4 — REQUIRED before first live signup)
Section titled “2.5 PHI encryption readiness (B4 — REQUIRED before first live signup)”Operator review (2026-05-22): Re-read this section after any change to
backend/services/stripe_provisioning.py,signup_service.py, or invitation/register paths. The table below must match the code before flippingsk_live_. Production VPS already has V089–V092 applied and PHI keys pinned — tick items you re-verify after the next deploy.
All users and tenants created through the Stripe provisioning flow — including the owner registered at Checkout and every carer or observer subsequently invited to their care group — must have their identity fields encrypted at rest before a live payment is accepted.
Production VPS (2026-05-22): Backfill complete, V090–V091 applied, PHI_* keys pinned via .\scripts\production-phi-pin.ps1. Re-run verification below after any deploy or SECRET_KEY rotation.
-
PHI_ENCRYPTION_KEYandPHI_BLIND_INDEX_KEYare set on VPS.env.production(pinned 2026-05-22). Verify after restart:Terminal window docker compose --env-file .env.production --profile production \exec app python -c "from config import settings; print('phi_key_len:', len(settings.PHI_ENCRYPTION_KEY))"Expect a non-zero length. If zero, the app is falling back to HKDF derivation from
SECRET_KEY— acceptable for dev; not acceptable before first live payment because the key is not independently rotatable. -
V089 migration applied (production 2026-05-22) —
tenants.name_encandtenants.enc_versioncolumns exist:SELECT column_name FROM information_schema.columnsWHERE table_name = 'tenants' AND column_name = 'name_enc'; -
Backfill script run and verified (production 2026-05-22) — all four checks must return
0:SELECT COUNT(*) FROM patients WHERE enc_version < 1;SELECT COUNT(*) FROM users WHERE enc_version < 1;SELECT COUNT(*) FROM care_groups WHERE enc_version < 1;SELECT COUNT(*) FROM tenants WHERE enc_version < 1;Run the backfill if needed (idempotent):
Terminal window docker compose --env-file .env.production --profile production \exec app python -m migrations.scripts.encrypt_phi_fields -
V090 constraints applied (production 2026-05-22) —
UNIQUE INDEX ON users(email_idx);NOT NULLon*_enccolumns. -
V091 plaintext drop applied (production 2026-05-22) — identity plaintext columns removed; login uses
email_idxonly.
Scope of encryption in the signup and invitation flow:
| Path | Fields encrypted on write |
|---|---|
New subscriber (Checkout webhook → stripe_provisioning.py) | users.email_enc, users.email_idx, users.enc_version=1; tenants.name_enc, tenants.enc_version=1 |
Google signup (marketing GIS → google_auth_service.py) | Same as above |
Manual /api/auth/register | users.email_enc, users.email_idx, users.enc_version=1 |
Invited carer or observer (accepts token → /api/auth/register) | users.email_enc, users.email_idx, users.enc_version=1 — invitation token lookup uses email_idx blind index |
| Patient created by admin | patients.full_name_enc, patients.date_of_birth_enc, patients.enc_version=1 |
| Care group created (auto-default or manual) | care_groups.name_enc, care_groups.enc_version=1 |
| Login (all flows) | Lookups use email_idx blind index only (post-V091) |
The invited carer or observer does not hold an encryption key themselves — the platform KEK (PHI_ENCRYPTION_KEY) decrypts identity fields on the server before returning them to any authenticated request that passes require_tenant_member. Access control (admin / carer / observer roles + patient_access grants) determines what each user can see; the encryption prevents the platform operator from reading identities at the database level.
3. The flip — sequential, ≈ 5 minutes
Section titled “3. The flip — sequential, ≈ 5 minutes”Do these steps in order, on the production host (PowerShell).
3.1 Generate live API keys in Stripe
Section titled “3.1 Generate live API keys in Stripe”- Stripe dashboard → toggle from Test → Live (top-right).
- Developers → API keys.
- Reveal the Secret key (
sk_live_…) — copy it now, this is the only time Stripe shows it in full. - Copy the Publishable key (
pk_live_…).
3.2 Update .env.production on the production host
Section titled “3.2 Update .env.production on the production host”Edit .env.production in the repo root (e.g. with your editor). Do not commit secrets.
Make these three edits:
STRIPE_SECRET_KEY=sk_test_51...STRIPE_SECRET_KEY=sk_live_51...
STRIPE_PUBLISHABLE_KEY=pk_test_51...STRIPE_PUBLISHABLE_KEY=pk_live_51...
STRIPE_WEBHOOK_SECRET=whsec_<test_secret>STRIPE_WEBHOOK_SECRET=Leave STRIPE_WEBHOOK_SECRET blank — the seeder in step 3.4
will create the live webhook endpoint and Stripe will show the
new signing secret.
Save. sudo chown root:docker .env.production && sudo chmod 640 .env.production.
3.3 Restart the app with the new live keys
Section titled “3.3 Restart the app with the new live keys”docker compose --env-file .env.production --profile production \ up -d --force-recreate appdocker compose --env-file .env.production --profile production \ logs --tail=40 appAt this point webhook signature verification is broken (the app
has STRIPE_WEBHOOK_SECRET=""). That is fine — we have not
received any live webhooks yet, and no live customers exist.
3.4 Run the tier seeder against live
Section titled “3.4 Run the tier seeder against live”docker compose --env-file .env.production --profile production \ exec app python -m scripts.stripe_seed_tiersRun only stripe_seed_tiers at launch. The live catalog is intentionally
limited to the three subscription tiers across seven currencies — extras
(à la carte modules, condition packs, extra-person add-ons) are not offered
until product packaging is finalised. Care Profile product spec (v2.0):
Palliative Care Archetypes.md.
Paid pack checkout remains 503 until §4.1b checklist is signed off.
Do not run
stripe_seed_module_pricesorstripe_seed_condition_packsin live mode until those packages are ready to sell. The app returns 503 for add-on purchase endpoints whenBILLING_TIER_PLANS_ONLY=true(production default).
If you previously seeded extras in live mode and need to clean up:
docker compose --env-file .env.production --profile production \ exec app python -m scripts.stripe_archive_non_tier_catalog --dry-run
docker compose --env-file .env.production --profile production \ exec app python -m scripts.stripe_archive_non_tier_catalogExpected output (truncated, with live IDs):
[seed] tier=essential usd=39 → product=prod_... price=price_... (active)[seed] tier=professional usd=69 → product=prod_... price=price_... (active)[seed] tier=complete usd=99 → product=prod_... price=price_... (active)[seed] webhook endpoint registered: we_...[seed] copy this into STRIPE_WEBHOOK_SECRET: whsec_...The seeder:
- Creates three new live Products + Prices (test/live are separate catalogues in Stripe — no data moves between them).
- Archives no test-mode data. Test-mode Products and Prices remain in test mode untouched; they are invisible to live-mode requests but still there if you need to fall back (§6).
- Writes the new live
stripe_price_idvalues intostripe_tiers(row-for-row replacing the test IDs — this is why step 2.2 matters, and why test-mode rollback means re-seeding with the test key). - Grandfathered subscriptions: customers who checked out on an older
Price id before a re-seed still bill that Price in Stripe. After
2026-05-30, module sync resolves those via Price metadata
lyncareos_tierwhen the id is absent fromstripe_tiers. Operators can still runpython -m scripts.resync_tenant_subscriptions <tenant_id>after deploy if modules were missing on first webhook. - Registers a live webhook endpoint at
{APP_PUBLIC_URL}/api/stripe/webhookand prints the newwhsec_….
3.5 Paste the live webhook secret and restart
Section titled “3.5 Paste the live webhook secret and restart”Copy the whsec_… value from the seeder output into
.env.production:
STRIPE_WEBHOOK_SECRET=STRIPE_WEBHOOK_SECRET=whsec_live_...Save, then:
docker compose --env-file .env.production --profile production \ up -d --force-recreate appTail the app logs and wait for Uvicorn running on http://0.0.0.0:8020.
4. Immediate verification — under 10 minutes
Section titled “4. Immediate verification — under 10 minutes”4.1 Tiers endpoint reports live IDs
Section titled “4.1 Tiers endpoint reports live IDs”docker compose --env-file .env.production --profile production \ exec app python -c "import urllib.request, jsonr = urllib.request.urlopen('http://127.0.0.1:8020/api/billing/tiers', timeout=5)data = json.loads(r.read())print('publishable prefix:', data['publishable_key'][:7])print('currency:', data['currency'])for t in data['tiers']: print(' -', t['slug'], t['stripe_price_id'])"Expect:
publishable prefix:→pk_live(notpk_test).- Three tiers with
price_…IDs that match the ones the seeder just printed.
4.1a Verify AUD local tier prices
Section titled “4.1a Verify AUD local tier prices”After seeding, confirm Essential/Family/Complete AUD amounts match 22-BILLING-PRICING-REFERENCE.md:
SELECT t.slug, lp.currency, lp.amount_cents, lp.stripe_price_id FROM stripe_tiers t JOIN stripe_tier_local_prices lp ON lp.tier_id = t.id WHERE lp.currency = 'AUD' ORDER BY lp.amount_cents;Expect: essential 5900, professional 9900, complete 14900 (cents).
4.1b Condition packs and à la carte modules (deferred at launch)
Section titled “4.1b Condition packs and à la carte modules (deferred at launch)”At tier-plans-only launch, skip pack and module price verification. Paid Care Profile purchase and à la carte module checkout return 503 in production until extras are finalised and re-seeded.
2026-06-04 (dev perf): GET /api/condition-packs now uses one cached Frankfurter rate for all price_display values (Subscriptions UI only). Does not change live Checkout line items, Stripe Price IDs, or this checklist — operator sign-off for pack sales is unchanged.
Before enabling paid packs in live, complete (human review):
- Catalogue reconciled in DB —
V007(production 2026-06-04, imagedeploy-20260604-1810) - Pack content seed —
V008+ patient columnsV009+ universal obsV010(production 2026-06-04) - Care Start apply —
POST …/care-start+ Add Person (demographics) on production app; archetype / Our care pattern UI withdrawn 2026-06-26 - Pricing in doc 22 matches
condition_packs.price_audon production (SELECT slug, price_aud FROM condition_packs WHERE is_active) - Counsel / product sign-off on Care Profile SKUs and Palliative Care Start bundle (REQ-CARE-START-01) — CRITICAL — see CARE-START-CLINICAL-SIGNOFF.md
- Palliative Care Start $24.99 Stripe line item + marketing signup UI (dev 2026-06-04)
- Register R2 automated audit PASS (C7) — CARE-START-REGISTER-R2-AUDIT.md; clinical sign-off (C1d) still required
When you are ready to sell extras:
- Run
stripe_seed_module_pricesand/orstripe_seed_condition_packsin live mode. - Set
BILLING_TIER_PLANS_ONLY=falsein.env.production(or remove the variable and rely on explicit opt-in). - Redeploy the app image that exposes the Subscriptions add-on UI.
- Verify pack purchase E2E on production with a real card (small SKU first).
Verification SQL (run only after pack seeding):
SELECT slug, price_aud, stripe_price_id FROM condition_packs WHERE price_aud > 0 ORDER BY price_aud;4.2 End-to-end live purchase with a real card
Section titled “4.2 End-to-end live purchase with a real card”Operator sign-off: Completed 2026-05-31 (tracked in 04-ROADMAP §1 Launch (A3)).
-
In an incognito window, open
https://lyncareos.com/?preview=<PREVIEW_SECRET>. -
Click Essential ($39/yr) → complete the signup modal (a fresh email, not one that already exists).
-
Pay with a real card. (Stripe test cards like
4242 4242 4242 4242are rejected in live mode — this is the correct behaviour, not a bug.) -
Confirm you land on
https://app.lyncareos.com/billing/successand the Welcome modal renders. If provisioning is slow, the page retries automatically; on failure it shows a plain-language message (charged vs not charged) — see 24 §11. -
In Stripe dashboard → Live → Payments, the transaction appears.
-
In Stripe dashboard → Live → Webhooks → the
whsec_…endpoint, thecheckout.session.completedevent shows a 200 response. -
Refund the transaction to yourself from the Stripe dashboard.
-
In the app DB, verify the tenant was provisioned with the right modules (use
email_idx/ blind index in production — example uses username for a disposable test account):SELECT t.id AS tenant_id, u.username, s.module, s.stripe_price_id, s.statusFROM users uJOIN tenant_memberships tm ON tm.user_id = u.id AND tm.role = 'admin'JOIN tenants t ON t.id = tm.tenant_idLEFT JOIN subscriptions s ON s.tenant_id = t.idWHERE u.username = '<test-username>'ORDER BY s.module;Expect
status = 'active'(ortrial) for every module in the purchased tier pertiers.json. Family (professional) must include at leastprescription_management,sleep_tracking,vitals_tracking,key_contacts,custom_observations, andfamily_helpamong shipped modules. -
If modules are missing but Stripe shows a paid subscription:
Terminal window docker compose --env-file .env.production --profile production \exec app python -m scripts.resync_tenant_subscriptions <tenant_id>Grep logs for
has no module/tier mapping— should not appear after the 2026-05-30 metadata fallback is deployed.
4.3 Webhook signature verification works
Section titled “4.3 Webhook signature verification works”In Stripe dashboard → Live → Webhooks → the whsec_… endpoint →
Send test event → customer.subscription.updated. Watch the app
logs:
INFO: 1.2.3.4 - "POST /api/stripe/webhook HTTP/1.1" 200A 400 here means STRIPE_WEBHOOK_SECRET in the env doesn’t match
what Stripe signed with — check for trailing whitespace or an
off-by-one copy error on the whsec_ value.
4.4 Error surface
Section titled “4.4 Error surface”Grep the last 10 minutes of app logs for 5xx:
docker compose --env-file .env.production --profile production \ logs --since 10m app 2>&1 | grep -E ' 5[0-9]{2} 'Expected: empty.
5. Post-flight — in the first 24 h
Section titled “5. Post-flight — in the first 24 h”-
Watch Stripe Live → Disputes and Failed payments each morning for the first week.
-
Confirm
stripe_webhook_eventsrows are being written for every live event:```sqlSELECT event_type, received_at, statusFROM stripe_webhook_eventsORDER BY received_at DESC LIMIT 10;``` -
Delete the test-mode webhook endpoint in the Stripe dashboard (Developers → Webhooks → Test mode). It no longer routes anywhere useful and only adds noise.
-
Archive the test-mode
STRIPE_WEBHOOK_SECRETin your secrets vault for completeness — you will need it again only if you ever roll back (§6). -
Doc 19 §1 executive snapshot reflects Stripe live mode (2026-05-27).
-
Doc 19 §7.2 — tier-plans-only billing scope documented (2026-05-27).
-
Subscriptions admin — tier-plans-only UI deployed (
deploy-20260527-tier-plans-only). -
Subscriptions plan card —
tier_resolutionmodule fallback + stale price-ID repair (deploy-20260527-tier-resolution-fix, 2026-05-27). -
After live flip, spot-check tenants that signed up in test mode: if
GET /api/billing/my-tiershowscurrent_tier: nullbefore fallback, run the SQL in 24 §5.3 or have the customer complete a fresh live checkout.
6. Rollback to test mode
Section titled “6. Rollback to test mode”You want this path only in two scenarios:
- Live transactions are failing for a Stripe-side reason (bank verification not complete, rejected business, fraud-flagged account) and you need to keep signups working until Stripe resolves.
- A code bug specifically affects the live path and will take
1 h to fix — cheaper to sandbox signups in the meantime.
6.1 Procedure
Section titled “6.1 Procedure”-
In
.env.production, restore the archived test keys:STRIPE_SECRET_KEY=sk_live_...STRIPE_SECRET_KEY=sk_test_...STRIPE_PUBLISHABLE_KEY=pk_live_...STRIPE_PUBLISHABLE_KEY=pk_test_...STRIPE_WEBHOOK_SECRET=whsec_live_...STRIPE_WEBHOOK_SECRET=whsec_test_... -
docker compose … up -d --force-recreate app. -
Re-run the test-mode tier seeder:
Terminal window docker compose --env-file .env.production --profile production \exec app python -m scripts.stripe_seed_tiersThis rewrites
stripe_tierswith test IDs again. Re-run module/pack seeders in test mode only if you need those catalogues for local UAT. -
Confirm
GET /api/billing/tiers→publishable_keystarts withpk_test.
6.2 What rollback does not undo
Section titled “6.2 What rollback does not undo”- Live customers who already signed up and paid are preserved in
Stripe. Their subscriptions continue to renew on live prices.
Their rows in
tenants/users/subscriptionsare unaffected. - However, the
subscriptions.stripe_price_idvalues for those users now point at live Price IDs, whilestripe_tiersholds test IDs. The app copes (provisioning readsstripe_tiersby tier slug, not bystripe_price_id), but any analytics joiningsubscriptions↔stripe_tiersonstripe_price_idwill produce misses. Prefer joining byslugor by atier_idonce introduced.
6.3 Re-flipping to live
Section titled “6.3 Re-flipping to live”Re-run §3 start-to-finish. The seeder is idempotent — the existing live Products are reused.
7. Troubleshooting
Section titled “7. Troubleshooting”| Symptom | Likely cause | Fix |
|---|---|---|
GET /api/billing/tiers returns publishable_key: "" | App can’t reach Stripe with the new key | Check STRIPE_SECRET_KEY in .env.production (trailing whitespace?); docker compose logs app for Stripe 401 |
| Checkout page loads but shows USD to all countries | Adaptive Pricing is off in live mode (it is a per-mode setting; enabling it in test mode does not flip live) | Dashboard → Live → Settings → Currencies → Adaptive Pricing → On |
| Webhook 400 “Invalid signature” on every event | STRIPE_WEBHOOK_SECRET in the env does not match the endpoint’s signing secret | Re-copy from dashboard → Developers → Webhooks → the live endpoint → Signing secret; restart app |
| Webhook 404 | APP_PUBLIC_URL in env is wrong or the live webhook endpoint points at the wrong URL | Confirm APP_PUBLIC_URL=https://app.lyncareos.com; dashboard → Developers → Webhooks → the endpoint URL must exactly equal {APP_PUBLIC_URL}/api/stripe/webhook |
400 Unknown or unseeded tier on Checkout | stripe_tiers still holds test-mode IDs, or tiers.json slug drifted | Re-run the seeder (§3.4) |
| Live payment succeeds but no tenant provisioned | Webhook delayed or failed; pending_signups row still pending while Stripe shows paid | Grep app logs for payment_outcome; check pending_signups by checkout_session_id; user can refresh /billing/success — complete-signup provisions inline when Stripe is paid. Replay webhook from Stripe dashboard if needed. |
User sees technical error on /billing/success | Old app build without structured payment outcomes | Deploy current app image; verify GET /api/stripe/checkout-outcome returns user_message + charged |
Real card rejected as generic_decline on first try | Stripe’s anti-fraud learned this account only ran test-mode before and flagged the first real card | Try a different card; if it persists, contact Stripe support — common with new accounts |
8. Cross-reference index
Section titled “8. Cross-reference index”| I need to… | Read |
|---|---|
| Understand the pricing model and Adaptive Pricing | 18-STRIPE-GLOBAL-PRICING.md |
| Change a price after live is enabled | 18-STRIPE-GLOBAL-PRICING.md §3.1 |
| See Stripe keys and billing flags in production | 04-ROADMAP §1.1 Secrets |
Tier-plans-only scope and BILLING_TIER_PLANS_ONLY | 24-SUBSCRIPTION-BILLING |
| Archive non-tier Stripe Products after accidental seed | backend/scripts/stripe_archive_non_tier_catalog.py |
| Payment failure UX and operator log grep | 24-SUBSCRIPTION-BILLING-AND-TIER-LIMITS.md §11 |
| Stand up the production environment from zero | 20-PRODUCTION-DEPLOYMENT-GUIDE.md |
| Run day-2 ops (logs, restarts, backups) | 07-PLATFORM-RUNBOOK.md |