Payments PendingCI Pipeline Design for Stripe and PayPal Integration Tests

CI Pipeline Design for Stripe and PayPal Integration Tests

Stateless mocks miss payment lifecycle bugs, so test Stripe and PayPal against stateful sandboxes.

· 8 min read

Integration testing against stateful APIs requires an isolated environment that preserves resource state across calls, rejects invalid transitions, and emits webhooks when state changes. For Stripe and PayPal, the pipeline must test payment lifecycles from start to finish as well as the shape of each response. Fast mocks remain useful, but they cannot establish that a payment created in one step reaches the correct outcome in the next.

Why payment integration bugs survive CI: the lifecycle gap

A pipeline mocks POST /v1/payment_intents, asserts 200, and goes green. The first checkout in staging then breaks because the handler never stored the PaymentIntent ID, leaving the next step of the webhook path reading undefined. The request passed its test. The relationship between that request and the later callback did not, because the mock imposed no requirement that the generated ID survive.

This lifecycle gap takes several forms across payment integrations. IDs fail to carry over between calls, mutations report success without sending events, and later operations ignore the resource state left by earlier calls. A refund against an uncaptured charge, which is documented to return an error, can therefore appear successful in a stateless mock. Snapshot tests and mocked fetch calls prove useful local properties, but neither establishes the sequence of transitions. More tests against the same stateless model leave that structural omission intact.

How do you write integration tests for payment APIs where order matters?

The environment must preserve state across sequential calls, guard invalid transitions, and reset to a known baseline between tests. For a capture flow, a PaymentIntent moves through requires_payment_method, requires_confirmation, requires_capture, and succeeded. Each call must act on the resource created earlier and return a response appropriate to its resulting state.

The same requirement extends to events and errors. A mutation must emit the correct webhook without the test having to create the state change that is supposed to cause it. An invalid operation must return the error in its documentation so the test can check the application’s error branch. Stateful integration tests also need their own data and must run one at a time so that one test does not affect another. Stateless stubs remain complementary, providing fast checks before the pipeline reaches these lifecycle obligations.

Diagram: Payment Lifecycle: Four States, One Sequence. Visualizes: The article describes a mandatory state sequence for a PaymentIntent capture flow: requires_payment_method → requires_confirmation → requires_capture → succeeded.

Structural differences between Stripe and PayPal that the pipeline must account for

Stripe and PayPal need different tests even though their payment flows are similar. Stripe’s test environment exposes the same API and dashboard, with test keys covering PaymentIntents, Customers, Subscriptions, and Invoices. It is not identical to production. Stripe’s testing documentation says that test rate limiting is stricter and settlement works differently, and that webhook endpoints, secrets, and delivery are kept separate from live mode. PayPal’s sandbox has historically had broader parity gaps, including failure states without direct equivalents to Stripe’s test cards.

Billing also changes the test surface for each processor. Stripe provides native proration, trials, usage-based billing, and billing anchors, while PayPal integrations require custom implementation for some midcycle changes, per-seat pricing, and hybrid billing models. Their subscription event taxonomies differ, so shared handlers need an abstraction over processor-specific event names. Currency coverage differs as well. Stripe specifies currency at checkout and settles in the configured payout currency, while PayPal tests must account for buyer funding, transaction, and settlement conversion layers. So Stripe tests can rely on test-mode tooling, while PayPal tests need parameters for specific edge cases and production smoke checks earlier on.

Environment setup: secrets, isolation boundaries, and local webhook forwarding

Before tests run, verify three boundaries, namely the processor sandbox, a disposable database, and the webhook delivery path. Store Stripe’s secret as STRIPE_TEST_SECRET_KEY and require the sk_test_ prefix, failing if sk_live_ appears in a CI environment variable. A prefix alone is insufficient. The dashboard, server key, publishable key, and test plan price must belong to the same named sandbox. Prefer that boundary for new integrations because general sandboxes isolate settings and data, while legacy test mode shares some settings with live mode.

For PayPal, create Business and Personal sandbox accounts and select the sandbox through its base URL and credentials or SDK initialization. Use a disposable database that has no real customer records, start dummy accounts that have no paid access, and turn off outgoing side effects or capture them in a test-only tool. Every run needs fresh starting state because PayPal periodically cleans sandbox data.

For local Stripe forwarding, run stripe listen --forward-to localhost:3000/api/webhooks/stripe in the background. Allow a startup delay before the first trigger command. Use the listener’s signing secret and configure hosted destinations in Workbench within the named sandbox. Verify signatures before processing payloads, with Stripe using HMAC-SHA256. For PayPal, keep the Webhooks Simulator for REST webhook events distinct from the IPN Simulator for Instant Payment Notifications.

Test card and sandbox coverage: mapping scenarios to both processors

Stripe’s matrix needs more than one successful card. Use 4242 4242 4242 4242 for success, 4000 0000 0000 9995 for insufficient funds, and 4000 0000 0000 0002 for a generic decline. Exercise lost_card with 4000 0000 0000 9987, fraudulent blocking with 4100 0000 0000 0019, and expiry with 4000 0000 0000 0069. Test inputs select distinct handler branches. In test mode, use a future expiry date and any three-digit CVV, or four digits for American Express.

