Testing & subscriptions

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

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 statusTriggering Stripe eventAccess rule in your appRecommended UI state
incompleteCheckout created, payment not finishedNo paid accessPrompt user to complete checkout
paidcheckout.session.completed (one-off)Unlock order, booking, or downloadShow confirmation, receipt link, and details
trialingcustomer.subscription.created (with trial)Grant full tier featuresDisplay trial end date and billing portal link
activeinvoice.paid or customer.subscription.updatedGrant full tier featuresShow active plan, renewal date, and Manage billing
past_dueinvoice.payment_failedOptional short grace period while Stripe retriesShow slim alert strip: "Payment failed — update card"
canceledcustomer.subscription.deletedDowngrade cleanly to Free or block paid featuresShow expired notice with one-click resubscribe button
refundedcharge.refundedRevoke access or cancel booking per refund policyMark 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 numberScenario simulatedWhat to verify in your app & Cloud
4242 4242 4242 4242Standard Visa approvalOrder or subscription row appears as paid / active, access unlocks, receipt triggers
4000 0025 0000 31553D Secure / SCA authentication challengeChallenge modal opens; completing it activates access, failing it leaves access locked
4000 0000 0000 0002Generic card declineStripe shows clean decline message; zero paid rows or false bookings created in Cloud
4000 0000 0000 9995Insufficient funds declineCustomer stays on checkout to try another card; slot hold or cart remains recoverable
4000 0000 0000 0069Expired card declineVerifies 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.

Starter 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.

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog