Stripe Payments
PPP charges users via Stripe PaymentIntents — one-off annual charges initiated from the signup or upgrade flow. The backend sends an explicit amount (in cents for AUD, pence for GBP) on each PaymentIntent creation; there are no Stripe Products, Prices, Subscriptions, or Checkout Sessions involved. This page explains how the integration works, what to watch for in production, and how to exercise it locally.
Quick navigation
- Changing a plan price? Read the Pricing Updates & Stripe Runbook.
- Running a local smoke test? Jump to Local development & webhook forwarding.
- Something went wrong in production? See Troubleshooting.
1. What PPP uses Stripe for
| Plan | Account type | Price |
|---|---|---|
| CPD Home | cpd | See PPP pricing |
| PPP Full Platform | cpdppp | See PPP pricing |
The current AUD and GBP figures live in one place — the Pricing Updates runbook and the PLAN_PRICES constant it documents. Both plans are billed annually as a single PaymentIntent. PPP does not issue recurring charges — at the end of the 12-month window the user re-pays with a fresh PaymentIntent, which is why there is no Subscription object in Stripe. Tax collection is tracked in #5140; until that lands, the charged amount equals the displayed minor-unit value.
Stripe concepts PPP does and does not use
| Concept | Used by PPP? | Notes |
|---|---|---|
| PaymentIntents | Yes | One per signup/upgrade; amount is computed per request from PLAN_PRICES |
| Webhooks | Yes | payment_intent.succeeded / payment_intent.payment_failed write paymentStatus to the DB |
| Stripe Elements | Yes | Frontend uses CardNumberElement + confirmCardPayment() so card data never transits PPP servers |
| Products / Prices | No | There is no catalog in the Stripe dashboard; see the pricing runbook for why |
| Subscriptions | Not yet | Annual renewal is currently a fresh PaymentIntent. The invoice.upcoming renewal-notice handler (§ 5.1) is in place and tested, but only fires once renewals are actually issued as Stripe Subscriptions — see the note there |
| Checkout Sessions | No | The frontend uses Stripe Elements directly |
| Stripe Tax / Billing | No (yet) | Jurisdiction-specific tax collection is #5140; tracked but not implemented |
2. Architecture
Frontend (React + Stripe Elements)
|
v
tRPC procedure: payments.createPaymentIntent
|
v
paymentService.createPaymentIntent(input, ctx)
|
v
Stripe API (paymentIntents.create)
|
v
Frontend confirms card with returned client_secret
|
v
Stripe fires webhook → payments.webhookHandler
|
v
paymentService writes paymentStatus to the users tableKey files (use these as jumping-off points when tracing a bug):
| File | Purpose |
|---|---|
packages-shared/ppp/src/constants/pricing.ts | Single source of truth for plan amounts across all surfaces |
api/backend-ppp/src/services/paymentService/index.ts | PaymentIntent creation and webhook dispatch |
api/backend-ppp/src/routers/procedures/payments/ | tRPC procedures (createPaymentIntent, getStripeConfig) |
instances/ppp/src/contexts/StripeContext.tsx | Loads Stripe.js with the publishable key from the backend |
instances/ppp/src/modules/Signup/components/PaymentForm.tsx | Signup flow's payment step, wraps GenericPaymentForm |
instances/ppp/src/components/PaymentSection/GenericPaymentForm.tsx | Reusable Stripe Elements form (no business logic) |
PCI posture
No card data ever touches a PPP server. CardNumberElement from @stripe/react-stripe-js renders an iframe hosted by Stripe. When the user submits, the frontend calls stripe.confirmCardPayment(clientSecret, { payment_method: { card: elements.getElement(CardNumberElement), ... } }). The client_secret is short-lived and scoped to a single PaymentIntent, so even a leaked secret cannot be replayed to move money.
The backend only ever holds:
- The PaymentIntent ID (
pi_…) - The amount and currency
- The
paymentStatusresolved from the webhook (pending/completed/failed)
3. Environment variables
Set in Doppler (ppp/uat or ppp/prod) and injected into the Container App by Pulumi:
| Variable | Purpose | Required |
|---|---|---|
STRIPE_SECRET_KEY | Backend secret key (sk_test_… in UAT, sk_live_… prod) | Yes |
STRIPE_PUBLISHABLE_KEY | Served to the frontend via getStripeConfig tRPC query | Yes |
STRIPE_WEBHOOK_SECRET | Used to verify the signature on incoming Stripe webhooks | Yes |
There is no STRIPE_*_PRICE_ID — amounts are read from PLAN_PRICES in packages-shared/ppp/src/constants/pricing.ts at request time via getAmountForCurrency(plan, currency).
The Stripe publishable key is not shipped to the browser at build time. Instead, the frontend calls getStripeConfig on page load, which returns the current STRIPE_PUBLISHABLE_KEY from the backend env. This makes key rotation a one-env-var change — no rebuild required.
4. Creating a PaymentIntent — the tRPC shape
Procedure: trpc.payments.createPaymentIntent.mutate(input)
Input:
interface CreatePaymentIntentInput {
accountType: 'cpd' | 'cpdppp';
userDetails: {
firstName: string;
lastName: string;
email: string;
};
}Response:
interface PaymentIntentResponse {
client_secret: string | null;
payment_intent_id: string;
amount: number; // minor units, e.g. AUD cents (see PLAN_PRICES)
currency: string; // lowercase 3-letter code
accountTypeLabel: string; // e.g. "CPD Home Only"
}The backend reads the currency from the user's region (AU or UK) and picks the matching minor-unit amount from PLAN_PRICES. It then calls stripe.paymentIntents.create() with that amount plus a metadata object containing the signup's embraceId. The embraceId is what the webhook handler uses to locate the correct user row when the payment completes.
Errors surface as regular tRPC errors — BAD_REQUEST for schema violations, INTERNAL_SERVER_ERROR for Stripe API failures. The client never sees the raw Stripe error message; it is logged server-side with ctx.logger and replaced with a generic user-facing message.
5. Webhook handling
Stripe fires webhooks to POST /api/webhooks/stripe on the Container App. The route is wired through PPP's shared REST router in api/backend-ppp/src/rest/index.ts, which hands the raw request off to src/rest/stripe/webhook.ts. That handler:
- Reads the raw body from
event.body— decoding from base64 whenevent.isBase64Encodedis set — because Stripe signature verification must run against the exact bytes Stripe signed. - Verifies the signature by delegating to
verifyWebhookSignature(rawBody, signature)inpaymentService/webhookService.ts, which callsstripe.webhooks.constructEvent(...)withSTRIPE_WEBHOOK_SECRET. Any mismatch returns400immediately. - Processes the verified event via
processWebhookEvent(event), which dispatches onevent.type:payment_intent.succeeded→ writespaymentStatus: 'completed',paymentDate: now(), the amount/currency, and (when present)accountAccessderived frommetadata.accountType, to the users row matched bymetadata.embraceId.payment_intent.payment_failed→ writespaymentStatus: 'failed'.payment_intent.canceled→ writespaymentStatus: 'failed'(fixes #4969 — cancellation was previously unhandled).charge.refunded→ writespaymentStatus: 'failed'andaccountAccess: 'cpd', immediately revoking full-platform access (fixes #4969 — refunded users were retainingccdpppaccess indefinitely).charge.succeeded/charge.failed→ logged with charge id + amount or failure reason; no DB write (these are informational, because the PaymentIntent events are the source of truth for PPP).invoice.upcoming→ sends the policy-promised 14-day advance renewal notice (#11017). See § 5.1.- Any other event type → logged as "unhandled" and acknowledged with
200.
- Gracefully handles missing metadata: if a PaymentIntent has no
embraceId(for example, a test event fired from the Stripe dashboard), the handler logs a warning and returns200without touching the DB.
Webhooks must be idempotent — Stripe will retry on any non-2xx response, and the same event may fire twice. The payment-status handlers achieve idempotency by writing the same paymentStatus each time; invoice.upcoming cannot (an email is not idempotent by rewriting) and uses a claim row instead — see below.
5.1 invoice.upcoming — the 14-day renewal notice
PPP's published operational policy commits to:
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.upcoming is the hook that honours it. Handler: paymentService/renewalNoticeService.ts.
⚠️ Prerequisite: renewals must be Stripe Subscriptions
invoice.upcoming is a Billing/Subscriptions event. Stripe only emits it for an upcoming subscription invoice. As recorded in § 1, PPP today charges each annual renewal as a fresh one-off PaymentIntent, so there is no subscription for Stripe to preview and this event will not fire in production until renewals are issued as Stripe Subscriptions.
The handler is deployed, tested and correct, but until that migration happens the policy's promise is met by the code and not yet by the running system. Do not read "handler merged" as "doctors are being notified" — confirm the Dashboard shows invoice.upcoming deliveries before making that claim to anyone, including a regulator.
The webhook endpoint's subscribed event list is now versioned, not Dashboard-only (#11018)
The full list of events the endpoint is subscribed to — including invoice.upcoming — is declared in api/infra-stripe/src/webhook-config.ts, cross-checked in CI against the cases handled in webhookService.ts (webhookService.cross-check.test.ts — a handler with no subscription, or a subscription with no handler, fails the build). Adding or removing a subscribed event is now a reviewed code diff, not a Dashboard click. See api/infra-stripe/README.md and docs/site/architecture/decisions/0007-stripe-webhook-config-as-reviewed-script.md for how the endpoint itself is created (one manual per-environment bootstrap step — no official Pulumi Stripe provider exists) and reconciled thereafter (pnpm preview:uat|prod, pnpm apply:uat|prod in api/infra-stripe/).
One Dashboard setting remains genuinely account-level and out of api/infra-stripe's scope: Settings → Billing → Automatic (dashboard.stripe.com/settings/billing/automatic) → "Upcoming renewal events" lead time. This is a Stripe account-wide billing setting, not a webhook-endpoint property — it is not something a webhook-endpoint reconciler can declare. Set it to 14 days per environment; this is the one line on this page most likely to be silently wrong.
Stripe's own definition of the event is: "Occurs X number of days before a subscription is scheduled to create an invoice that is automatically charged — where X is determined by your subscriptions settings." That setting is account-level, applies to every subscription on the account, cannot be overridden per subscription, and (per Stripe) "for existing subscriptions, changing the number of days takes effect on the next billing period."
So the "2 weeks" the policy promises AMC lives, by default, in a Dashboard text field that anyone with Stripe access can change with no code change, no deploy and no review. The handler therefore does not trust it. It computes the actual days-to-charge from the invoice's own next_payment_attempt and refuses to send outside RENEWAL_NOTICE_LEAD_DAYS ± RENEWAL_NOTICE_LEAD_TOLERANCE_DAYS (14 ± 1), logging event: RENEWAL_NOTICE_LEAD_TIME_MISMATCH at error level.
If that marker appears in the logs, the account setting has drifted off 14 and the published notice period is no longer being honoured. It should carry an alert rule alongside ACS_SEND_FAILURE. The trade-off is deliberate and worth stating plainly: on drift the platform sends nothing and shouts, rather than silently sending a notice at the wrong lead time that misstates a commitment a regulator has reviewed.
This is exactly why the setting belongs in IaC — see #11018.
Two further quirks of this event, both load-bearing here:
- Upcoming invoices have no invoice ID. Stripe: "the received
Invoiceobject will not have an invoice ID." This is why the idempotency key below is (subscription, period) andstripe_invoice_idis nullable and excluded from the unique index — an id-keyed claim would fail on every real event. Covered by thehas no idtest. collection_method=send_invoicenever emitsinvoice.upcoming. Only automatically-charged subscriptions do — which is the case the policy describes ("charged to the registered credit card").
What triggers a notice
All of the following must hold, else the event is acknowledged with 200 and nothing is sent:
| Condition | Source | Skip reason logged |
|---|---|---|
| Invoice has a subscription parent | invoice.parent.subscription_details.subscription | not-a-subscription |
| A line item bills ≥ 360 days of service | invoice.lines.data[].period | not-annual |
| Charge date is 13–15 days away | next_payment_attempt ?? period_end | lead-time-mismatch |
| The customer maps to a PPP user | subscription metadata embraceId, else customer_email | user-not-found |
| No notice already sent for this period | subscription_renewal_notices | already-notified |
Cadence is derived from the line item's own service period because, under API version 2025-08-27.basil, an upcoming invoice's line items carry only price/product ids — not the recurring interval — and expanding the price would mean an outbound Stripe call from inside a webhook handler.
Idempotency
Stripe retries on any non-2xx and invoice.upcoming can fire more than once for the same invoice. A doctor receiving three "you're about to be charged" emails is worse than one receiving none, so the handler is biased to at-most-once:
- The send is claimed before it is dispatched — a row is inserted into
subscription_renewal_noticeswithonConflictDoNothing, guarded byUNIQUE (stripe_subscription_id, period_end). A losing insert returns zero rows and sends nothing. The unique index (not an application-levelSELECTpre-check) is what makes this safe under genuinely concurrent redeliveries. - The dedupe key is subscription + billing period, deliberately not the invoice id — a regenerated preview invoice for the same period is still one notice, while next year's renewal is a new period and is notified normally.
- A dispatch that fails keeps its claim row and returns
200. Retrying would risk a second email for a message that may already have left ACS; the failure is instead surfaced by the mailer'sACS_SEND_FAILUREmarker plusRENEWAL_NOTICE_SEND_FAILUREfrom the handler.
The table doubles as the audit record for the commitment. It deliberately separates intent from outcome:
| Column | Means |
|---|---|
claimed_at | When this row won the unique index. Proves only that a send was attempted. |
dispatched_at | When ACS accepted the message. This is the audit answer to "was the doctor notified?" — NULL means claimed but never sent. |
email_message_id | ACS operation id for support traceability. Can be NULL even on a successful send, so it is not the authoritative sent flag. |
lead_days | The lead time actually applied, so an audit can prove the 2-week promise per send rather than trusting the constant. |
amount_due / currency | Exactly what the doctor was told they would be charged. |
Local testing
stripe trigger invoice.upcomingNote that a triggered fixture will not usually satisfy the annual + 14-day conditions, so expect a not-annual or lead-time-mismatch skip. The behavioural contract is covered by unit tests in api/backend-ppp/src/services/payments-and-subscriptions/paymentService/renewalNoticeService.test.ts and end-to-end through the webhook switch in webhookService.test.ts.
6. Local development & webhook forwarding
You can run the full payment flow locally against Stripe's test mode.
Prerequisites:
# macOS
brew install stripe/stripe-cli/stripe
# Linux
# See https://stripe.com/docs/stripe-cli for the current install instructionsOne-time setup:
stripe login
# Follow the browser flow to authorise the CLI against your test accountRun PPP locally:
# Terminal 1: backend
cd api/backend-ppp
pnpm start
# Now listening on http://localhost:4000
# Terminal 2: frontend
cd instances/ppp
pnpm start
# Now listening on http://localhost:3000Forward Stripe webhooks to the local backend:
# Terminal 3
stripe listen --forward-to localhost:4000/api/webhooks/stripeThe CLI will print a fresh whsec_… signing secret on startup. Copy it into api/backend-ppp/.env:
STRIPE_WEBHOOK_SECRET=whsec_copy_the_one_the_cli_printedThen restart the backend so the new secret takes effect. Now trigger a test payment:
# From a fourth terminal:
stripe trigger payment_intent.succeeded
stripe trigger payment_intent.payment_failedYou should see the event hit listen, the backend log the webhook, and the corresponding DB write land in the users table (you will need an existing row with a matching embraceId in its PaymentIntent metadata for the DB write to take effect — the gracefully-ignored-missing-metadata path will fire otherwise).
To run the full signup flow end-to-end:
- Open
http://localhost:3000/signup-processin the browser - Fill the form and pick an account type (CPD or PPP Full)
- Use a test card — do not use a real card against the test key
- Confirm the payment — you should land on the next signup step with
paymentStatus: 'completed'on the user record
7. Test cards
Stripe test mode accepts a fixed set of test card numbers. Always use these, never real cards, in dev/UAT:
| Scenario | Card number | Notes |
|---|---|---|
| Successful payment | 4242 4242 4242 4242 | Any future expiry, any CVC |
| Card declined | 4000 0000 0000 0002 | Generic decline |
| Insufficient funds | 4000 0000 0000 9995 | Use to exercise the failure path |
| 3DS required | 4000 0027 6000 3184 | Triggers Stripe Radar 3D Secure challenge |
For the complete list see Stripe's test cards documentation. The CI contract tests in api/backend-ppp/src/__fixtures__/external-services.contracts.test.ts cover the main scenarios against recorded fixtures.
8. Testing the payment service
Unit and integration tests:
cd api/backend-ppp
pnpm test -- paymentServiceContract tests (verify the mock matches Stripe's current response shape):
cd api/backend-ppp
pnpm test -- external-services.contractsEnd-to-end (Playwright BDD):
pnpm --filter @ppp-org/instance-ppp test:bdd --grep @feature:signup-payment --grep @smokePer api/backend-ppp/CLAUDE.md, tests hit paymentService methods directly with a real TrpcContext instead of going through the tRPC procedure layer, and always clean up test rows in afterAll.
9. Observability
Structured logs — the payment service and webhook handler use the shared baseLogger with service: 'payments'. Diagnose payment issues with:
ContainerAppConsoleLogs_CL
| where Log_s contains "service=payments"
| project TimeGenerated, Log_s
| order by TimeGenerated descMetrics to monitor:
- Payment success rate — percentage of PaymentIntents that reach
succeeded - Webhook verification failures — indicates clock skew or a rotated secret gone wrong
- Webhook processing latency — webhooks must return
2xxwithin ~20s or Stripe retries - Stripe API error rates — broken out by
type(card_error,api_connection_error, etc.)
Alerting — there is no dedicated Stripe dashboard yet; track #5140 for the payment observability epic.
10. Production deployment
Production secrets live in Doppler's ppp/prod config and are rotated through the same flow as any other Key Vault secret. The relevant change sequence is:
- Rotate
STRIPE_SECRET_KEY/STRIPE_WEBHOOK_SECRETin Stripe dashboard → Developers → API keys / Webhooks - Update the values in
ppp/prodvia Doppler - Restart the
ppp-uk-prodContainer App revision so the new env vars are picked up - Run a live smoke test — trigger a £1 PaymentIntent from a test account and confirm the webhook writes
There is no "Stripe price" to update — all prices flow from PLAN_PRICES via a deploy. See the pricing runbook for the full fan-out.
11. Troubleshooting
"STRIPE_SECRET_KEY environment variable is required" : The Container App restarted without the env var bound. Check the Pulumi stack applied cleanly and that Doppler is healthy; then restart the app.
Webhook signature verification fails : Either the STRIPE_WEBHOOK_SECRET is stale (rotated in Stripe but not in Doppler) or the request came from a different webhook endpoint (Stripe allows multiple). Confirm the endpoint URL in Stripe dashboard → Developers → Webhooks matches the Container App's public URL.
Payment succeeds in Stripe but user still shows paymentStatus: 'pending' : The webhook did not reach the Container App, or the embraceId metadata was missing. Check ContainerAppConsoleLogs_CL for webhook received but no embraceId. You can replay the event from the Stripe dashboard → Developers → Webhooks → the event → "Resend".
"No such payment_intent" : Usually caused by using a test secret key against a live PaymentIntent (or vice versa). Check the key prefix — sk_test_… vs sk_live_….
Frontend "Stripe has not loaded" : getStripeConfig returned an empty publishable key. Most common cause: STRIPE_PUBLISHABLE_KEY missing in env. Open the network tab and inspect the getStripeConfig response.
12. Security considerations
- Rate limiting on
createPaymentIntentprevents enumeration and DoS — seerateLimitedSensitiveProcedurein the payments router - Input is validated via Zod schemas — malformed account types or emails are rejected before a Stripe call
- Stripe API errors are logged with
ctx.loggerbut never returned to the client verbatim - The
payments.webhookHandleruses Stripe's official signature verification — do not reimplement it - PPP never stores card numbers, CVC, or expiry in any form
13. Frontend integration pattern
The frontend follows the Stripe Elements pattern end-to-end — card data never touches PPP servers, and the tRPC call that creates the PaymentIntent is decoupled from the call that confirms the payment.
13.1 Provider setup
At app boot, StripeContext calls getStripeConfig and initialises Stripe.js with the returned publishable key:
// instances/ppp/src/contexts/StripeContext.tsx (simplified)
const { data } = trpc.payments.getStripeConfig.useQuery();
useEffect(() => {
if (data?.publishableKey) {
setStripePromise(loadStripe(data.publishableKey));
}
}, [data]);
return <Elements stripe={stripePromise}>{children}</Elements>;Wrapping the signup/upgrade flow in <Elements> gives every child access to useStripe() and useElements() hooks.
13.2 Payment form
GenericPaymentForm renders three CardNumberElement/CardExpiryElement/CardCvcElement iframes and a submit button. All business logic (amount, label, account type) is injected via props — the form itself contains no PPP-specific values:
// instances/ppp/src/components/PaymentSection/GenericPaymentForm.tsx (simplified)
interface Props {
accountType: 'cpd' | 'cpdppp';
onSuccess: (paymentIntentId: string) => void;
onError: (message: string) => void;
firstName: string;
lastName: string;
email: string;
}The "pay" handler:
const handlePay = async () => {
const stripe = useStripe();
const elements = useElements();
if (!stripe || !elements) return;
// 🤗 Ask the backend to create a PaymentIntent and return a client secret
const response = await createPaymentIntentMutation.mutateAsync({
accountType: props.accountType,
userDetails: {
firstName: props.firstName,
lastName: props.lastName,
email: props.email,
},
});
// 🤗 Confirm the card payment directly with Stripe
const { error } = await stripe.confirmCardPayment(response.client_secret, {
payment_method: {
card: elements.getElement(CardNumberElement)!,
billing_details: {
name: `${props.firstName} ${props.lastName}`,
email: props.email,
},
},
});
if (error) {
props.onError(error.message ?? 'Payment failed');
return;
}
props.onSuccess(response.payment_intent_id);
};13.3 Post-payment flow
When onSuccess fires, the caller advances the signup wizard to the next step. Crucially, the user record has not yet been flipped to paymentStatus: 'completed' — that write happens in the webhook handler when Stripe notifies the backend. The signup flow displays a "confirming payment" intermediate state for the handful of seconds it takes for the webhook to land. If the webhook does not arrive within a timeout window (usually 10 seconds), the user can retry and the backend will return the existing PaymentIntent status.
14. Backend request handling
14.1 createPaymentIntent in detail
// Simplified from api/backend-ppp/src/services/paymentService/index.ts
export async function createPaymentIntent(
input: CreatePaymentIntentInput,
ctx: TrpcContext,
) {
// 🤗 Resolve the currency from the user's region (AU → AUD, UK → GBP)
const currency = resolveCurrency(ctx);
// 🤗 Read the minor-unit amount from PLAN_PRICES
const amount = getAmountForCurrency(input.accountType, currency);
// 🤗 Build the metadata that the webhook handler will use to locate the user
const metadata: Record<string, string> = {
accountType: input.accountType,
userEmail: input.userDetails.email,
};
if (ctx.embraceId) metadata.embraceId = String(ctx.embraceId);
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency,
payment_method_types: ['card'],
metadata,
description: `${PAYMENT_CONFIG.accountTypes[input.accountType]} — annual`,
});
return {
client_secret: paymentIntent.client_secret,
payment_intent_id: paymentIntent.id,
amount,
currency,
accountTypeLabel: PAYMENT_CONFIG.accountTypes[input.accountType],
};
}14.2 Webhook handler in detail
The webhook entry point is a plain REST handler (not a tRPC procedure) because Stripe's signature verification requires access to the raw request body. PPP uses its own IRestHandler shim so the same code shape runs in both the dev Express server and the production Container App, without depending on express.raw():
// Simplified from api/backend-ppp/src/rest/stripe/webhook.ts
import type { IRestHandler } from '~ppp-core/types/rest-handler';
import {
verifyWebhookSignature,
processWebhookEvent,
} from '~ppp-api/services/paymentService/webhookService';
const handler: IRestHandler = async event => {
const signature = event.headers['stripe-signature'];
if (!signature || !event.body) {
return { statusCode: 400, body: JSON.stringify({ error: 'Bad request' }) };
}
// 🤗 Decode base64 when the upstream gateway wraps the body
const rawBody = event.isBase64Encoded
? Buffer.from(event.body, 'base64').toString('utf-8')
: event.body;
try {
const stripeEvent = verifyWebhookSignature(rawBody, signature);
await processWebhookEvent(stripeEvent);
return { statusCode: 200, body: JSON.stringify({ received: true }) };
} catch (err) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Webhook signature verification failed' }),
};
}
};
export default handler;processWebhookEvent is defined in paymentService/webhookService.ts and switches on event.type:
// Simplified from api/backend-ppp/src/services/paymentService/webhookService.ts
switch (event.type) {
case 'payment_intent.succeeded': {
const pi = event.data.object as Stripe.PaymentIntent;
await writePaymentStatus(pi, 'completed');
return { received: true, eventType: event.type, paymentIntentId: pi.id };
}
case 'payment_intent.payment_failed': {
const pi = event.data.object as Stripe.PaymentIntent;
await writePaymentStatus(pi, 'failed');
return { received: true, eventType: event.type, paymentIntentId: pi.id };
}
case 'charge.succeeded':
case 'charge.failed':
// 🤗 Logged for observability; PaymentIntent events drive state changes
return { received: true, eventType: event.type };
default:
// 🤗 Unhandled event type — acknowledged so Stripe does not retry
return { received: true, eventType: event.type };
}writePaymentStatus locates the user via metadata.embraceId (and also reads metadata.accountType to derive accountAccess), then calls updatePaymentInfo(...) to write the new status. If the metadata is missing or embraceId is not a valid number, it logs a warning and returns — no DB write, no error.
15. Architecture decisions
15.1 Why PaymentIntents and not Checkout Sessions?
Checkout Sessions are Stripe's hosted checkout page — they handle everything from card collection to 3DS to receipt. They are faster to implement but require:
- A redirect away from the PPP signup wizard
- Configuring a success/cancel URL pair
- A Stripe Product and Price per plan per currency
PPP's signup is a multi-step wizard with pre- and post-payment steps, and redirecting away from the wizard mid-flow would break the experience. PaymentIntents keep everything in-page and let the signup form own the UX.
15.2 Why no Stripe Products / Prices?
At current volume, PPP has two plans and two currencies — four (plan, currency) tuples in total. Managing them in PLAN_PRICES as a single constant is simpler than creating Stripe catalogue entries that have to be kept in sync via API calls or dashboard edits. If PPP grows to dozens of plans or adds automated promotions/discounts, moving to Stripe catalogue objects becomes worth the complexity. Until then, the one-file-of-constants approach is reviewed and shipped like any other code change.
See the Pricing Updates & Stripe Runbook for the full rationale and the fan-out steps.
15.3 Why is card confirmation client-side?
Because PCI. If the card data flows through PPP servers to reach Stripe, PPP enters scope for full PCI DSS compliance — a heavy cost for a small team. By using Stripe Elements and confirmCardPayment() client-side, the card data goes browser → Stripe directly, and PPP only ever sees the payment_intent_id and (later) the webhook event. This is Stripe's explicit recommendation and the reason Elements exists.
15.4 Why is the publishable key fetched server-side at runtime?
PPP frontend is built and deployed to Cloudflare Pages as a static bundle. Embedding STRIPE_PUBLISHABLE_KEY at build time would mean every key rotation requires a frontend redeploy. Instead, getStripeConfig returns the current publishable key on page load, so rotating the key is a one-env-var change on the Container App — no frontend touch.
16. Failure modes at a glance
| Failure | User impact | Operator action |
|---|---|---|
| Stripe API is down | Signup payment step shows an error; user can retry | Monitor status.stripe.com; no PPP action |
STRIPE_SECRET_KEY missing | createPaymentIntent returns 500 for everyone | Re-apply Pulumi; restart Container App |
| Webhook endpoint unreachable | Payments succeed but paymentStatus stays pending | Replay events from Stripe dashboard; fix infra |
STRIPE_WEBHOOK_SECRET rotated stale | All webhooks fail signature verification | Roll the Doppler value; restart app |
Metadata missing embraceId | Webhook is acknowledged but no DB write | Usually harmless (dashboard test events) |
Canonical implementation docs
The full internal guide — including historical context, architecture decisions, and the changelog for the integration — lives in the backend repo:
Related
- Integrations overview — the five external services PPP depends on
- Pricing Updates & Stripe Runbook — step-by-step for changing a plan price
api/backend-ppp/src/utils/resilience.ts— shared retry, timeout, and circuit breaker helpers reused across integrations