Payments PendingDriving Payment Integration Tests From a Fully Controllable Simulator When Stripe or Kalshi Owns the Workflow State

Driving Payment Integration Tests From a Fully Controllable Simulator When Stripe or Kalshi Owns the Workflow State

Stateful simulators catch the workflow bugs that mocks and sandboxes miss.

· 8 min read

Integration testing against stateful APIs requires a simulator that remembers prior calls, enforces workflow transitions, and delivers the events your application consumes. For Stripe and Kalshi, realistic end-to-end tests must run from a controlled version of the provider’s authoritative state machine. Native test environments are a useful starting point, while a local simulator with full controls adds deterministic failures, tests that run offline, and state that stays in sync across services.

Why payment APIs are different from ordinary data APIs

Stripe owns the authoritative status of a PaymentIntent, Subscription, Checkout Session, or Invoice. Your application’s domain state must map to that status. The distinction becomes visible when event delivery fails. A PaymentIntent can succeed while your order remains pending because the webhook worker failed. An integration test therefore has to assert the mapping from the provider’s transition to your application’s transition.

Kalshi places similar dependencies outside the application. An order’s fill, partial fill, or rejection depends on market conditions and order-book state, while access depends on its token-bucket rate model. Those conditions live inside Kalshi’s system. Testing only the client’s requests cannot show whether it handles the workflow that follows correctly.

What stateless mocks actually cannot do with payment workflows

A stateless mock can return a customer followed by a subscription that references that customer. The relationships between them depend entirely on matching fixtures, which breaks tests whose outcome depends on the order of calls. Consider creating an order, receiving a 201 with an ID, polling until completion, and then attempting cancellation with an expected 409. A fixed status response makes polling stop at once or run forever, without proving that cancellation became invalid because the order was complete.

Asynchronous behavior exposes the same missing memory. A response-only mock does not generate webhook events because an object changed state, so it leaves the event-driven half of the workflow untested. It also cannot enforce legal transitions based on prior state. Tests may exercise duplicate-event handling in application code, but the mock does not supply an authoritative workflow against which to judge that handling.

Fixtures maintained by hand also fall out of date as APIs change. Kalshi replaced its RPS quota model with token buckets and removed legacy integer-cent price fields. A mock that keeps those interfaces can still pass tests while using an out-of-date contract.

What a stateful simulator must actually control to replicate payment workflows

A stateful simulator must keep objects across calls and enforce the relationships between them. A customer created earlier must remain available later. An order marked complete must reject cancellation with the appropriate conflict response. State changes must also produce outbound events, including a signed payment_intent.succeeded webhook when the simulated PaymentIntent succeeds.

Time must be controllable through synthetic clock advancement so a test can reach subscription trials, renewals, dunning, and cancellations that unfold over days or months. Fault controls must expose latency, 429s, 503s, and malformed responses on demand. The design also needs isolation because state can leak from one scenario into another. Stripe’s documentation says that card-level state can affect later tests that use the same card, so end-to-end scenarios need distinct test cards to stay independent.

How Stripe's native sandbox meets — and falls short of — those requirements

Stripe has isolated sandboxes whose objects do not affect live mode. Teams can create up to five separate sandboxes, with test API keys restricting calls to simulated objects. Its supported scenarios are substantial, including successful payments, declines, fraud, disputes, refunds, 3D Secure, and PIN scenarios. Test clocks make subscription testing particularly capable. They let tests advance through renewals, dunning, and cancellations without waiting for real time to pass.

A sandbox requires network access and credentials, respects rate limits, and cannot be started as a self-contained CI container. Stripe warns against using it for load testing because those limits apply. General sandboxes keep settings and data separate from live mode, but legacy test mode shares settings with it. Stripe also recommends PaymentMethod identifiers such as pm_card_visa in test code rather than card numbers passed directly to server-side API calls, which can create payment card security compliance problems at go-live.

How Kalshi's demo environment handles — and limits — integration testing for prediction-market workflows

Kalshi’s demo environment has mock funds and needs a demo account and demo API keys. It is the sanctioned place to exercise signing, order lifecycle, WebSocket reconnects, and retry logic. That gives integration tests a provider-operated comparison point. It does not make demo market behavior equivalent to production. Kalshi acknowledges that demo prices may differ from real markets, so strategy performance should be validated against historical data.

The demo also remains an external dependency. It needs network access, an account, and credentials rather than running offline within an ephemeral CI job. More importantly, edge cases require conditions the demo does not expose on demand. Malformed responses, partial fills at API boundaries, and signing errors cannot all be scheduled at a chosen workflow step. A local simulator adds that control without replacing the demo’s role as a reference environment.

The cross-API coherence problem that emerges when payment state spans multiple services

A failed Stripe payment rarely ends at the webhook handler. The application may get billing records, apply business rules, send a Resend notification, and log what happened through another service. Every call must refer to the same transaction. Stripe’s sandbox controls its own objects but has no mechanism to synchronize them with Resend or PayPal state.

A simulator catalog might contain 30 customers and a history of charges since November 2024, including one disputed charge and one refunded charge. Companion Slack, Resend, PayPal, and Lob environments must reference the same clients, invoice numbers, and dates. Otherwise, a passing cross-service assertion proves only that unrelated fixtures were compatible with the test. For an agent that books, pays, and confirms across services, inconsistent state also changes the information available at each decision.

