# eSIM backend payment router

The new common endpoint selects payment using one per-application setting. Existing Razorpay and
legacy Stripe callbacks remain available. Backend prices/coupons, not frontend
amounts or success flags, authorize charging/provisioning.

## Current inter-project contract

| Mode | Initiation | Verified status |
| --- | --- | --- |
| Razorpay redirect | Existing gateway /api/payment | Existing Razorpay path |
| Stripe web redirect | Existing /api/payment, encrypted body with signed esim_checkout marker | Existing POST /api/payment-status, signed JSON with payment_flow=checkout |
| Native Apple Pay | Existing POST /api/payment, signed JSON with payment_flow=apple_pay | Existing POST /api/payment-status, signed JSON with payment_flow=apple_pay |

Gateway auth headers are X-Payment-Timestamp and X-Payment-Signature. Signature:
HMAC-SHA256(timestamp + "." + request_path_without_leading_slash + "." + exact_body).
Web signs the encrypted request bytes. Native/status signs JSON bytes. Requests
expire after 300 seconds. These server secrets never go to the app.

Native initiation returns `token=native_ap_...`, `payment_intent_id=pi_...`, client
secret and public merchant configuration. Common stores the gateway token as
gateway_payment_id/customerPaymentId and the Stripe ID as paymentId. Status
returns that SAME gateway token; successful native payment must be Apple Pay.

Hosted initiation returns token, URL and checkout_session_id. Common correlates
gateway_payment_id with cs_..., not pi_.... Paid status returns both cs_... and
pi_..., matching amount/currency/tracking/plan/quote. No browser redirect authorizes
an eSIM. This opt-in path has stable idempotency; ordinary gateway Checkout callers
keep their original behavior and response contract.

Both gateway adapters use existing transactions/transactions_meta with independent
flow markers. No gateway migration or new gateway API paths. The existing
`/webhook/stripe-payment` handler dispatches tracked flows only after per-project
signature verification, leaving unmarked legacy processing intact.

Common backend uses ONLY `esim_transactions`. Apply
`add_esim_transaction_checkout.sql` schema-first: four nullable columns
(checkout_request_key, payment_mode, checkout_context, payment_last_checked_at)
and two indexes. Existing amount/coupon/status/provisioning/ID/email fields remain
authoritative. checkout_context holds exact immutable quote bytes, plan snapshot,
creation state, provider recovery result and delivery claim. It does not hold a
second payment/provisioning status. The existing STRIPE method is reused without
changing its old-app visibility; no bookkeeping method is added.

Do not run discarded draft CREATE TABLE instructions. If a draft table already
contains attempts, reconcile/copy them explicitly before enabling; do not drop it
or leave paid attempts behind. No data migration has been run.

## Controls and old apps

- ESIM_STRIPE_ENABLED is the only provider-selection switch. Missing/0 selects
  Razorpay on the NEW API; 1 selects Stripe. It does not disable the endpoint.
- With Stripe on, authenticated iOS devices declaring native Apple Pay support
  receive apple_pay; web, Android and other clients receive hosted Checkout.
- Unsupported currencies are rejected, not silently converted or rerouted. The
  current server quote supports USD and INR; gateway account eligibility is also checked.
- Retired router/web/native/app/user/currency/method-ID settings are ignored.
  Before deploying this simplification, explicitly set ESIM_STRIPE_ENABLED=0;
  a previous secondary gate no longer limits a Stripe switch already set to 1.
- Old apps calling the old link API stay on their existing flow.
- Both APIs share RazorpayService::makeEsimPayment for the original eSIM gateway
  encryption/payment/decryption transport and PAYMENT_BASE_URL. The old API's
  amount/coupon/currency/response behaviour is preserved; the new API uses its
  existing backend-calculated, persisted quote and response envelope.
- New native app needs Stripe SDK/merchant entitlement and payment_mode handling.
- Disabling new payments does not cancel already-created provider attempts.
- Never automatically fail over after uncertain creation: reuse/reconcile the
  original tracking ID to avoid two payable orders.

All current my_settings constants and deployment values are documented in
`esim-payments-staging-setup.md`. Gateway config is STRIPE_APPLE_PAY_APPS, with
independent enabled (native) and checkout_enabled flags. Both use the target application's existing
Stripe credentials and unrestricted active Stripe permission.

The new adapter reuses STRIPE_PAYMENT_API_URL (the existing gateway API prefix),
STRIPE_PAYMENT_SUCCESS and STRIPE_PAYMENT_FAILURE. No separate web-return URL
settings are needed. ESIM_GATEWAY_SHARED_SECRET is request authentication, not a URL
or a Stripe account key, and must match the gateway's configured signing secret.
The signed gateway resolves its existing active STRIPE method and project
credentials, without a common-backend numeric Stripe-method setting. A caller
that still supplies a method ID must match the gateway's Stripe method. Legacy
unmarked requests keep their existing required-method behaviour.

The switch is read only when choosing a NEW transaction. Retrying the same
request_id resumes its saved provider even after the switch changes. Missing
Stripe configuration/errors never cause automatic second-provider creation.

## Money and lifecycle

Plan prices start in USD. Existing backend coupons apply before the payment
quote. The current quote supports USD and explicit INR using server configuration;
it preserves integer minor amounts and a stable quote hash. The final quoted
amount is what the gateway charges. Do not assume arbitrary currency/UPI support.

One request_id per intended purchase; same ID on retries. Initiated payments
are saved before external creation. Gateway retry protection uses stable
project/tracking keys, immutable fingerprints and a 23-hour cutoff for uncertain
creation. Do not rotate accounts on an unresolved attempt.

Common worker verifies gateway status before provisioning, then locks by tracking
ID, saves provider outcome before assignment, and sends customer success mail only
after QR/ICCID and linked subscription. Unknown purchase outcomes require support
review, not an automatic second provider order. Recovery uses the saved provider
result/order. Failure and email-only recovery must not buy another eSIM.

Webhooks verify signatures and fetch current Stripe state. Duplicate events are
recorded under the payment lock in metadata. Separate flow markers do not
adopt legacy payments. Common polling does not require the browser to return.

See `esim-payments-qa.md` for evidence and release gates. Local fixtures do not
establish production DB locking, certificates, real Stripe eligibility, or device
wallet behavior.
