Skip to content

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.


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_URL is wrong.
  • Price-ID drift between Stripe catalogue and the stripe_tiers mirror table that, if unnoticed, will cause 400 Unknown or unseeded tier at 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.

  • 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).
  • Copy the Postgres volume or take a full host backup (Veeam, Windows image, or your standard) before the flip.

  • Run a fresh pg_dump to the repo backups\ folder and copy the file off-box:

    ```powershell
    cd D:\Projects\LynCareOS
    docker compose --env-file .env.production --profile production exec -T postgres `
    pg_dump -U lyncare -d lyncareos -Fc -f /tmp/pre_stripe_live.dump
    docker compose --env-file .env.production cp "postgres:/tmp/pre_stripe_live.dump" `
    "D:\Projects\LynCareOS\backups\pre_stripe_live.dump"
    ```
  • Verify the stripe_tiers mirror matches tiers.json in test mode — if they disagree now, they will still disagree after the flip:

    ```bash
    docker compose --env-file .env.production --profile production \
    exec postgres \
    psql -U lyncare -d lyncareos -c \
    "SELECT slug, stripe_price_id, usd_cents, active
    FROM stripe_tiers ORDER BY usd_cents;"
    ```
    Expect three rows, all `active = t`, `stripe_price_id` populated
    with **`price_…` test IDs**.
  • 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:

    ```powershell
    cd D:\Projects\LynCareOS
    docker 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.

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 flipping sk_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_KEY and PHI_BLIND_INDEX_KEY are 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_enc and tenants.enc_version columns exist:

    SELECT column_name FROM information_schema.columns
    WHERE 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 NULL on *_enc columns.

  • V091 plaintext drop applied (production 2026-05-22) — identity plaintext columns removed; login uses email_idx only.

Scope of encryption in the signup and invitation flow:

PathFields 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/registerusers.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 adminpatients.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.


Do these steps in order, on the production host (PowerShell).

  1. Stripe dashboard → toggle from Test → Live (top-right).
  2. Developers → API keys.
  3. Reveal the Secret key (sk_live_…) — copy it now, this is the only time Stripe shows it in full.
  4. 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”
Terminal window
docker compose --env-file .env.production --profile production \
up -d --force-recreate app
docker compose --env-file .env.production --profile production \
logs --tail=40 app

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

Terminal window
docker compose --env-file .env.production --profile production \
exec app python -m scripts.stripe_seed_tiers

Run 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_prices or stripe_seed_condition_packs in live mode until those packages are ready to sell. The app returns 503 for add-on purchase endpoints when BILLING_TIER_PLANS_ONLY=true (production default).

If you previously seeded extras in live mode and need to clean up:

Terminal window
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_catalog

Expected 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_id values into stripe_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_tier when the id is absent from stripe_tiers. Operators can still run python -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/webhook and prints the new whsec_….

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:

Terminal window
docker compose --env-file .env.production --profile production \
up -d --force-recreate app

Tail 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”
Terminal window
docker compose --env-file .env.production --profile production \
exec app python -c "
import urllib.request, json
r = 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 (not pk_test).
  • Three tiers with price_… IDs that match the ones the seeder just printed.

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, image deploy-20260604-1810)
  • Pack content seed — V008 + patient columns V009 + universal obs V010 (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_aud on 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:

  1. Run stripe_seed_module_prices and/or stripe_seed_condition_packs in live mode.
  2. Set BILLING_TIER_PLANS_ONLY=false in .env.production (or remove the variable and rely on explicit opt-in).
  3. Redeploy the app image that exposes the Subscriptions add-on UI.
  4. 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)).

  1. In an incognito window, open https://lyncareos.com/?preview=<PREVIEW_SECRET>.

  2. Click Essential ($39/yr) → complete the signup modal (a fresh email, not one that already exists).

  3. Pay with a real card. (Stripe test cards like 4242 4242 4242 4242 are rejected in live mode — this is the correct behaviour, not a bug.)

  4. Confirm you land on https://app.lyncareos.com/billing/success and 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.

  5. In Stripe dashboard → Live → Payments, the transaction appears.

  6. In Stripe dashboard → Live → Webhooks → the whsec_… endpoint, the checkout.session.completed event shows a 200 response.

  7. Refund the transaction to yourself from the Stripe dashboard.

  8. 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.status
    FROM users u
    JOIN tenant_memberships tm ON tm.user_id = u.id AND tm.role = 'admin'
    JOIN tenants t ON t.id = tm.tenant_id
    LEFT JOIN subscriptions s ON s.tenant_id = t.id
    WHERE u.username = '<test-username>'
    ORDER BY s.module;

    Expect status = 'active' (or trial) for every module in the purchased tier per tiers.json. Family (professional) must include at least prescription_management, sleep_tracking, vitals_tracking, key_contacts, custom_observations, and family_help among shipped modules.

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

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" 200

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

Grep the last 10 minutes of app logs for 5xx:

Terminal window
docker compose --env-file .env.production --profile production \
logs --since 10m app 2>&1 | grep -E ' 5[0-9]{2} '

Expected: empty.


  • Watch Stripe Live → Disputes and Failed payments each morning for the first week.

  • Confirm stripe_webhook_events rows are being written for every live event:

    ```sql
    SELECT event_type, received_at, status
    FROM stripe_webhook_events
    ORDER 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_SECRET in 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_resolution module 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-tier shows current_tier: null before fallback, run the SQL in 24 §5.3 or have the customer complete a fresh live checkout.