Authentication requires a separate set of cases. Card 4000 0027 6000 3184 needs 3D Secure on every transaction, and the result depends on whether the challenge is completed. Card 4000 0082 6000 3178 authenticates successfully and then declines with insufficient_funds, while 4000 0000 0000 3220 requires 3DS 2 authentication and then succeeds. Card 4000 0025 0000 3155 needs authentication unless it is set up for future payments. The SCA modal is a browser iframe, requiring Playwright or Cypress, and Stripe Elements inputs require iframe-aware targeting such as frame_locator.

PayPal tests should cover payments, refunds, and disputes through its sandbox accounts, with specific cases for currency combinations and the narrower set of subscription paths. Billing Plans and Agreements tests must also allow for limits on how often plans can be created. Recovery is a lifecycle test for both processors. After a payment is declined, it must be possible to update the payment method and retry. For delayed Stripe payments, a completed Checkout session can still be unpaid, so access must wait for confirmation and the application must show a useful state if confirmation never comes.

Webhook handling in CI: idempotency, ordering, and the stateful trap

Stripe may deliver the same event more than once. The handler must store event.id and skip an event already handled. In CI, deliver the same event ID twice and assert one fulfillment action, one access grant, and one database write. Repeat with concurrent delivery if the application processes webhooks in parallel. For PayPal, duplicate the same notification through the appropriate simulator and assert one fulfillment outcome.

Exercise both orders of invoice.paid and customer.subscription.updated rather than assuming payment notification always arrives first. Subscription tests must also cover invoice.payment_failed and customer.subscription.deleted, and tests for asynchronous Checkout need checkout.session.async_payment_succeeded and checkout.session.async_payment_failed. Success alone is an incomplete state machine. Tests must reach processing, requires_action, and failed paths, with signature verification remaining a gate before processing. Enforce high line and branch coverage on webhook handlers, checkout creation, and token verification, and investigate flaky webhook tests as possible state leakage that retries can mask.

Stage matrix: what runs at each CI phase and why

Diagram: Four-Phase CI Pipeline at a Glance. Visualizes: The article defines four distinct CI phases with specific triggers, tools, and goals.

Phase 1 runs on pull requests with stateless mocks, no live API interaction, and a target of roughly 20 seconds. It checks request shape, parameter construction, and branching on predefined responses. This is the fast feedback layer. Before the branch enters Phase 2, a separate workflow receipt must prove resource creation, mutation, retrieval of the same ID, and the webhook branch caused by the mutation.

Phase 2 exercises staging integration through the real test-mode API, active Stripe CLI forwarding, and PayPal’s Webhooks Simulator. Run isolated stateful tests serially through create, confirm, capture, and refund. Stripe CLI JSON fixtures describe sequences of API calls and work with stripe trigger to reproduce flows without manual intervention or account tokens in scripts. PayPal fixtures must establish their own starting resources for each run.

Phase 3 is a small smoke check of the production deployment. It verifies endpoint reachability and the correct environment’s keys without card numbers or complete payment flows, failing on key-prefix mismatches.

Phase 4 runs full browser E2E tests manually, on a schedule, or as a release gate, outside the per-pull-request workflow. Playwright or Cypress exercises card interaction, 3D Secure, decline recovery, and asynchronous settlement. This phase checks the user-facing path that API-only stages cannot reach.

Fault injection: testing the error paths that only appear under specific conditions

Fault injection must hit specific points in a payment lifecycle. After a slow response or timeout, the resource should be in a clear state, and a 429 should lead to scheduled backoff that delays further requests. Malformed responses must lead to an error that the application handles without a crash or silent failure. Processor 5xx responses should reach retry logic. A dropped connection must not be treated as proof that the transaction completed.

Retries need their own payment-safety assertion. Repeat a mutation with the same idempotency key after a network failure and verify that it returns the original response and preserves a single resource. Separately, exercise authentication abandonment and a webhook arriving while the application restarts. The latter must either be processed or fail in a way that invokes the provider’s retry mechanism.

Stateful simulators make these faults conditional on resource state. They can inject a resource-dependent 429 at capture after earlier steps succeeded. Include at least one composed fault in each payment flow, such as rate limiting combined with a webhook delivery timeout.

API drift and simulator fidelity: keeping the CI environment honest over time

A simulator can keep state correctly and still use an old API contract. If its PaymentIntent response schema diverges from the real API, passing lifecycle tests no longer establish compatibility. Statefulness alone does not establish lasting fidelity. The opening failure and this drift failure can produce the same green pipeline, but their causes differ, with one omitting the lifecycle and the other modeling an obsolete contract.

Run a drift job on a schedule to compare the model’s responses with the live API’s OpenAPI specification. Fail the build on new required fields and warn on new optional fields. Apply this check to mocks as well as simulators. Coverage shows which branches in the model ran, while fidelity verification checks that the model still meets the API requirements. Both belong in the CI gate.

Assembling the full pipeline: a checklist for Stripe and PayPal CI readiness

Evaluate readiness by the evidence required to advance between stages. Environment admission should establish sandbox identity, disposable data, matching webhook secrets, and a listener ready before triggers begin. Lifecycle admission should provide a trace through one resource’s creation, mutation, retrieval, and resulting event. Invalid transitions must have evidence too. For PayPal, that trace must start with state created by the current run.

Webhook readiness requires duplicate and reordered delivery results. Fault readiness requires timeout handling, rate-limit recovery, idempotent mutation retries, and a composed-failure result for each flow. Browser tests must show that the authentication and recovery interactions that HTTP tests cannot exercise work. Scheduled fidelity checks must also be part of the evidence for a release.

More in Payment Flow Testing