Copy-paste AI prompt
Stripe Secure
Make a Stripe Checkout integration detect failures, block defective deployments, and keep a verified fallback payment path ready.
- Stripe
- Checkout
- Reliability
You are the senior production engineer responsible for a revenue-critical Stripe Checkout system. Do not merely add monitoring or explain a design. Inspect the repository, implement automatic payment continuity, deploy it safely, and verify the exact live production host. Never claim the system is fixed until every required production check passes. Business requirements: - A failure in the application's primary Checkout Session path must not prevent eligible customers from paying. - Detection alone is insufficient; implement automatic, pre-deployed failover. - Monitoring and recovery must run in the cloud and must not depend on a developer's computer. - Emergency changes are not complete until committed, pushed, deployed from that commit, and verified on production. - Preserve authentication, active-subscription prevention, pricing, discount, affiliate, fulfillment, and webhook rules. - Never print, expose, commit, or return Stripe secret keys, webhook secrets, email credentials, database credentials, or full environment files. - Follow every repository-specific safety instruction before installing, building, creating worktrees, or deploying. 1. Establish deployment and repository truth - Identify the canonical production host, production Git branch, deployment project, and current production deployment. - Record the current production deployment ID and source commit SHA when the platform exposes them. - Inspect Git status before editing and preserve unrelated user changes. - Implement the repair on a commit, push it to the production source branch, and deploy from that exact commit. - After deployment, prove that the production alias points to a deployment containing the repair commit. - Do not deploy an uncommitted local patch as the final fix. - If an emergency local deployment is unavoidable, immediately commit and push the identical source, redeploy from the committed revision, and verify the alias again. - Add a CI or deployment check that rejects production promotion when the deployed source does not include the required checkout guard commit or tests. 2. Inventory every revenue path - Find every authenticated and anonymous checkout API route. - Find every page, modal, button, and component that can start checkout on desktop or mobile. - Inventory every live Stripe Price, Product, coupon, promotion code, billing interval, success URL, cancel URL, Payment Link, and webhook involved. - Identify how user ID, anonymous purchase state, affiliate reference, campaign, interval, and discount data reach fulfillment. - Preserve existing business behavior and document any path that cannot support automatic failover. 3. Eliminate fragile callback configuration - Define one immutable canonical production origin for revenue-critical Stripe callback URLs. - Do not construct live success or cancel URLs from an unvalidated environment variable. - Parse every URL with the URL API; require HTTPS and the exact canonical production host. - Keep development and preview URL behavior explicitly separate from production. - Use a Stripe Price ID, never a Product ID, in `line_items[].price`. - Validate that recurring Prices are active, use the intended currency, and have the expected interval. - Validate one-time Prices, coupons, and promotion codes against their intended amount and offer. 4. Harden primary Checkout Session creation - Generate a cryptographically random request ID for every checkout attempt. - Configure bounded Stripe network retries and a finite timeout. - Create the Checkout Session with canonical success and cancel URLs. - Validate that Stripe returned a non-empty HTTPS URL whose hostname is `checkout.stripe.com` or an explicitly approved Stripe Checkout hostname. - Return a machine-readable result containing the safe checkout URL, request ID, and mode: `primary` or `fallback`. - Never expose the Checkout Session ID publicly unless a protected canary route specifically requires it for immediate expiration. - Log structured safe failure details: request ID, route, interval, safe Price ID, Stripe error type, Stripe error code, Stripe parameter, deployment ID, commit SHA, and timestamp. 5. Build an independent Stripe-hosted fallback - Create and activate one live Stripe Payment Link for every purchasable offer and billing interval. - Pin each fallback to the exact intended live Price; do not dynamically derive the backup from the failing application configuration. - Configure required discounts using verified live promotion codes or coupons. - Preserve safe affiliate or campaign attribution using supported Payment Link query parameters or metadata. - Add explicit metadata needed by the existing webhook to distinguish anonymous purchases, intervals, products, and fulfillment behavior. - Treat fallback Payment Link IDs, expected URLs, Price IDs, and metadata as immutable validated configuration. - Never put secret keys or sensitive customer data into a Payment Link URL. - Verify that each fallback opens a live Stripe-hosted checkout with the correct product, currency, interval, amount, and discount. 6. Implement deterministic automatic failover - Add one shared client checkout launcher and use it from every checkout entry point. - Give the primary API a bounded browser wait, such as eight seconds. - Redirect to the correct fallback Payment Link when the request times out, is unreachable, returns malformed data, returns an invalid Stripe URL, or returns HTTP 5xx. - Also make server checkout routes return the matching fallback when Stripe Session creation throws an infrastructure error. - Do not fail over on HTTP 400 or 401 business and authorization errors, including active subscriptions, invalid selections, or unauthenticated access. - Prevent double redirects and repeated Session creation when a late primary response arrives after browser fallback. - Make the fallback selection deterministic by offer, interval, discount eligibility, and permitted attribution. - Return and log mode `fallback` so the event is measurable. 7. Preserve webhook fulfillment on both paths - Confirm the existing webhook receives `checkout.session.completed` for primary Sessions and Payment Link purchases. - Make identity, anonymous purchase state, affiliate reference, interval, and product derivation work for both modes. - Keep webhook processing idempotent so retries or duplicate events cannot provision twice. - Validate the Stripe signature before processing. - Add tests using representative primary and fallback event fixtures. - Perform a controlled live or Stripe-approved test purchase for each mode when feasible, then confirm the same fulfillment outcome; do not claim this was tested if it was not. 8. Add a production deployment gate - Create a production-only Stripe checkout preflight script. - Before a production deployment can be promoted, retrieve and validate every required primary Price, fallback Payment Link, coupon, and promotion code. - Create a real live-mode canary Checkout Session with the production Price and canonical callbacks. - Verify its URL and immediately expire the canary Session. - Exit nonzero on invalid credentials, Price, discount, URL, Payment Link, metadata, Stripe response, or expiration failure. - Ensure the script itself runs under the project's actual module/runtime configuration; a preflight that cannot execute is a deployment failure. - Run the gate in the remote production builder before the alias can move. - Keep local and preview builds usable without production secrets unless preflight is explicitly enabled. 9. Monitor primary and fallback from the cloud - Add a no-store protected health check that directly tests production Stripe configuration. - Validate account connectivity, canonical callback URLs, all primary Prices, every fallback Payment Link, expected Payment Link metadata, every required promotion code, and webhook prerequisites. - Create and expire a live canary Session to prove the primary path rather than merely retrieving a Price. - When safely authorized, call the exact deployed production checkout API so routing and runtime configuration are tested too. - Report exactly one of three states: `healthy`, `failover`, or `degraded`. - `healthy` means primary and fallback checks pass. - `failover` means the primary path fails but the correct independent fallback remains usable. - `degraded` means customers cannot reliably pay through either path. - Return only safe check names, request IDs, deployment identifiers, and timestamps; never return secrets. 10. Add five-minute stateful alerting - Schedule the monitor on the production cloud platform every five minutes. - Protect the cron endpoint with the platform's cron secret or equivalent authorization. - Persist incident state with a stable unique key. - On transition from healthy to failover, send one urgent alert stating that automatic payment continuity is active and primary repair is required. - On transition to degraded, send a highest-severity total-checkout-outage alert. - On restoration of primary checkout, send one recovery message. - Include safe failed checks, request ID, production deployment ID, commit SHA, and timestamp. - Do not send duplicate alerts every five minutes for the same state. - If alert delivery fails, keep the incident unacknowledged and retry on the next run. - If persistence fails, emit a structured critical event and make the cron invocation fail visibly. - Do not claim cron or email delivery was tested unless an actual authorized invocation and delivered message were observed. 11. Test failures end to end - Unit-test fallback URL validation and safe attribution propagation. - Simulate API network failure, timeout, HTTP 500/503, malformed JSON, missing URL, and a non-Stripe URL; each must choose the correct fallback. - Simulate HTTP 400/401 business-rule failures; none may bypass protections through fallback. - Test every billing interval, discount state, anonymous path, authenticated path, and checkout entry point. - Test that a late primary response cannot override an already selected fallback. - Test health-state transitions: healthy to failover, failover to degraded, degraded to failover, and recovery to healthy. - Test alert deduplication and retry after email failure. - Test webhook idempotency and equivalent fulfillment for primary and fallback purchases. - Run the repository's focused tests, type checks, production build, and Stripe preflight. 12. Deploy and verify the real production site - Deploy through the existing production platform from the pushed repair commit. - Confirm the canonical production alias, deployment ID, source commit SHA, and deployment timestamp. - Verify a live primary monthly checkout returns HTTP 200, mode `primary`, and a valid Stripe Checkout URL. - Verify every active discount and billing interval. - Force or safely simulate a production-like 503 and timeout and prove the browser selects the intended live fallback URL. - Verify every fallback Payment Link remains active and displays the exact expected price and discount. - Verify the health endpoint reports the correct three-state result. - Verify the cron is registered and enabled; distinguish registration from observing a successful invocation. - Verify unauthorized cron requests are rejected. - Confirm logs contain request IDs and deployment provenance without secrets. - Report any untested external dependency honestly. 13. Prevent recurrence - Add regression tests for the exact root cause that caused the incident. - Keep the checkout reliability changes in the production branch; do not leave them only in a temporary worktree or local branch. - Protect required CI checks so a later clean deployment cannot restore the defective path. - Make production promotion depend on successful checkout preflight and automated tests. - Document primary and fallback Stripe resource IDs, ownership, rotation procedure, and an emergency runbook without recording secrets. - Treat changes to canonical URLs, Prices, discounts, Payment Links, checkout routes, webhooks, build commands, or deployment aliases as payment-system changes requiring the full verification suite. - Never claim that checkout can survive a Stripe-wide outage when both paths depend on Stripe; state the remaining dependency explicitly. Final report requirements: - State the incident root cause in one concrete sentence. - State why the previous protection failed or was insufficient. - List the repair commit SHA, pushed branch, production deployment ID, canonical alias, and deployment timestamp. - List the primary and fallback modes verified in production. - Separate what was directly observed from what is merely configured or inferred. - State every remaining risk and untested dependency. - Do not say "fixed," "bulletproof," "never," or "fully tested" unless the evidence supports that exact claim. Do not stop after adding an alert. A monitor that reports lost revenue without preserving the customer's ability to pay is incomplete.
What this prompt covers
- Blocks defective production deployments with a live Stripe preflight.
- Adds deterministic fallback when the primary checkout path fails.
- Checks Prices, discounts, callback URLs, Payment Links, and webhooks.
- Requires failure simulation, cloud monitoring, alerts, and deployment proof.