# Deploy both payment projects to staging

This guide matches the current native Apple Pay + signed hosted Checkout code.
No production enablement is approved by this document. No real provider orders,
payment requests, schema changes or deployment were executed during implementation.

## 1. Isolate staging

- Record the actual common backend and gateway branches/commits and HTTPS roots.
- Verify each configured DB with `SELECT DATABASE(), @@hostname;` and back it up.
- Use Stripe test keys on the application's EXISTING gateway Stripe account row.
  `stripe_key` is the legacy name for the secret `sk_test_...` credential.
- Use provider sandboxes/mocks and QA email/upload destinations. A Stripe test
  payment can still trigger a REAL TGT/Maya purchase if provider credentials are live.
- Do not run release/provisioning cron jobs against a copied live DB.
- Keep API signing secrets, `.env`, parameters.yml, client secrets and logs out of Git.
- Confirm actual PHP versions and existing vendor dependencies; no composer update
  or new dependency is required by this change.
- Explicitly set ESIM_STRIPE_ENABLED=0 before deploying the simplified router.
  The previous extra routing gates are ignored, so do not rely on their old values.

Review/commit each repository separately before uploading. The earlier voice/SMS
commit does not contain these payment changes. Do not overwrite user edits or
assume the branches in the two repositories have the same name.

## 2. Gateway first

Deploy the reviewed gateway branch with all new project configurations disabled.
There is NO new gateway migration. The adapters reuse existing InnoDB
`transactions` and `transactions_meta`, with separate flow prefixes and short
metadata values. Confirm schema parity, column capacity and lookup indexes on
staging. Do not run historical migrations or recreate/drop shared tables.

Gateway admin prerequisites for the TARGET eSIM project only:

1. Application Active, exact project_code matching common APP_CODE.
2. Existing STRIPE method Active; the signed adapter resolves it in the gateway,
   so no numeric method-ID setting is needed in the common backend.
3. Active unrestricted Stripe restriction for this app (`country=0`, `status=1`).
   Do not loosen another project's country rules for this test.
4. StripeDetails Active for that app/method, with encrypted test secret handled
   by the existing model cast. Preserve APP_KEY and DB_SECRET_ENCRYPTION_KEY.
5. Razorpay fallback must also use staging/test credentials.

Generate one random shared server signing secret (`openssl rand -hex 32`). Put
the same value in common ESIM_GATEWAY_SHARED_SECRET and the gateway project config.
Use real JSON booleans. Merge entries; do not replace existing projects.

```dotenv
STRIPE_APPLE_PAY_APPS='{"TARGET_APP_CODE":{"enabled":false,"checkout_enabled":false,"shared_secret":"REPLACE_RANDOM_SECRET","livemode":false,"currencies":["USD"],"publishable_key":"pk_test_REPLACE","webhook_secret":"whsec_NATIVE","checkout_webhook_secret":"whsec_CHECKOUT","merchant_identifier":"merchant.yourcompany.esim","merchant_country_code":"YOUR_MERCHANT_COUNTRY"}}'
```

Native merchant configuration, entitlements/certificates and Stripe SDK belong
to the iOS app and its Stripe account. Merchant country is NOT the destination
country. Secret/publishable keys must match account and mode; prefix checks alone
cannot prove they belong to the same account. Do not promise UPI merely because
INR is enabled; account/payment-method eligibility must be tested separately.

Clear existing gateway caches using the normal deployment procedure:

```sh
php artisan config:clear
php artisan route:clear
php artisan route:list --path=payment
```

Do not introduce config:cache while unrelated legacy code reads env() at runtime.
Do not run key:generate on an existing deployment.

## 3. Stripe webhooks

Reuse the existing HTTPS Stripe webhook URL. Leave old app processing intact.
Use snapshot API versions compatible with the pinned SDK request version
(`2022-11-15` by default); validate any override independently.

Native:
`https://STAGING_GATEWAY/webhook/stripe-payment`

Events: payment_intent.succeeded, payment_intent.processing,
payment_intent.payment_failed, payment_intent.canceled.

Hosted Checkout:
`https://STAGING_GATEWAY/webhook/stripe-payment`

Events: checkout.session.completed, checkout.session.async_payment_succeeded,
checkout.session.async_payment_failed, checkout.session.expired.

Copy the relevant Stripe endpoint's own whsec into webhook_secret (native) and
checkout_webhook_secret (hosted), not the server shared secret. Both can use the
same endpoint secret if the SAME account/endpoint receives both event families.
If the account already has an endpoint at this URL, reuse it and its signing
secret instead of creating duplicate deliveries with incompatible secrets. Event
metadata selects the configured project, then signature/mode are verified before
processing; metadata by itself never authorizes a payment. Allow raw bodies/Stripe-Signature and server X-Payment-Timestamp /
X-Payment-Signature through the proxy. No staging login may intercept webhooks.
Gateway webhooks update verified payment state; they do NOT buy an eSIM. The
common reconciliation worker retrieves and validates current provider status.

## 4. Common backend

Apply `src/AppBundle/Resources/sql/add_esim_transaction_checkout.sql` to the intended
STAGING DB BEFORE deploying entity changes to any served app. It adds four nullable
columns and two indexes to existing esim_transactions plus disabled settings.
It creates NO table and NO payment method. Existing financial/provisioning/email
fields are reused. Confirm the existing common STRIPE method row is present; do
not change its active flag just for this router. Existing provisioning and voice
feature migrations must already be applied.