Why AI agents and RL environments raise the stakes for stateful payment simulation

An agent’s next action depends on earlier results. In a Stripe billing workflow, event verification, billing-record retrieval, and failure rules must remain deterministic, with the model limited to bounded enrichment tasks. The simulator must preserve the state those steps establish. An LLM timeout must then lead to a deterministic fallback, which requires injecting the timeout at the relevant point.

Reinforcement-learning environments add repeatability and parallel execution requirements. They need server-side state that is deterministic and isolated across many agent instances, whereas a live sandbox introduces externally managed state and rate-limited access. Planner-worker evaluations also need configurable format errors, logic errors, and tool-call failures. Before an agent touches live billing data, tests of the workflows it will face should include duplicate deliveries, delayed events, and malformed model output. Successful tool calls alone do not show that the workflow is safe.

How do you evaluate a local payment simulator for CI and offline workflows?

State must last across calls in a session, illegal transitions must return the right errors, and changes must produce signed events that reach the application’s handler. Faults should be declarative controls. Offline operation should require a single startup command, no external credentials, and isolation within one test job. A suite that silently falls back to a live endpoint is not demonstrating offline correctness.

Realistic pre-seeded customers, charges, disputes, and pending transactions remove repetitive setup, while a published verification methodology shows how the simulator detects divergence before releases. PaymentSimulator v1.0.1 offers a concrete local option covering Stripe, AbacatePay, Mercado Pago, Asaas, and Pagar.me. It runs on localhost port 4001 without signup or API keys, works offline, and supports configurable webhook delays, retries, and failure rates. Its documented in-memory state suits local sessions but does not persist across restarts, a distinction tests must account for.

How a continuously verified, pre-seeded stateful simulator closes the remaining gaps

Statefulness, fidelity, and cross-API coherence are separate requirements. A simulator can remember every call while enforcing yesterday’s contract, or accurately reproduce individual APIs while providing inconsistent records between them. Continuous verification before each release helps keep the contract up to date. Coherent pre-seeded data addresses the relationships that verification of one API cannot establish.

Together, those capabilities support meaningful assertions from the first transaction. Existing charges, disputed and refunded payments, and pending bank debits give tests a service that already has data in it. Shared identifiers let a failed-payment test follow the Stripe event into a Resend notification and a Slack alert. First-class fault controls then make webhook retries, LLM timeout fallbacks, and Kalshi rate-limit handling reproducible offline. Deterministic server-side state also lets agent training scale horizontally across containers that run in parallel.

A concrete workflow: driving a Stripe failed-payment scenario end-to-end from the simulator

The workflow begins with a local simulator seeded with customer and charge records, without external credentials or network access. Its local endpoint and webhook delivery address connect the application to the controlled environment. The test then selects a customer and declares a decline for the next charge attempt using Stripe’s documented pm_card_chargeDeclined PaymentMethod identifier.

When application code attempts the PaymentIntent payment, the simulator enforces the decline, produces the expected StripeCardError with card_declined, and places the PaymentIntent in requires_payment_method. It then delivers a signed payment_intent.payment_failed webhook to the handler. The assertion belongs at the domain boundary. The application must move from payment_pending to payment_failed, rather than merely receive a correctly shaped Stripe object.

The test next injects a duplicate webhook delivery. The handler must deduplicate it without creating a second failure record. Advancing the simulator’s clock then triggers dunning, allowing the test to assert retry behavior and a Resend notification containing the seeded customer and invoice details. Each transition remains under the test’s control. The complete scenario runs in one offline CI job, without live credentials or external rate-limit exposure.

Applying the same pattern to Kalshi order-lifecycle testing

Kalshi tests start with signing, then work through order placement, resting state, execution or cancellation, and the delivery of WebSocket events. The simulator must support the relevant Ed25519 or RSA-PSS/MGF1(SHA256) signing behavior, with Ed25519 the default for new keys. Authentication is only the first dependency to reproduce. Its token-bucket model has five tiers and two independent buckets per tier, with no Retry-After header, so tests need controllable bucket exhaustion to evaluate 429 handling.

Fill control makes order-dependent conflicts reproducible. The test places an order, directs the simulator to mark it filled, attempts cancellation, and asserts the expected 409 response. For trading agents, market and order-book state must also persist through the planning loop. A later decision must use the fill received earlier.

Keeping simulators honest: drift detection and fidelity verification as ongoing practice

A stateful simulator can still become a complex mock that is out of date. Kalshi’s changes through mid-2026 span signing, rate models, field removals, and WebSocket authentication, showing why build-time verification is insufficient. Fidelity must cover behavior as well as schemas. New error codes, changed rate-limit headers, required fields, and token-bucket semantics can invalidate tests even when familiar response objects still parse.

The verification methodology should compare the simulator with the real API before every release and publish fidelity scores. Teams can supplement that process with contract tests defining required transitions and response shapes, failing CI when the simulator diverges internally between releases. The methodology must explain what those scores cover. Published evidence gives security reviewers and compliance auditors a basis for assessing the simulator, while an opaque score leaves the underlying trust question unanswered.

Sources

  1. docs.stripe.com
  2. Test your integration
  3. Testing use cases

More in Payment Flow Testing