Payment & Subscription Lifecycle
Feature Overview
Stripe-backed annual payment for PPP plans (CPD Home and PPP Full Platform — current AUD/GBP figures in the canonical PPP pricing table). Covers initial purchase, mid-cycle upgrade with proration, and end-of-period downgrade. Users always retain the access tier they have paid for until the period they paid for ends.
Open Questions
| # | Question | Ref | Proposed answer |
|---|---|---|---|
| — | No open questions. |
Acceptance Criteria
Downgrade
- ✅ Downgrade request schedules a flip; access is NOT revoked immediately (#4966)
- ✅ User keeps PPP access until end of current annual billing period (#4966)
- ✅ Period end =
paymentDate + 1 year, rolled forward past historic anniversaries (#4966) - ✅
accountAccessflips tocpdlazily on next user load after period end (#4966) - ✅ Confirmation copy matches behaviour: "retain access until end of billing period" (#4966)
Payment confirmation from the client
- ✅
payments.updatePaymentInfotakes only a PaymentIntent id from the client. AnypaymentStatus,accountAccess,paymentAmount,paymentCurrencyorpaymentDatethe client sends is dropped. The server retrieves the PaymentIntent from Stripe and writes the payment and the tier only when Stripe reports itsucceeded, received in full (amount_received) and not refunded or disputed (checked on the expandedlatest_charge, because Stripe leaves a refunded PaymentIntentsucceeded), it belongs to the caller (metadata.embraceIdis the caller, or, when unbound,metadata.userEmailis the email of the caller's authenticated session (not the editableusers.email), after which it is bound), it charged thePLAN_PRICESannual price for the plan in its server-setmetadata.accountType(a prorated upgrade: more than zero and no more than the full PPP price,metadata.upgradeFrom = 'cpd', and only for a caller on a paid CPD plan —accountAccess = 'cpd',paymentStatus = 'completed'— keeping that plan'spaymentDate;createUpgradePaymentIntentrefuses anyone else), and no other account has already recorded it. Otherwise the call is refusedFORBIDDEN/BAD_REQUESTand nothing is written. Re-confirming a PaymentIntent already recorded on the caller's own row (any status butpending) is a no-op: no re-grant after a downgrade or refund, andpaymentDateis not reset; the call reports the stored grant only when that row'spaymentStatusiscompleted, otherwise a non-granting response. A PaymentIntent grants at most once: after granting, the server marks it in Stripe metadata (pppGrantedUserId,pppGrantedAt) and refuses it on any later call, and a PaymentIntent created before the caller's current plan was granted (paymentDate) is refused, so alternating older PaymentIntents after a downgrade restores nothing (#12605) † ‡
Upgrade
- ✅ Mid-cycle CPD → PPP upgrade is prorated to next anniversary (#3145)
Initial purchase
- ✅
createPaymentIntent(public — the anonymous sign-up flow creates the PaymentIntent before an account exists, so it cannot require auth) never trusts a client-suppliedembraceId; the field does not exist on its input schema. When the caller is authenticated,metadata.embraceIdis bound server-side to the caller's own id (resolved from the session, not request input); an unauthenticated caller gets noembraceIdat all — it is attached later via theuserEmail-match path inattachEmbraceIdToPaymentIntentonce the account exists (#12683). - ✅ The Stripe webhook (
payment_intent.succeeded/.payment_failed/.canceled) is never authoritative foraccountAccesson its own. A failed/canceled event never changesaccountAccess, regardless ofmetadata.accountType. A succeeded event only writesaccountAccesswhenassessPaymentIntentGrant— the same rulesconfirmPaymentFromStripeenforces (#12605) — grants it against the current DB row, with the PaymentIntent re-retrieved (expandedlatest_charge) and re-verified from Stripe rather than trusting the webhook payload's own metadata; a PaymentIntent already recorded on this row with a completed grant is a no-op, but a priorfailedwrite on the same id never blocks a genuine later retry-success from being granted (#12683). Supersedes the prior "Stripe webhook setsaccountAccessfromaccountTypemetadata" behaviour from #3554, which wrote unconditionally — including on a failed payment — and let an unauthenticated caller corrupt any account's entitlement for free. - ✅
attachEmbraceIdToPaymentIntent's#5036race-condition reconciliation write (the webhook fired before signup completed) is also gated throughassessPaymentIntentGrant, not a directmetadata.accountTyperead — the same unverified-write gap the webhook fix closed applied equally here, since this path is reachable without ever going through the webhook (#12683 review follow-up). - ✅ At sign-up, the paid tier and
paymentStatus = 'completed'come only from Stripe. The client'spaymentStatus,accountAccessandpayment*values are never saved. A supplied PaymentIntent id is used only to look up the PaymentIntent in Stripe. The tier is written from the PaymentIntent's server-setmetadata.accountType, and only when Stripe reports the PaymentIntent as succeeded (#12594) - ✅ A PaymentIntent pays for exactly one account, including under concurrent sign-ups (#12594).
attachEmbraceIdToPaymentIntentenforces this in three steps:- It refuses a PaymentIntent whose server-set
metadata.userEmaildoes not match the registrant's email (case-insensitive). The server sets that value increatePaymentIntent, and only the server can change it afterwards. - It refuses a PaymentIntent whose
metadata.embraceIdalready names a different user. - Before crediting a succeeded PaymentIntent, it claims it in the DB (
claimPaymentIntentForUser: a conditional UPDATE ofusers.payment_intent_idunder a transaction-scoped advisory lock on the PaymentIntent id). Only the account that wins the claim is credited. Stripe metadata has no compare-and-set andusers.emailis not unique (#12597), so neither of the first two checks alone holds under concurrency.
- It refuses a PaymentIntent whose server-set
- ⚠️ If the attach throws during sign-up, the paid registrant is created on
cpdwith nopaymentStatusand is sent to/complete-payment. Nothing repairs that grant automatically until #12611 lands. Today only the/billingemail re-attach does. - ✅
/complete-paymentis an initial-purchase surface only, never a way to move an already-paid account between tiers.assessPaymentIntentGrantrefuses any non-upgrade (nometadata.isUpgrade) PaymentIntent when the caller already hasaccountAccess = 'cpdppp'andpaymentStatus = 'completed', andCompletePaymentredirects such a user to/billingbefore the Stripe form renders. Without this, an already-paid PPP user who reached/complete-payment(nothing blocked a direct visit) and paid full price for CPD Home would be downgraded tocpdimmediately — bypassingpendingDowngradeAtentirely, the exact outcome the Downgrade ACs above exist to prevent (#12676) ‡
Billing history
- ✅
/billing's Payment History list distinguishes a real load failure from "you have no payments yet" —listUserPaymentsreads live from Stripe, so a transient Stripe error must surface as an error state, not the same empty-state copy a genuinely payment-free account sees (#12648;code:instances/ppp/src/modules/payments/billing/index.tsx). - ✅
payment.history-row-fields— each/billingPayment History row renders the router'screatedAt(date),amount+currency(formatted) andstatus; reading the legacypaymentDate/paymentAmount/paymentCurrency/paymentStatuskeys left every row at "N/A" / "Unknown" (T7-39, #11189). - ✅
payment.pending-downgrade-indicator— whilependingDowngradeAtis set (a downgrade scheduled but not yet applied),/billingand/plans-and-pricingshow a persistent notice: "Your plan will change to CPD Home on<date>. You keep full PPP access until then." (#12686; componentPendingDowngradeNotice).
Review & appeal fee
- ✅ The CPD review/appeal fee is defined once, in
REVIEW_APPEAL_FEES(packages-shared/ppp/src/constants/pricing.ts): appeal filing fee $600 AUD (ex GST) per the published Review and Appeal Policy July 2026; internal reviews carry no fee. Consuming surfaces (CPD Support appeal form, User Guide) render the constant's label, never a hard-coded figure, so the charge shown to doctors cannot drift from the published policy without a reviewed change to this constant. Supersedes the pre-July-2026 $165 incl-GST figure (#8059/#8069 era). (#11034)
Renewal notice
The published operational policy states: "Annual membership fees are due December 31st each year and charged to the registered credit card. Notification via email will be sent to subscribed users 2 weeks in advance notifying of this upcoming billing occurrence."
- ✅
invoice.upcomingsends one email 14 days before an annual renewal, stating the plan, renewal date and amount (#11017) - ✅ The 14-day lead time is an explicit constant asserted against the invoice's charge date, never inherited from the Stripe account setting; a mismatch logs
RENEWAL_NOTICE_LEAD_TIME_MISMATCHand sends nothing (#11017) - ✅ Idempotent: the send is claimed against
UNIQUE (stripe_subscription_id, period_end)before dispatch, so a replayed webhook sends nothing (#11017) - ✅ A non-annual or non-subscription invoice does not trigger the notice (#11017)
- ✅ The Stripe webhook endpoint's subscribed event list is managed as reviewed, versioned config (
api/infra-stripe/) rather than a Dashboard-only setting, with a drift-detecting reconciler script — see ADR-0007 (#11018) - ✅ The declared event list (
api/infra-stripe/src/webhook-config.ts) and thecaselist actually handled inwebhookService.tsare cross-checked by test: an event handled but not declared silently never fires (Stripe was never told to call it); an event declared but not handled falls through to the unhandleddefaultbranch (#11018)
Current Status
| Sub-feature | Status | Notes |
|---|---|---|
| Initial purchase | ✅ Built | Stripe webhook flow |
| Mid-cycle upgrade | ✅ Built | Proration in calculateProratedUpgrade |
| End-of-period down | ✅ Built | #4966 — pendingDowngradeAt + lazy flip |
| Renewal notice | ✅ Built | #11017 — invoice.upcoming, 14-day advance email |
Open issues on label:feature:payment — issue data unavailable at build time.Fetched at: 2026-10-13T07:29:49Z — live list on GitHub.
Open GitHub Issues
No open issues — #4966 (downgrade revoked access immediately) was closed once the pendingDowngradeAt fix landed; confirmed closed on GitHub during the 2026-10-01 payments re-audit, correcting this table which had gone stale.
Change Log
| Date | Change | PR/Issue | Reason |
|---|---|---|---|
| 2026-10-05 | Billing Payment History rows now read the router's createdAt/amount/currency/status (they showed N/A / Unknown), and a persistent pending-downgrade notice shows on Billing and Plans & Pricing while pendingDowngradeAt is set. | #11189, #12686 | Rob 2026-10-05 Task 7 live audit (T7-39) and #12686: the page read legacy payment* keys the router never returns, and a scheduled downgrade had no visible indicator. |
| 2026-10-01 | An already-paid PPP (cpdppp) user can no longer be downgraded immediately by paying full price for CPD via /complete-payment; assessPaymentIntentGrant refuses the grant and /complete-payment redirects an already-paid user to /billing before a charge can even be attempted. | #12676 | Live-repro''d during the 2026-10-01 payments area-lane re-audit with a real Stripe test-mode charge: createPaymentIntent/confirmPaymentFromStripe had no concept of "the caller already owns a plan", so a non-upgrade PaymentIntent could grant cpd immediately, overwriting paymentDate/paymentIntentId and completely bypassing the pendingDowngradeAt deferred-downgrade mechanism #4966 exists to protect. |
| 2026-10-01 | createPaymentIntent no longer trusts a client-supplied embraceId — it is bound server-side from the authenticated session (or left unbound for a genuine anonymous sign-up) and removed from the input schema entirely. The Stripe webhook (payment_intent.succeeded / .payment_failed / .canceled) is no longer authoritative for accountAccess: a failed/canceled event never touches entitlement, and a succeeded event only grants it when assessPaymentIntentGrant — the same #12605 business rules confirmPaymentFromStripe enforces — approves it against the current DB row, re-verified with Stripe. | #12683 | Security (#12683): createPaymentIntent is a public procedure (anonymous sign-up creates the PaymentIntent before an account exists), so the client-trusted embraceId let an unauthenticated caller point any victim's id at a PaymentIntent and have the webhook overwrite that victim's accountAccess/paymentStatus for free — on a FAILED payment, no less. The same gap also re-opened #12676 (the webhook granted/downgraded unconditionally, bypassing the #12680 guard that only covers the confirmPaymentFromStripe path). |
| 2026-09-30 | '/billing'''s Payment History list now shows an error state when listUserPayments fails, instead of the same "No payment history found." copy a genuinely payment-free account sees. | #12648 | listUserPayments reads live from Stripe on every load; the component never checked isError, so a transient Stripe outage would silently read to a doctor as "you never paid" rather than "something went wrong, try again" (found live during the onboarding team-mode audit, #11189). |
| 2026-09-29 | payments.updatePaymentInfo now takes only a PaymentIntent id. The server retrieves it from Stripe and grants the tier from its server-set metadata.accountType only when it succeeded, belongs to the caller, charged the PLAN_PRICES amount, and has not been recorded on another account; otherwise FORBIDDEN/BAD_REQUEST and nothing is written. The upgrade modal, upgrade form and Complete Payment page send only the PaymentIntent id. Review hardening: a refunded or partially received PaymentIntent is refused (checked on the expanded latest_charge); re-confirming a PaymentIntent already recorded on the caller's row is a no-op; an upgrade PaymentIntent only lifts a paid CPD plan (and createUpgradePaymentIntent refuses anyone else) and keeps its paymentDate; unbound ownership uses the session email. A PaymentIntent grants at most once, ever: it is marked pppGrantedUserId / pppGrantedAt in Stripe metadata after granting, and a PaymentIntent created before the caller's current plan was granted is refused, so alternating older PaymentIntents after a downgrade restores nothing. A disputed charge is refused. A no-op re-confirm reports the stored grant only for a completed row (a failed row can still carry the PaymentIntent's tier from the webhook, tracked in #12618). The concurrent-claim race is tracked in #12615. | #12612, #12605 | Security (#12605): the procedure wrote the client's paymentStatus / accountAccess straight onto the caller's row, so any signed-in user could unlock the paid tier without paying (confirmed with a live-DB integration test on uat). |
| 2026-09-29 | At sign-up (password and SSO), the paid tier and paymentStatus now come only from Stripe. Any supplied PaymentIntent is handed to attachEmbraceIdToPaymentIntent whatever paymentStatus the client claims. That function binds the PaymentIntent to its server-set metadata.userEmail and claims it atomically in the DB (advisory lock + conditional UPDATE), so concurrent sign-ups cannot all be credited for one payment. | #12607, #12594 | Security (#12594): signUp saved the client-sent paymentStatus: completed and accountAccess: cpdppp, so a registrant could unlock the paid tier without paying. |
| 2026-08-27 | Stripe webhook endpoint config (subscribed event list) moved from Dashboard-only to reviewed, versioned IaC (api/infra-stripe/), with a drift-detecting reconciler and a cross-check test that the declared event list and the handled case list in webhookService.ts match exactly. | #11872, #11018 | The webhook subscription list had no version control, review, or drift detection — an unsubscribed event silently stops calling its handler with no test failure (#11018). See ADR-0007 for why a reviewed script was chosen over a Pulumi provider (none exists for Stripe). |
| 2026-08-01 | Review/appeal fee single-sourced in REVIEW_APPEAL_FEES (packages-shared/ppp/src/constants/pricing.ts) — appeal $600 AUD ex GST per the July 2026 policy; internal reviews remain free. | #11255, #11034 | The fee was hard-coded per surface and stale ($165 incl GST); a constant makes future fee changes single-point and reviewable (#11034). |
| 2026-07-26 | Implement the policy-promised 14-day advance renewal notice. invoice.upcoming is now handled and sends one email 14 days before an annual renewal. The 14 days is an explicit constant asserted against the invoice charge date (not inherited from the Stripe account setting, which is Dashboard-editable); idempotency is enforced by claiming the send against UNIQUE (stripe_subscription_id, period_end) before dispatch. Email only — no in-app notification. | #11023, #11017 | The published operational policy has committed to this notice since before launch but it was never implemented; the policy is being published for an AMC review. Does not fire until renewals are issued as Stripe Subscriptions and the endpoint is subscribed to invoice.upcoming (manual Dashboard step, automated by #11018). |
| 2026-06-10 | Added code-paths for pricing.ts | #8606, #8485 | Matt-locked prices live in pricing.ts (no-hardcoded-brand-values policy #7525); drift gate now fires correctly when prices change, per #8485 |
| 2026-06-02 | AUD prices shown GST-inclusive (B2C); AUD tax label reverted to incl. GST. Charge unchanged at $275 (27500). | #8078, #8069, #8059 | Matt: PPP sells B2C to individual doctors, so the displayed figure is the all-in price including GST. Reverses the #8058 ex-GST labelling. |
| 2026-06-02 | CPD Home AUD price set to $275 ex GST (27500 cents); AUD tax label changed from incl-GST to ex-GST. | #8058, #8057 | AMC review — realign code with the canonical pricing runbook and marketing cards; reverses the #5140 incl-GST labelling. Charged amount equals the displayed value (no GST added at checkout). |
| 2026-05-19 | Added Stripe Customer Portal integration — a "Manage billing & invoices" button on the Billing page opens a Stripe-hosted portal session for downloading invoices and updating the saved payment method. | #6532, #4972 | The Billing page only showed a read-only PaymentIntent table — users had no way to download a receipt/invoice PDF or update their payment method. Stripe's Customer Portal provides all of this via a single redirect; the customer is resolved/created by email at session time so no schema migration was needed. |
| 2026-04-28 | Spec authored. Downgrade now defers accountAccess flip to end of billing period via pendingDowngradeAt. | #4966 | Matt's call: do not remove access until end of billing cycle; UX copy was already correct. |