Apply to EVERY DB served by the same code deployment: Doctrine reads mapped new
columns even when flags are disabled. Back up and test DDL first. The SQL requires
online DDL and a short metadata-lock wait; stop if unsupported/blocked rather than
using a blocking table copy. Never schema:update --force. If any earlier draft
table contains attempts, pause rollout and reconcile them into the same transaction
rows before enabling this version; do not drop the table or rerun old migrations.

Then deploy the reviewed common code and clear cache as the web account:

```sh
sudo -u www-data php bin/console cache:clear --env=prod --no-debug
```

`--env=prod` is the Symfony runtime configuration, NOT evidence the DB is staging
or production. Verify parameters.yml and selected settings environment explicitly.
Use the existing settings-management procedure; do not insert duplicate constants.

| my_settings key | Staging value |
| --- | --- |
| STRIPE_PAYMENT_API_URL | Existing gateway API prefix, e.g. https://STAGING_GATEWAY/api/; reused, not a new setting |
| ESIM_STRIPE_ENABLED | 0 initially |
| ESIM_GATEWAY_SHARED_SECRET | Same random secret as the gateway project config |
| STRIPE_PAYMENT_SUCCESS | Existing HTTPS success return URL, reused without changing its value |
| STRIPE_PAYMENT_FAILURE | Existing HTTPS cancellation/failure return URL, reused without changing its value |
| PAYMENT_BASE_URL | Existing Razorpay gateway root, unchanged; shared legacy eSIM link transport |

Settings may select production_value based on application environment detection,
not just the CLI --env. Confirm the selected values in the isolated staging DB.
Only ESIM_STRIPE_ENABLED selects the provider. Missing/0 means Razorpay; 1 means
Stripe. This is per application's configured database, not a global default for
all projects. Router/web/Apple Pay/app/user/currency/method-ID settings from older
drafts are no longer read or created. Leave existing unused rows alone during
deployment. Gateway signing remains required for Stripe; it is not a routing flag.
Old frontend callers remain on the old API regardless of this switch. Do not change
shared URL values merely to enable this flow. The new API remains authenticated
and available for Razorpay when Stripe is disabled.

## 5. Enable QA only

1. With ESIM_STRIPE_ENABLED=0, confirm old Razorpay callers AND the new API create
   Razorpay links through the shared legacy transport. No Stripe signing setup is
   required for this disabled state.
2. Configure gateway credentials for the QA project; enabled permits native and
   checkout_enabled permits hosted Checkout. These are gateway account permissions,
   not additional common-backend routing settings. Preserve credentials/status
   access for in-flight attempts after disabling new common initiations.
3. On the isolated staging DB, set ESIM_STRIPE_ENABLED=1 and test both modes:
   native Apple Pay for supported authenticated iOS clients; hosted Checkout for
   other clients (including mobile card payments).
4. There is no QA user/app allowlist in the common router. Scope testing through the
   isolated staging app/database and trusted application identity. Do not change
   STRIPE_PAYMENT_API_URL on a shared live deployment to point at staging.
5. New app calls the new endpoint, processes backend payment_mode, and polls
   the authenticated status endpoint. Old app continues using generatePaymentLink.

Example new API request, using the app's normal JWT/app headers:

```http
POST /api/v220309/esim/payment/initiate
Content-Type: application/json

{
  "plan_id": 12022,
  "request_id": "STAGING-CHECKOUT-UNIQUE-001",
  "currency": "USD",
  "coupon_code": "WELCOME10",
  "client_capabilities": {"apple_pay_available": true}
}
```

Use an actual staging plan/coupon. Generate request_id once PER purchase and
reuse it on retries/double taps. A second intended purchase needs a new ID.
Frontend provider/amount/discount/success flags never authorize a purchase.
INR uses the existing backend USD_TO_INR_RATE quote before final gateway charging;
start with USD, then test INR independently. Currency is not inferred from timezone.
Existing Razorpay uses PAYMENT_BASE_URL unchanged; new Stripe uses the existing
STRIPE_PAYMENT_API_URL prefix. Do not silently substitute one endpoint for the
other if configuration is missing. The common endpoints retain the existing RNcryptor response wrapper; decode it
using the application's normal API client before reading payment_mode/status.

Native Apple Pay requires an authenticated iOS device with apple_pay_available=true.
Other clients receive hosted Checkout when Stripe is enabled. Native Apple Pay needs
an iOS device with wallet support and the app's new Stripe SDK integration. It
opens the native sheet, not Stripe Checkout. Return URLs never establish payment success.

Status: `GET /api/v220309/esim/payment/status?tracking_id=...` with normal app auth.

## 6. Reconciliation worker

Preview only:

```sh
sudo -u www-data php bin/console app:process-esim-gateway-payments --env=prod --no-debug
```

After verifying provider sandbox/mock, QA email destinations and test payments:

```sh
sudo -u www-data php bin/console app:process-esim-gateway-payments --confirm --limit=20 --env=prod --no-debug
```

For continued staging QA, schedule this NEW payment worker every minute using
flock on the intended staging project directory. It is separate from release/
expiry cron and processes only explicitly marked Stripe rows in esim_transactions. Payment is checked
server-side even when the app/browser closes or Stripe webhook is delayed.

Do not enable a recurring worker until sandbox credentials and app scope are
confirmed. Keep worker, shared secrets and status/webhook configs available for
in-flight payments even after disabling new initiations.

## 7. Release gate

Complete `esim-payments-qa.md`. A staging code deploy with flags disabled is not
payment feature approval. Require physical-device Apple Pay, real Stripe test
webhooks, disposable-DB concurrency and legacy Razorpay/Stripe regression evidence
before production enablement. Never switch an unresolved charged attempt to
another provider; reconcile/refund it first. No new app is automatically routed
to Stripe merely by uploading this backend.
