# Testing & subscriptions

> Verify checkouts, declines, webhooks, and subscription changes in Stripe Test mode before accepting a single real customer card.

- Canonical: https://exaspark.ai/docs/testing-stripe-and-webhooks/

## Why webhooks are the source of truth

One of the most important engineering rules in online payments is simple: **never unlock access or mark an order paid solely because the browser reached `/checkout/success`.**

In real production, customers close their phone tab right after tapping Apple Pay, lose subway signal mid-redirect, or type `/checkout/success` straight into the URL bar to probe for free access.

Instead, reliable apps listen for **Stripe webhooks** — cryptographically signed server-to-server events Stripe sends directly to your backend the moment payment settles. Your server verifies Stripe's signature, writes the verified status to your database, and unlocks access even if the customer closed their browser ten seconds earlier.

```text
[Customer Browser] --1. Pays on Stripe Checkout--> [Stripe Servers]
       |                                                  |
       | 2. Redirects to /checkout/success                | 3. Sends signed webhook
       |    (shows "Confirming order...")                 |    (checkout.session.completed)
       v                                                  v
[App Frontend] <---4. Reads verified DB status---- [App Backend]
                                                          |
                                              Verifies webhook signature,
                                              updates orders.status = 'paid'
                                              in Cloud Database
```

## Subscription and payment state machine

Your database should mirror Stripe's lifecycle explicitly so every screen — pricing badges, member portals, and admin dashboards — stays truthful as cards succeed, renew, fail, or refund.

| Database status | Triggering Stripe event | Access rule in your app | Recommended UI state |
| --- | --- | --- | --- |
| `incomplete` | Checkout created, payment not finished | No paid access | Prompt user to complete checkout |
| `paid` | `checkout.session.completed` (one-off) | Unlock order, booking, or download | Show confirmation, receipt link, and details |
| `trialing` | `customer.subscription.created` (with trial) | Grant full tier features | Display trial end date and billing portal link |
| `active` | `invoice.paid` or `customer.subscription.updated` | Grant full tier features | Show active plan, renewal date, and **Manage billing** |
| `past_due` | `invoice.payment_failed` | Optional short grace period while Stripe retries | Show slim alert strip: "Payment failed — update card" |
| `canceled` | `customer.subscription.deleted` | Downgrade cleanly to Free or block paid features | Show expired notice with one-click resubscribe button |
| `refunded` | `charge.refunded` | Revoke access or cancel booking per refund policy | Mark order `refunded` and preserve audit trail |

### Idempotency: handling duplicate webhook deliveries

Stripe guarantees "at-least-once" delivery — if a brief network hiccup delays your server's `200 OK` response, Stripe sends the exact same event again.

To prevent duplicate orders, double stock deductions, or two identical receipt emails, store the processed Stripe event ID (or upsert by unique `stripe_checkout_session_id` / `stripe_subscription_id`) so re-receiving the same webhook safely does nothing twice.

## Testing checkout scenarios with Stripe test cards

Your **Preview** environment stays permanently bound to Stripe **Test mode**, so you can run dozens of realistic checkouts with zero real money moving. Enter any future expiration date (such as `12/30`), any 3-digit CVC (`424`), and any valid postal code.

| Stripe test card number | Scenario simulated | What to verify in your app & Cloud |
| --- | --- | --- |
| `4242 4242 4242 4242` | Standard Visa approval | Order or subscription row appears as `paid` / `active`, access unlocks, receipt triggers |
| `4000 0025 0000 3155` | 3D Secure / SCA authentication challenge | Challenge modal opens; completing it activates access, failing it leaves access locked |
| `4000 0000 0000 0002` | Generic card decline | Stripe shows clean decline message; zero `paid` rows or false bookings created in Cloud |
| `4000 0000 0000 9995` | Insufficient funds decline | Customer stays on checkout to try another card; slot hold or cart remains recoverable |
| `4000 0000 0000 0069` | Expired card decline | Verifies failed-payment copy and retry UX without crashing checkout |

### Verifying every test checkout in Cloud

Never treat a friendly "Thank you!" page as proof that payments work. After every test card run, open **Cloud → Preview** and inspect your tables directly:

- Confirm the `orders`, `bookings`, or `subscriptions` row exists with the exact integer amount (`amount_cents`) and currency.
- Confirm `stripe_customer_id` and `stripe_subscription_id` (or `stripe_checkout_session_id`) are saved so future webhooks match the right user.
- Confirm your declined-card runs left **zero** paid entitlements or wrongly confirmed time slots behind.