You want this path only in two scenarios:

  1. 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.
  2. A code bug specifically affects the live path and will take

    1 h to fix — cheaper to sandbox signups in the meantime.

  1. 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_...
  2. docker compose … up -d --force-recreate app.

  3. Re-run the test-mode tier seeder:

    Terminal window
    docker compose --env-file .env.production --profile production \
    exec app python -m scripts.stripe_seed_tiers

    This rewrites stripe_tiers with test IDs again. Re-run module/pack seeders in test mode only if you need those catalogues for local UAT.

  4. Confirm GET /api/billing/tiers → publishable_key starts with pk_test.

  • 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 / subscriptions are unaffected.
  • However, the subscriptions.stripe_price_id values for those users now point at live Price IDs, while stripe_tiers holds test IDs. The app copes (provisioning reads stripe_tiers by tier slug, not by stripe_price_id), but any analytics joining subscriptions ↔ stripe_tiers on stripe_price_id will produce misses. Prefer joining by slug or by a tier_id once introduced.

Re-run §3 start-to-finish. The seeder is idempotent — the existing live Products are reused.


SymptomLikely causeFix
GET /api/billing/tiers returns publishable_key: ""App can’t reach Stripe with the new keyCheck STRIPE_SECRET_KEY in .env.production (trailing whitespace?); docker compose logs app for Stripe 401
Checkout page loads but shows USD to all countriesAdaptive 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 eventSTRIPE_WEBHOOK_SECRET in the env does not match the endpoint’s signing secretRe-copy from dashboard → Developers → Webhooks → the live endpoint → Signing secret; restart app
Webhook 404APP_PUBLIC_URL in env is wrong or the live webhook endpoint points at the wrong URLConfirm 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 Checkoutstripe_tiers still holds test-mode IDs, or tiers.json slug driftedRe-run the seeder (§3.4)
Live payment succeeds but no tenant provisionedWebhook delayed or failed; pending_signups row still pending while Stripe shows paidGrep 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/successOld app build without structured payment outcomesDeploy current app image; verify GET /api/stripe/checkout-outcome returns user_message + charged
Real card rejected as generic_decline on first tryStripe’s anti-fraud learned this account only ran test-mode before and flagged the first real cardTry a different card; if it persists, contact Stripe support — common with new accounts

I need to…Read
Understand the pricing model and Adaptive Pricing18-STRIPE-GLOBAL-PRICING.md
Change a price after live is enabled18-STRIPE-GLOBAL-PRICING.md §3.1
See Stripe keys and billing flags in production04-ROADMAP §1.1 Secrets
Tier-plans-only scope and BILLING_TIER_PLANS_ONLY24-SUBSCRIPTION-BILLING
Archive non-tier Stripe Products after accidental seedbackend/scripts/stripe_archive_non_tier_catalog.py
Payment failure UX and operator log grep24-SUBSCRIPTION-BILLING-AND-TIER-LIMITS.md §11
Stand up the production environment from zero20-PRODUCTION-DEPLOYMENT-GUIDE.md
Run day-2 ops (logs, restarts, backups)07-PLATFORM-RUNBOOK.md