## Handling upgrades, downgrades, cancellations, and refunds

Real subscription businesses deal with mid-month plan changes and failed renewals every week. Handle these four transitions intentionally before launch.

### Upgrades and downgrades

When a subscriber switches from Basic to Pro inside the Stripe Customer Portal, Stripe fires `customer.subscription.updated` with the new active price ID. Always map the incoming Stripe price ID to your app's tier (`basic`, `pro`) inside the webhook handler so upgraded features unlock within seconds.

### Cancel at period end vs immediate cancellation

When a subscriber clicks cancel in the Customer Portal, Stripe normally sets `cancel_at_period_end = true` while keeping `status = 'active'` until the paid cycle expires.

Show a calm notice such as *"Your Pro plan remains active until Dec 31"* rather than cutting off access early. Only downgrade the account to Free when `customer.subscription.deleted` fires at the end of the cycle.

### Failed renewals (past_due) and grace periods

Cards expire and banks flag recurring charges unexpectedly. When a renewal fails, Stripe sets the subscription to `past_due` and retries automatically according to your Smart Retries schedule.

Avoid abruptly kicking loyal subscribers out on the first retry failure. Display an unmistakable account banner linking straight to the Stripe Customer Portal to update their card, and lock paid features only if Stripe exhausts retries and transitions the subscription to `canceled` or `unpaid`.

### Refunds and audit trails

Never hard-delete an order row when a refund happens. Update `status` to `refunded`, store `refunded_at`, and keep the row intact so your revenue dashboard, bookkeeping exports, and customer history remain accurate.

> **Example prompt (App):** Harden our Stripe webhook handler with full idempotency (storing processed Stripe event IDs so duplicate deliveries never create duplicate orders or double-send confirmation emails). Handle `checkout.session.completed`, `invoice.paid`, `invoice.payment_failed`, `customer.subscription.updated`, `customer.subscription.deleted`, and `charge.refunded`. Show a non-blocking "Update payment method" banner when `status` is `past_due`, and show the exact end date when `cancel_at_period_end` is true.

## Test-to-Live switchover checklist

When Preview passes every happy path and decline test cleanly, follow this six-step launch sequence to move safely into **Live mode**.

1. **Finish Stripe account verification** — Confirm business identity details, bank payout account, and a recognizable customer card statement descriptor are active inside your Stripe Dashboard.
2. **Switch payment settings from Test to Live** — Toggle Stripe mode to **Live** in your project's payment settings so production uses live Stripe credentials and live webhook verification.
3. **Verify Live products and prices exist** — Stripe keeps Test products separate from Live products. Confirm every Live plan, currency, and billing interval matches what your app expects.
4. **Click Publish** — Push your verified app to Live so production checkout routes connect to Live Stripe.
5. **Run one real-card smoke test on your Live URL** — Complete one genuine purchase using your own personal card, verify the order appears in **Cloud → Live** and your Stripe Live Dashboard, and check that the confirmation email arrives.
6. **Refund your smoke test and confirm sync** — Issue a full refund from Stripe Live Dashboard and confirm your Live database row updates to `refunded` cleanly.

> **Note:** **Preview stays safe after launch.** Even after Live accepts real money, your **Preview** workspace continues running Stripe **Test mode** against your isolated Preview database so future feature iterations never trigger real charges. See [Preview vs Live isolation](https://exaspark.ai/docs/preview-vs-live/).

## Next steps

- [Payments with Stripe](https://exaspark.ai/docs/payments/) — Review 0% ExaSpark platform fees, supported models, and Customer Portal setup.
- [SaaS, booking & store guides](https://exaspark.ai/docs/business-playbooks/) — Copy complete architectures with tables, roles, and Stripe flows.
- [Launch readiness checklist](https://exaspark.ai/docs/production-checklist/) — Run the full pre-launch verification across auth, DNS, SEO, and billing.

## From the blog

- [How online payments work](https://exaspark.ai/blog/how-online-payments-work/) — Plain-English guide to checkout sessions, webhooks, and payouts.
- [How to build a SaaS product](https://exaspark.ai/blog/how-to-build-a-saas-product/) — End-to-end subscription architecture, pricing tiers, and retention.
- [App security basics](https://exaspark.ai/blog/app-security-checklist/) — Verify webhook signatures, role gates, and live keys before launch.
