SSafeStripe Docs0.3.0 · Node.js 22.19+

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Start here

Build payments with SafeStripe

SafeStripe helps your Node.js application remember what it asked Stripe to do, verify incoming payment events, and finish background work without repeating the same business action.

Use it with Express or Next.js. Start locally with SQLite, then choose PostgreSQL, MongoDB or Firebase Cloud Firestore when you deploy. The Stripe SDK is included in the package installation.

Start with one working payment

If this is your first integration, follow these pages in order:

  1. Install and configure. Understand the three credentials and choose a database.
  2. Make your first payment. Run the sample locally without Docker.
  3. Connect Express or Next.js. Add the endpoints to your own application.
  4. Add a payment form. Use hosted Checkout or the ready-made React component.
  5. Deploy your integration. Keep web requests short and run a durable worker.

Already have a Stripe integration? Read what SafeStripe solves, database adapters, and upgrading an existing integration.

How a payment reaches your application

A customer presses Pay. Your server checks their identity and selects the price from your own catalog. SafeStripe saves a stable operation identity before asking Stripe to create Checkout. The customer pays using Stripe's payment fields. Stripe then sends a signed webhook to your server. A worker verifies the current payment and updates your order inside a database transaction.

The success page is a receipt for the browser journey. The verified webhook and stored order decide whether to deliver the product.

Choose your path

You want to… Read
Try payments without installing a database server Local quickstart
Use PostgreSQL, MongoDB, Firebase or SQLite Storage setup
Add Express routes or Next.js Route Handlers Framework integration
Style a payment form without wiring every Stripe component Payment UI
Create customers, refunds, subscriptions and invoices Recipes
Review real payment, refund and renewal test coverage Payment lifecycle verification
Design a larger production system Enterprise architecture
Learn Dashboard workflows and financial operations Operations workbook
Maintain or publish this package Maintainer guide

What is included

Durable operation records, request fingerprints, account and tenant scoping, signed webhook receivers, persistent jobs, bounded retries, dead-job recovery, transactional effects, an outbox, Express and Next.js adapters, and a React Checkout component.

Your application supplies authentication, resource ownership, approved prices, business rules and worker hosting. SafeStripe makes these boundaries explicit. It does not claim to make every payment integration secure automatically, and this release has no published large-scale throughput benchmark.

The package is ESM and server-side code requires Node.js 22.19 or later. Only safestripe/react belongs in a client component. The SQLite adapter uses Node's built-in SQLite API, which emits an experimental warning on Node 22.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Start here

Release readiness

Reviewed 7 October 2026. SafeStripe 0.3.0 is published on npm as an evaluation preview. The public sandbox is available for evaluation. There is enough working software to run a pilot, but the evidence does not support recommending this release for unattended production payments at a large company.

What the project does

Stripe processes payments and manages billing. Your application still needs to decide who can buy, what they owe, when to grant access, and how to recover after a server or database failure.

SafeStripe stores the history of that work in your database. It wraps selected Stripe commands, receives verified webhooks, and gives workers a recoverable queue. Within a transaction, your handler can update application state, record that a business effect happened, and schedule a downstream notification together.

For example, an online course sells a $40 enrollment:

  1. Your server loads the approved order and calls SafeStripe with checkout:order-184.
  2. SafeStripe records the operation and creates the Stripe Checkout Session with a stable idempotency key.
  3. If the response disappears, the same operation can be retried with the same terms. Changing the amount under that identity is rejected.
  4. After payment, the endpoint verifies and stores Stripe's webhook before acknowledging it.
  5. A worker checks the stored order and payment, then commits enrollment and one receipt intent with an effect key tied to that order.
  6. If the worker stops before commit, the database rolls back. Another worker can recover the job after its lease expires. A repeated event does not create another committed enrollment under the same effect key.

The email or downstream service may still receive a delivery twice. It needs its own durable deduplication keyed by the receipt identity. SafeStripe provides at-least-once outbox delivery, not a universal exactly-once network guarantee.

Problems it saves an application team from rebuilding

Failure SafeStripe mechanism Application responsibility
A refund succeeds remotely, but the server times out Durable operation identity, immutable terms, Stripe idempotency and a bounded automatic retry window Keep the operation ID and history; investigate unresolved operations after the cutoff
A webhook receives HTTP 200, then the process crashes Signature verification and database admission before acknowledgment Operate the database and worker; configure the signing secret and endpoint
A worker dies while holding work Expiring leases and ownership checks on completion Monitor recovery, tune lease duration and use bounded handlers
Different events describe the same paid order A transactional business-effect guard Choose the business key and validate the payment against the order
An order update commits, but its notification is lost State, effect and outbox intent can share a database transaction Deliver the outbox and make the receiver idempotent

These failures are real integration concerns. Stripe documents duplicate delivery, retries and event ordering in its webhook guide, and remote request replay in Idempotent requests. Stripe's idempotency key does not, by itself, make your enrollment, inventory, receipt or entitlement update idempotent.

SafeStripe is most useful when an application has fulfillment or billing state to coordinate. A simple hosted Payment Link with no local fulfillment may not need this library. A company with an established payment orchestration system should compare these mechanisms with its existing controls before adopting another layer.

Current evidence

Area Observed state Practical limit
Public demo Vercel frontend, Render Express backend and Firestore workspaces are deployed Temporary evaluation service; no production availability commitment
Browser payment form Hosted and embedded Checkout completed fake-card payments with signed Firestore receipts. The embedded form recovered from an initial loading failure; decline/retry, one 3DS challenge and reload restoration passed Dated browser observations cover selected cards and deployments
Published-package lifecycle All twelve selected journeys passed at 09:32 UTC on 7 October: cards, refund replay, ten signed duplicates, delayed ACH outcomes and subscription renewal/recovery/cancellation. Account verification and cleanup passed Actual npm 0.3.0 consumer on backend 8b01d90; bank creation/confirmation used SDK fixtures. Live payments, capture, disputes and every method are outside this run
Dedicated service suite Protected CI passed six account-verified API checks on clean revision 5f06e28 The report covers customer response loss, Checkout, refund, subscription and portal. Repeat on the exact eventual release tag
Failure tests and CI Actual child workers are killed with SIGKILL. Node 22/24, PostgreSQL recovery and MongoDB/Firestore conformance passed for the strengthened lifecycle runner Tested invariants under stated conditions; not a hosted failover or enterprise capacity certification
Storage adapters PostgreSQL, MongoDB replica sets and Firestore have transaction-facing adapters and CI conformance checks; the public lifecycle used actual Cloud Firestore Validate production IAM, indexes, connection budgets and backup recovery in your deployment
Benchmarks SQLite baseline and nine measured PostgreSQL repetitions retained zero duplicate effects. Failed four/eight-lane warm-ups and recovery are retained in the report Store measurements on stated machines; no HTTP, payment or multi-host capacity claim
npm Public safestripe@0.3.0 passed a normal clean install, integrity, exports, types and selected optional-peer imports No CI provenance or verified signed release tag on this first publication. Import checks do not prove connectivity or capacity
Source and documentation License notices, architecture, ADRs, guides, runbooks, security policy and automated workflows are available Documentation and automated scans are not independent review

The verification record retains dated results. The separate sandbox repository records its browser walkthrough and deployment checks. The newer lifecycle suite is separate from the first walkthrough. Catalog, tax, Connect and other workflows marked API-only or unconfigured in that walkthrough have not become passing lifecycle tests.

Required before recommending a production release

  1. Verify the application's required payment journeys. The public lifecycle suite passed twelve selected journeys against the published package. The embedded form observation separately covers loading recovery, one decline, one 3DS challenge and signed receipts. These do not cover every country, payment method, capture policy or dispute outcome. Add the scenarios the adopting application actually needs.
  2. Pass CI on the release commit. Keep the actual PostgreSQL process tests and MongoDB/Firestore conformance enabled. Investigate flaky failures; do not mark skipped provider tests as passes.
  3. Keep account-verified Stripe release checks current. The protected six-service suite and twelve-journey deployed-consumer suite passed on their recorded revisions. Eight lifecycle development failures and the earlier restricted-key permission failure remain visible. Repeat the relevant protected workflows on the exact eventual tag and reviewed deployment. A passing earlier runner does not verify a later package build.
  4. Complete the release supply chain. The npm naming transition and clean registry check are complete. The demo now pins the exact npm release; its transition passed Node 22/24, the pruned production build and Firestore emulator checks before merging. Configure the trusted publisher and use the release workflow for a subsequent unpublished version with a verified signed tag, provenance, SBOM and checksums. npm versions are immutable; 0.3.0 cannot be republished to add provenance.
  5. Review the security boundaries independently. Focus on authorization, tenant isolation, credential handling, replay permissions, ownership and restore behavior. Turn findings into reproducible issues and fixes.
  6. Validate the intended production infrastructure. Measure database contention and queue recovery with representative workloads. Test migrations, rolling deployments, Stripe rate limits, retries and database outages. Exercise backup restoration before financial writes resume. Alert on queue age, dead jobs, review-state operations and outbox failures.
  7. Run unfamiliar-developer onboarding. Have developers follow the published quickstart without coaching. Record where they get stuck and improve the guide. Do not claim outside adoption, audits or performance that have not happened.

A company can evaluate the preview in a test environment now. A production pilot needs a named owner, selected workflows, limits, rollback and a review of the company's authorization and fulfillment code. Millions of users is a capacity target to test against; it is not a property established by the package name or architecture diagram.

Staying connected to the public sandbox

The browser keeps an HttpOnly, Secure session cookie. Reloading or returning from Checkout uses that cookie to reopen the same workspace while its one-hour access window remains valid. Test secret keys stay encrypted on the server and are not placed in browser storage.

If the server is temporarily unreachable, choose Retry saved connection. The retry reads the existing workspace; it does not submit your keys or create another set of Stripe records. If setup was interrupted, resume that workspace. Missing, expired or deleted sessions return to the connection form.

Reloads do not extend the expiry. Disconnect deletes the demo workspace; Stripe test records remain in your account. The online demo does not provide permanent credential storage. Companies integrating the library manage their own long-lived credentials, authentication and database; they do not use the public visitor session as production infrastructure.

Scope and trust

SafeStripe does not replace Stripe, application authentication, a fraud policy, tax registration, accounting, reconciliation procedures or database operations. The default request gate limits one process, not every server sharing an account. It also does not promise that every Stripe feature is available to every account.

Verification statements describe observed tests and their limits. Keep the release evidence, issue history and known limitations available when reviewing an integration.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Start here

Reliability contracts and evidence

SafeStripe coordinates Stripe with your database. Neither system can commit a transaction on behalf of the other. The library stores enough identity and progress to make retries deliberate, preserve work after process failure and surface outcomes that need review.

These contracts apply to supported SafeStripe methods and transactions. Calls made directly through the Stripe SDK, external work inside a retried transaction callback, lost database history and incorrect application authorization are outside them.

Operation, inbox, worker and outbox boundaries

1. One operation keeps its identity

Problem: a server times out after Stripe accepts a request. A new request identity could create a second charge or refund.

Mechanism: the caller supplies a stable business operation ID. SafeStripe binds its scope, kind and parameter fingerprint in durable storage, derives a stable Stripe key, and retrieves the recorded resource on completed retries. Changed terms conflict. Unresolved older operations enter review instead of being retried indefinitely.

Evidence: tests/operations.test.ts, tests/storage.test.ts and tests/scenarios.test.ts exercise competing claims, parameter conflicts, successful replay and the recovery cutoff. The mocked SDK fixture does not establish real remote outcomes. The protected service report separately verifies one remote customer after response loss and replay. The public lifecycle suite checks refund replay through the deployed npm consumer. Dedicated sandbox work is tracked in issue 3.

Boundary: Stripe's key retention is finite. Retain local operation history, keep the same ID on retries, and review ambiguous outcomes before the configured cutoff. A restored database can be missing writes Stripe already accepted. Reconcile before reopening payment writes.

2. Admission precedes acknowledgment

Problem: acknowledging a webhook before storing it lets a process crash erase the work.

Mechanism: the receiver verifies the original bytes, signature, mode, account scope and API version, then awaits durable admission. Storage failure propagates to the HTTP adapter. Authentic unsupported event types may be explicitly ignored; they are not admitted work.

Evidence: receiver and adapter tests reject invalid events and persistence failures. Storage conformance exercises atomic admission. Process recovery tests start with a committed inbox job.

Boundary: process durability relies on the database's durability configuration. This does not promise survival of database loss, destructive retention, or restoring an old backup.

3. Work ownership is recoverable

Problem: a worker claims a job and disappears. Another worker must recover it, while the original owner must not overwrite the new result.

Mechanism: claims have expirations and ownership tokens. Completion checks state, lease and token in the same transaction as handler writes. Reclaiming changes ownership. Exhausted work moves to a dead state for reviewed replay.

Evidence: tests/chaos/recovery.test.ts kills real child processes after claim and during the effect transaction, then recovers with a second process. It also checks stale completion and graceful SIGTERM. PostgreSQL runs require a real disposable database; local SQLite runs use one active worker at a time.

Boundary: eventual progress requires available storage, a running worker and an unexhausted retry policy. Lease expiry does not stop code already executing or fence arbitrary external services.

4. One committed effect per business key

Problem: different events can describe the same business outcome. Deduplicating only event IDs cannot prevent duplicate fulfillment.

Mechanism: effectOnce stores the business effect guard and the associated billing-record writes inside a serializable transaction. Every event for the same outcome must use the same scoped business key.

Evidence: the chaos suite admits repeated deliveries and distinct event IDs for one order, then asserts one fulfillment and one guard. PostgreSQL CI adds twenty competing worker processes.

Boundary: handler execution can repeat. Only the guarded transaction's committed effects are deduplicated. Do not send email, make Stripe mutations or call external services inside the transaction callback. The portable context writes SafeStripe records; unrelated application tables/documents do not automatically join its transaction.

5. State and downstream intent commit together

Problem: state commits but the process crashes before sending an email or downstream request.

Mechanism: an outbox intent shares the state/effect transaction. A separate dispatcher sends it using a stable delivery key. Delivery is at least once.

Evidence: the process suite kills a sender after a simulated receiver durably accepts delivery but before sender completion. Recovery delivers again; the receiver's own guard prevents a second effect. Both the repeated delivery and the single recipient effect are asserted.

Boundary: the receiver must honor the delivery key or provide an equivalent business constraint. SafeStripe cannot make an arbitrary third-party endpoint exactly once.

What a crash changes

Crash checkpoints and recovery decisions

Failure point Required response
Before inbox commit Return failure; Stripe can retry
After inbox commit, before acknowledgment A repeat finds the admitted job
After claim, before effect commit Recover after lease expiry; uncommitted work rolls back
After effect/outbox commit Preserve the result; reprocessing uses the effect guard
After recipient acceptance, before delivery acknowledgment Retry the same delivery key; recipient deduplicates
After database restore Suspend mutations and reconcile gaps against Stripe

Read the ADRs, security boundaries and verification record. Tests demonstrate the stated scenarios; they are not an independent security audit or a throughput guarantee.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Start here

Try SafeStripe

Start with one paid checkout and its saved receipt. You do not need to explore every billing feature to find out whether the library fits your application.

Try it in the browser

The online sandbox runs Express, the published safestripe@0.3.0 package and Cloud Firestore. There is nothing to install.

  1. Open a dedicated Stripe sandbox and copy its test secret and matching publishable key. Enter keys only in Connect sandbox, never in a public issue or recording. A test secret still grants access to that sandbox's data and settings.
  2. Connect and let automatic setup create the test customer, prices and signed webhook destination. If setup stops, use Resume setup in the same workspace. Do not create another workspace to retry an interrupted setup.
  3. Choose Hosted checkout and open the payment page. Use 4242 4242 4242 4242, a future expiry and any valid three-digit CVC. These are Stripe test card details, not a real card.
  4. Return to the workspace. Wait for the payment checks and verified receipt. A redirect or a connected badge alone does not establish payment.
  5. Use Your test records and cleanup in the connection dialog when finished. Financial history remains visible in Stripe; cleanup is not an erasure of a financial record.

The demo creates real records in your Stripe sandbox. It accepts test keys only. Separate Stripe products can require account configuration or additional key permissions; automatic setup does not enable Connect, Identity, Tax or every payment method.

Install it in your own application

Use Node.js 22.19 or newer. Start in a new application folder:

bash
npm install safestripe@0.3.0

The Stripe server SDK installs with SafeStripe. Install only the storage driver and framework your application uses:

Application choice Add to your installation
Local SQLite No separate database driver
PostgreSQL npm install pg
MongoDB replica set npm install mongodb
Cloud Firestore npm install @google-cloud/firestore
Express npm install express express-rate-limit
Next.js Use your existing Next.js application
React payment form Follow the optional browser dependencies in Payment UI

Follow Getting started for the client and storage configuration, then Framework integration for your routes and worker. Your application supplies authentication, customer ownership and server-approved prices. Do not copy an unrestricted authorization function into a deployed billing endpoint.

Run the complete local example

For a working website, webhook endpoint and worker together, follow Make your first payment. Its Express and Next.js examples share the same local workflow and use a SQLite file by default. No Docker or database server is required.

This is a repository tutorial with example tooling. Installing the library in a separate application uses the normal npm install command above; consumers do not need the repository's npm ci --ignore-scripts command.

What to check before adopting it

  • A retry keeps its operation ID and immutable terms.
  • A paid checkout reaches a signed, persisted webhook and one committed receipt.
  • A failed payment does not grant access.
  • Your chosen database and worker deployment pass your integration's recovery tests.

Read the recorded lifecycle results, the reliability contracts and release readiness. The current release is an evaluation preview. Twelve verified sandbox journeys do not establish every company's payment policy, security posture or production capacity.

The onboarding target is five minutes to a first verified receipt once prerequisites are available. Independent timed runs have not yet established that target. If you get stuck, report the exact step, the version and what you expected. Leave keys and private account details out of the report.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Start here

Install and configure

Start with a Node.js application, a Stripe sandbox, and a place to store billing records. You can use a local file while learning. You do not need Docker.

Install the package

Choose the command for your database. npm installs SafeStripe's built JavaScript, TypeScript declarations and Stripe dependencies together.

bash
npm install safestripe

SQLite is built into supported Node.js versions. No database service or extra database driver is required.

bash
npm install safestripe pg

Use a PostgreSQL connection string from your existing database or a hosted provider. pg is an optional peer. Install it when your application selects PostgreSQL.

bash
npm install safestripe mongodb

Use MongoDB Atlas or a replica set. A standalone MongoDB server does not provide the transactions this adapter needs.

bash
npm install safestripe @google-cloud/firestore

This adapter uses Cloud Firestore, through its server SDK. Firebase Realtime Database is a different product and is not supported by this adapter.

Do not install the stripe package separately just to use SafeStripe. It is a pinned runtime dependency and npm installs it automatically. PostgreSQL and browser UI libraries are optional peers, so a core-only installation does not include them. For SafeCheckout, also install @stripe/react-stripe-js, @stripe/stripe-js, react and react-dom; an existing React/Next.js app may already have React. Express apps install Express as their web framework. The runnable Express examples also use express-rate-limit; install it if you copy those examples. It is optional and is not loaded by the core or webhook adapter.

Understand your credentials

Setting Where it belongs When you need it
STRIPE_SECRET_KEY (sk_test_… or rk_test_…) Server environment only Creating and retrieving Stripe records
Publishable key (pk_test_…) Browser configuration Embedded Stripe payment fields; hosted Checkout does not need it
STRIPE_WEBHOOK_SECRET (whsec_…) Server environment only Verifying Stripe webhook messages
STRIPE_ACCOUNT_ID (acct_…) Server configuration, optional Explicit scope when account discovery is unavailable
Database credentials Server environment only A hosted database; SQLite does not need them

A signing secret belongs to one webhook destination. The Stripe CLI prints the secret for local forwarding; a deployed destination has its own secret. Do not interchange them.

createSafeStripe() normally discovers your account ID from your secret key at startup. You do not have to copy it manually. Internally, the account ID still matters: it keeps records from different accounts and environments separate. A restricted key might lack permission to retrieve the account. In that case, supply accountId from your trusted deployment configuration.

For Stripe Connect, configure a distinct connectedAccountId from an authorized server-side account mapping. Never trust a browser-provided account ID. Organization keys and thin events are outside the current receiver's contract.

Configure your environment

An .env file is a local text file containing settings. Add it to .gitignore. On a hosting platform, enter the same values in its environment settings or secret manager.

dotenv
STRIPE_SECRET_KEY=your_sandbox_secret_key
STRIPE_WEBHOOK_SECRET=your_local_signing_secret
APP_ORIGIN=http://localhost:3000
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=your_sandbox_publishable_key

Only the publishable key gets the NEXT_PUBLIC_ prefix. A variable with that prefix can be included in browser JavaScript. Never use it for a secret API key, signing secret, database password or service-account credential.

Create the server client once

The following is an application integration pattern. billingPolicy is your application's authorization function: it must check the signed-in tenant, resource ownership, approved prices and the requested action. The local quickstart includes a complete, deliberately restricted learning policy.

ts
import { createSafeStripe } from 'safestripe';
import { sqliteStorage } from 'safestripe/storage/sqlite';
import { billingPolicy } from './billing-policy.js';

const storage = await sqliteStorage({ filename: './.data/billing.sqlite' });

export const billing = await createSafeStripe({
  secretKey: process.env.STRIPE_SECRET_KEY!,
  storage,
  appOrigin: 'http://localhost:3000',
  allowLocalhost: true,
  authorize: billingPolicy,
});

Keep this instance in server code and reuse it. The factory resolves the account once and sets the reviewed Stripe API version. A deployed application uses an HTTPS appOrigin and shared storage. The factory rejects a live key with SQLite.

Three identities you will use

Every wrapped write takes an actor with three fields:

ts
const actor = {
  tenantId: signedInUser.organizationId,
  actorId: signedInUser.id,
  operationId: `checkout:${order.id}`,
};

tenantId is the business or customer workspace. actorId identifies the person or service allowed to act. operationId identifies one intended business action. Derive them on the server.

Keep the operation ID unchanged when retrying the same action. Use a new one for a new purchase or a changed business instruction. SafeStripe rejects different inputs under an existing identity instead of silently creating a second payment.

Before continuing

You should now know where your keys belong, which database you will use, and which part of your app decides who may pay. Next, run a sandbox payment or choose a storage adapter.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Start here

Make your first payment

This tutorial runs the included sample on your computer. It uses SQLite, a small database file. You do not install Docker or a database server.

The sample sells one server-configured product to one sandbox customer. Its local sign-in token makes the first test reproducible. It refuses production mode; a deployed app needs your real authentication and order policy.

1. Prepare the sample

Open a terminal in the repository folder. Install dependencies, run the offline checks, and create your private settings file:

bash
npm ci --ignore-scripts
npm test
cp .env.example .env

npm test uses synthetic Stripe events and local test data. It does not contact Stripe. Passing this step proves local behavior, not a real payment.

Create a sandbox customer and a product with a one-time price in the Stripe Dashboard. Copy the cus_… and price_… IDs into .env. Use a price greater than zero for this tutorial; its fulfillment check deliberately requires payment_status=paid.

Generate a local sign-in token:

bash
node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"

Paste the result into DEMO_TOKEN. This is a password for the sample, not a Stripe credential.

dotenv
BILLING_DATABASE=sqlite
SQLITE_PATH=./.data/billing.sqlite
STRIPE_SECRET_KEY=your_sandbox_secret_key
STRIPE_WEBHOOK_SECRET=filled_in_the_next_step
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=your_sandbox_publishable_key
APP_ORIGIN=http://localhost:3000
DEMO_TOKEN=your_generated_local_token
DEMO_CUSTOMER_ID=your_sandbox_customer_id
DEMO_PRICE_ID=your_sandbox_price_id
DEMO_ORDER_ID=demo-order-001

Leave STRIPE_ACCOUNT_ID empty for automatic discovery. Keep all credentials out of screenshots, recordings and Git commits.

2. Forward Stripe events to your computer

Install the Stripe CLI, then open a separate terminal:

bash
stripe login
stripe listen   --events checkout.session.completed,checkout.session.async_payment_succeeded   --forward-to localhost:3000/api/webhooks/stripe

Copy the printed whsec_… secret into .env as STRIPE_WEBHOOK_SECRET. Keep the listener running. The API key lets your app talk to Stripe; the listener lets Stripe's events reach your local app.

Make sure the sandbox's snapshot events use the API version listed in the documentation footer: 2026-08-26.dahlia. The receiver rejects another event shape/version so schema changes cannot silently enter fulfillment. See Stripe's local webhook testing guide.

3. Start your framework

bash
npm run dev:express

The Express starter runs the web server and webhook worker in one process. Keep it open. Its source is the local Express example.

In another terminal, use your demo token to create hosted Checkout:

bash
curl http://localhost:3000/api/checkout   -H "Authorization: Bearer YOUR_DEMO_TOKEN"   -H "Content-Type: application/json"   -d '{"uiMode":"hosted"}'

Open the url from the response in your browser. The token can appear in shell history; this is a disposable local token. Do not put your Stripe secret key in this command.

bash
npm run dev:next

In a second terminal, start the worker against the same local SQLite file:

bash
npm run worker

Open http://localhost:3000. Enter your DEMO_TOKEN and press Open secure checkout. The page uses SafeCheckout to render the Stripe payment form. Its server route selects the price; the browser only requests a Checkout UI mode.

Use the Node.js runtime. The database and secret key stay in Route Handlers; the publishable key goes to the client component.

4. Complete a test payment

For a successful sandbox card payment, use Stripe's test card 4242 4242 4242 4242, a future expiry and any valid three-digit CVC. Never use a real card for this tutorial. See Stripe test payment methods for authentication, declines and asynchronous methods.

The expected sequence is: Checkout opens, payment completes, the CLI forwards the signed event, the receiver saves it, and the worker marks the stored order fulfilled after checking the current Session, customer, reference, line item and quantity.

Read the order status:

bash
curl http://localhost:3000/api/order   -H "Authorization: Bearer YOUR_DEMO_TOKEN"

The final response should be {"state":"fulfilled"}. pending means the webhook or worker has not finished. The success page alone is not proof that fulfillment happened. The sample records a receipt intent in the outbox; it does not send an email.

5. Test the behaviors that matter

Test What to do Expected result
Same request twice Repeat the Checkout request with the same order ID and UI mode The same Session ID is returned
Changed request Switch hosted/custom without changing the order ID PAYLOAD_CONFLICT; choose a new order for a new flow
Restart Stop and restart the app without removing .data Operation history and order state remain
Invalid webhook POST unsigned JSON to the webhook endpoint A rejection; no order update
Worker interruption Stop the Next.js worker, complete payment, restart it Pending work is picked up from storage
Wrong token Send an incorrect demo token 403
Another payment Set a new DEMO_ORDER_ID, restart and pay again A distinct Session and order

The automated tests also exercise duplicate webhook delivery, competing workers, transaction rollback and stale ownership. Use the advanced testing runbook for failure injection.

If something does not work

The form cannot load: check the publishable key, sandbox mode, returned clientSecret, and browser network access to Stripe.js. A hosted Session cannot initialize the custom form.

The webhook returns an error: check the CLI signing secret, accepted event types, snapshot API version and raw-body middleware order. Restart the app after changing .env.

The order stays pending: check that the worker is running and uses the same file or database as the web server. An event created by stripe trigger normally belongs to a fixture Session, not your stored order. Pay through this application's Checkout for the end-to-end test.

Account discovery fails: check the key and account-read permission. For a restricted key, set the trusted STRIPE_ACCOUNT_ID explicitly.

SQLite prints an experimental warning: this is Node.js reporting the status of its built-in SQLite API. It is expected on Node 22. SQLite here is a development option, not your Vercel database.

When the local payment works, move to your own Express or Next.js application.

Request limits in the local example

The local Express server permits 60 authenticated-route requests per IP each minute, across Checkout and order reads. This protects the sign-in check before it runs. A 429 response means wait for the reset rather than create a new operation. Webhook admission has a separate path so these visitor limits do not block Stripe retries. The example uses an in-memory limiter with no trusted proxy; a public deployment needs a shared limiter and an explicit proxy policy. If copying the Express server into another project, also install express-rate-limit. Core users and Next.js integrations do not need that dependency.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Build your app

Connect Express or Next.js

Both frameworks use the same billing client and storage adapter. The differences are where you read authentication, how you preserve the webhook body, and where your worker runs.

If you are learning, run the complete local sample first. The snippets on this page are integration patterns for an application that already has users and orders. Imports from ./auth, ./orders, ./billing-policy and ./billing-handlers are application modules you implement, not hidden SafeStripe exports.

1. Set up storage and your billing client

Choose the complete PostgreSQL or MongoDB module in database setup and save it as billing-storage.ts. SQLite works for the local sample; use a shared service for deployment.

Create billing.ts in server-only code. Cache the promise so concurrent requests reuse one initialization. Clear a failed initialization so a transient account lookup failure does not disable the instance forever.

ts
import { createSafeStripe } from 'safestripe';
import { storage } from './billing-storage.js';
import { billingPolicy } from './billing-policy.js';

let pending: ReturnType<typeof createSafeStripe> | undefined;

export function getBilling() {
  return (pending ??= createSafeStripe({
    secretKey: process.env.STRIPE_SECRET_KEY!,
    storage,
    appOrigin: process.env.APP_ORIGIN!,
    authorize: billingPolicy,
  }).catch((error) => {
    pending = undefined;
    throw error;
  }));
}

In a Next.js application, add import 'server-only' to this module. Use allowLocalhost: true only for a sandbox origin such as http://localhost:3000. Set APP_ORIGIN to your trusted HTTPS deployment origin in production. Never derive payment return URLs from an untrusted Host header.

2. Define your authorization boundary

Your authentication helper must verify a real session or signed token. Return a server-derived user ID and tenant ID; do not copy either from a request body. Your order loader accepts that tenant and returns only an order it owns. Your billing policy must authorize the action, customer, price and relevant commercial parameters again, including on a replay.

An order used below has id, tenantId, stripeCustomerId, stripePriceId and quantity. It is loaded from your database. The example uses a fixed payment mode; recurring prices need a subscription workflow and a separate entitlement policy.

Cookies require your normal CSRF protection. The snippets enforce a fixed same-origin browser request as one part of that boundary. Machine-to-machine clients need their own authenticated API route and policy; do not weaken the browser route to accommodate them.

3. Create Checkout on the server

Only accept an order ID from the browser. Choose the customer, price, quantity and return origin on the server. Reject expired, cancelled, already fulfilled or otherwise ineligible orders in your loader/policy. Serialize changes to commercial terms before starting Checkout; an operation fingerprint is not a stock reservation system.

ts
import express from 'express';
import { publicError } from 'safestripe';
import { getBilling } from './billing.js';
import { requireUser } from './auth.js';
import { loadPayableOrder, bindCheckout } from './orders.js';

export const checkoutRouter = express.Router();

checkoutRouter.post('/checkout', async (req, res) => {
  res.setHeader('Cache-Control', 'no-store');
  try {
    if (req.get('origin') !== process.env.APP_ORIGIN) {
      res.status(403).json({ error: 'ORIGIN_NOT_ALLOWED' });
      return;
    }
    const user = await requireUser(req);
    const order = await loadPayableOrder(user.tenantId, req.body.orderId);
    const billing = await getBilling();
    const session = await billing.createCheckout(
      {
        tenantId: user.tenantId,
        actorId: user.id,
        operationId: `checkout:${order.id}`,
      },
      {
        customerId: order.stripeCustomerId,
        mode: 'payment',
        items: [{ priceId: order.stripePriceId, quantity: order.quantity }],
        reference: order.id,
      },
    );
    await bindCheckout(order, session.id);
    res.json({ url: session.url });
  } catch (error) {
    const result = publicError(error);
    res.status(result.status).json(result.body);
  }
});

Mount express.json({ limit: '8kb' }) before this router, but after the webhook route. loadPayableOrder must validate the input type, length and ownership before using it. The complete local Express source demonstrates request validation and safe error responses.

ts
// app/api/checkout/route.ts
import { publicError } from 'safestripe';
import { boundedBody } from 'safestripe/next';
import { getBilling } from '@/lib/billing';
import { requireUser } from '@/lib/auth';
import { loadPayableOrder, bindCheckout } from '@/lib/orders';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  const headers = { 'Cache-Control': 'no-store' };
  try {
    if (request.headers.get('origin') !== process.env.APP_ORIGIN) {
      return Response.json({ error: 'ORIGIN_NOT_ALLOWED' }, { status: 403, headers });
    }
    const user = await requireUser(request);
    const input = JSON.parse((await boundedBody(request, 8192)).toString());
    const order = await loadPayableOrder(user.tenantId, input.orderId);
    const billing = await getBilling();
    const session = await billing.createCheckout(
      {
        tenantId: user.tenantId,
        actorId: user.id,
        operationId: `checkout:${order.id}`,
      },
      {
        customerId: order.stripeCustomerId,
        mode: 'payment',
        items: [{ priceId: order.stripePriceId, quantity: order.quantity }],
        reference: order.id,
      },
    );
    await bindCheckout(order, session.id);
    return Response.json({ url: session.url }, { headers });
  } catch (error) {
    if (error instanceof SyntaxError) {
      return Response.json({ error: 'INVALID_JSON' }, { status: 400, headers });
    }
    const result = publicError(error);
    return Response.json(result.body, { status: result.status, headers });
  }
}

boundedBody prevents an unbounded JSON read. Your order loader still validates the parsed object's structure and requested order ID. Never place this route in the Edge runtime. The complete Next.js sample route includes the restricted local policy.

bindCheckout is an application transaction: attach the returned Session ID to the stored, immutable commercial terms only if no conflicting binding exists. Do not return a successful response before the binding is durable. A webhook can arrive first; its worker must retry an unknown binding, then alert/reconcile if the binding never appears. The local runtime demonstrates the storage transaction and verification steps.

On the browser, navigate to the returned hosted Checkout URL after a successful authenticated response. For the embedded component, create the Session with uiMode: 'custom' and return only its ID and client secret to the authorized customer. See payment UI.

4. Accept signed webhooks

Create a receiver from your cached billing client. Event types must match the handlers your worker actually implements.

ts
const receiver = billing.webhooks({
  signingSecrets: [process.env.STRIPE_WEBHOOK_SECRET!],
  eventTypes: [
    'checkout.session.completed',
    'checkout.session.async_payment_succeeded',
  ],
});
ts
import express from 'express';
import { expressWebhook } from 'safestripe/express';

const app = express();
app.post(
  '/api/webhooks/stripe',
  express.raw({
    type: 'application/json',
    inflate: false,
    limit: receiver.maxBytes,
  }),
  expressWebhook(receiver),
);
app.use(express.json({ limit: '8kb' }));

Mount this route before any JSON parser or body-transforming middleware. Stripe signs the original bytes, not a parsed and re-serialized object.

ts
// app/api/webhooks/stripe/route.ts
import { nextWebhook } from 'safestripe/next';
import { getBilling } from '@/lib/billing';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  const billing = await getBilling();
  const receiver = billing.webhooks({
    signingSecrets: [process.env.STRIPE_WEBHOOK_SECRET!],
    eventTypes: [
      'checkout.session.completed',
      'checkout.session.async_payment_succeeded',
    ],
  });
  return nextWebhook(receiver)(request);
}

Pass the untouched Request. Do not call request.json() first. The adapter streams the body with a byte limit, verifies its signature and persists the event before acknowledging it.

5. Run a worker

A worker is a long-running process that repeatedly takes one stored event, applies your handler and records the result. It is separate from the customer's HTTP request.

ts
import { runWorkerLoop } from 'safestripe';
import { getBilling } from './billing.js';
import { paymentHandlers } from './billing-handlers.js';

const billing = await getBilling();
const worker = billing.worker(paymentHandlers);
const stop = new AbortController();

process.once('SIGTERM', () => stop.abort());
process.once('SIGINT', () => stop.abort());

await runWorkerLoop(() => worker.runOnce(), {
  signal: stop.signal,
  concurrency: 4,
  pollIntervalMs: 1000,
});

paymentHandlers must retrieve the current Stripe resource, check its stored order binding and terms, and commit an effect through the supplied BillingTransaction. The complete sample handler checks customer, reference, mode, price, quantity, completion and payment state. Do not replace those checks with event.type === 'checkout.session.completed' alone.

Stop accepting new work on shutdown, drain the loop, then close your database client. Keep a handler comfortably within its lease. There is no automatic lease heartbeat.

6. Use Next.js on Vercel

Choose hosted PostgreSQL or MongoDB Atlas and initialize a small shared pool/client at module scope. Configure the Stripe and database secrets separately for Preview and Production. Register the deployed HTTPS webhook URL with Stripe and use that destination's signing secret. Keep production Preview builds away from the live account.

Vercel runs the web routes. Run the continuous worker on a service that supports long-running Node.js processes, against the same database and Stripe scope. Do not start runWorkerLoop inside a Route Handler or leave a promise running after returning the response.

A scheduled, authenticated, bounded worker endpoint can suit low-volume jobs, but you must design its scheduling, time budget, retry and overlapping-run behavior. It is not provided as a magic unlimited background process. Check your hosting plan's function duration and connection limits.

Never place the SQLite file in /tmp or your deployed application directory and treat it as persistent billing storage. Read deployment for the full release checklist.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Build your app

Choose a database

SafeStripe stores operation history, pending webhooks, outbox messages, effect guards and application billing records. These records must survive restarts. A process-local Map cannot reliably prevent duplicate work across servers.

You can keep the rest of your application in any database. For atomic fulfillment, put the billing state and outbox intent inside the chosen SafeStripe transaction. If your main application data lives elsewhere, deliver an idempotent outbox message to update it. Two unrelated databases cannot share one local transaction.

Supported adapters

Database Best starting point Required extra package Hosting constraint
SQLite Local learning and tests None Persistent file on one computer; sandbox factory only
PostgreSQL Existing SQL applications and durable workers pg A shared PostgreSQL service
MongoDB Applications already using MongoDB mongodb Atlas or a replica set with transaction support
Cloud Firestore Firebase applications using Firestore @google-cloud/firestore Server credentials, indexes and IAM permissions

These adapters share a transaction protocol and the same operation/job implementation. They do not have identical throughput, costs or operational behavior. In particular, the portable queue uses bounded candidate reads and transactional claims; it is not a substitute for a measured large-scale message broker.

Create your storage

These snippets are complete storage modules. Use one, then pass storage to createSafeStripe. Environment values come from your own deployment. MongoDB and Firestore drivers are optional; importing the package's main entry point does not load them.

ts
import { sqliteStorage } from 'safestripe/storage/sqlite';

export const storage = await sqliteStorage({
  filename: './.data/billing.sqlite',
});

The adapter creates the directory and tables. It uses WAL journaling, full synchronous writes and serialized transactions within each connection. A small local web process and worker may share the same file on the same computer. Keep it off network filesystems. Never delete the file to recover an uncertain payment.

Node.js 22.19+ is required. Node 22 labels node:sqlite experimental. Use shared storage for live or distributed applications; createSafeStripe refuses live keys with this adapter.

ts
import { Pool } from 'pg';
import { postgresStorage } from 'safestripe/storage/postgres';

export const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 5,
  connectionTimeoutMillis: 5000,
  statement_timeout: 15000,
  idle_in_transaction_session_timeout: 20000,
});

pool.on('error', () => {
  console.error('Billing database connection interrupted');
});

export const storage = await postgresStorage({ db: pool });

Before first startup, run migrations with a deployment role that can change the schema:

bash
DATABASE_URL="your_database_connection_string" npx safestripe migrate

For a disposable development database, postgresStorage({ db: pool, migrate: true }) can apply migrations automatically. Production request handlers should not require schema-change privileges.

The portable adapter uses serializable transactions with bounded retries. Keep pool sizes small per process and calculate the total across replicas. Use your provider's documented TLS configuration; do not disable certificate validation to make a connection succeed.

ts
import { MongoClient } from 'mongodb';
import { mongoStorage } from 'safestripe/storage/mongodb';

export const client = new MongoClient(process.env.MONGODB_URI!, {
  maxPoolSize: 5,
  serverSelectionTimeoutMS: 5000,
});
await client.connect();

export const storage = await mongoStorage({
  client,
  database: 'billing',
});

Atlas avoids running MongoDB on your computer. Initialization verifies that transactions are available and creates the queue index. A standalone server is rejected. The database user needs access to this database and permission to create the index during setup.

The adapter uses snapshot transactions, majority write concern and forced writes to read dependencies. This last step prevents concurrent handlers from making conflicting decisions using stale business records. It adds write cost, so measure hot-order contention before scaling worker counts. Keep transaction callbacks short and do not perform parallel operations inside them.

ts
import { Firestore } from '@google-cloud/firestore';
import { firestoreStorage } from 'safestripe/storage/firestore';

export const firestore = new Firestore({
  projectId: process.env.GOOGLE_CLOUD_PROJECT,
});

export const storage = await firestoreStorage({ db: firestore });

Use Application Default Credentials on supported infrastructure or your platform's documented workload identity setup. For local development with a service-account file, GOOGLE_APPLICATION_CREDENTIALS points to that private file. Never put the file in Git or browser code. On Vercel, configure an appropriate server credential strategy; a Firebase browser configuration object is not sufficient.

The default collection is safestripe_records. The worker query needs a composite index with scope, queue, and dueAt in ascending order. The supplied Firestore index configuration also exempts the record value map from indexing so large event payloads do not create unnecessary index entries. Deploy it through your Firebase project, or create the equivalent indexes in its console. Missing indexes produce a setup error containing a creation link. Firestore index documentation.

Deny browser access to this collection. The server SDK uses IAM; Firebase Security Rules do not restrict a privileged server credential. Grant the service only the project access it needs. Existing broad rules must not override your intended denial through another matching allow rule.

text
match /safestripe_records/{document=**} {
  allow read, write: if false;
}

Transactions read before writing. SafeStripe buffers writes until the callback finishes so get after set still works in your callback. Firestore may repeat the callback after contention; never send emails or charge a payment inside it.

Update billing data atomically

Use these methods inside a worker's transaction, or call storage.transaction(billing.scopeId, callback) for an application operation. Collection and record IDs accept letters, digits, underscores, dots, colons and hyphens, up to 200 characters. The record contents must be finite JSON values; convert dates to strings and large integer amounts to decimal strings where necessary.

ts
await storage.transaction(billing.scopeId, async (tx) => {
  const order = await tx.get<{ state: string }>('orders', 'order-123');
  if (!order) throw new Error('Order is missing');

  await tx.effectOnce('tenant-1:order-123:fulfill', async (effect) => {
    await effect.set('orders', 'order-123', { ...order, state: 'fulfilled' });
    await effect.enqueue('tenant-1:order-123:receipt', 'order.confirmed', {
      orderId: 'order-123',
    });
  });
});

Call this only after your handler has verified the authorized payment. effectOnce prevents the same effect key from committing twice in this storage scope. The record update, effect guard and outbox intent commit together. A thrown error rolls them all back.

Tenant isolation is still an application rule. The storage scope separates Stripe accounts and modes; it does not automatically authorize a tenant. Include the tenant in application record/effect IDs when IDs are not globally unique, and verify ownership before calling storage methods. Do not expose storage.read, recovery methods or the raw database to public routes.

A transaction can be retried. Use only its data methods and bounded, repeatable reads. Do not call billing.createRefund, send email, grant access in another database or call a fulfillment provider from inside it. Put the intended external work in the outbox instead.

Limits, lifetime and cleanup

The portable API limits an individual JSON payload to 512,000 bytes. The configured webhook receiver leaves space for stored metadata. Keep effects small, and remain within your provider's overall transaction size, duration and write limits. Large invoices or unusual events may need a different reviewed ingestion strategy; do not simply remove the payload bound.

storage.close() closes SQLite. For PostgreSQL, MongoDB and Firestore, the application owns the client it supplied: close it during process shutdown with pool.end(), client.close() or firestore.terminate(). Do not close it after every serverless request.

There is no automatic retention job. Operations and effects carry duplicate-prevention history; deleting them can allow an old action to run again. Define retention, backups and audit access before pruning. Firestore polling consumes reads even when there is little work; use an appropriate polling interval and watch cost.

Do not switch a running application to a new empty database. Read the migration guide first.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Build your app

Add a payment form

The browser UI is optional. Install its dependencies in your frontend application:

sh
npm install safestripe @stripe/react-stripe-js @stripe/stripe-js react react-dom

Hosted Checkout does not require these browser packages.

Use hosted Checkout for the shortest integration. Stripe supplies the page, payment fields and supported payment methods. Your app creates a Session and redirects to its URL.

Use SafeCheckout when the payment form belongs inside your own React or Next.js page. It supplies the Stripe provider, Payment Element, submit button, loading state, duplicate-click guard and result message. You can place an order summary inside it and customize its appearance.

Create a custom Checkout Session

On your authenticated server endpoint, use the same order validation and binding as the framework guide, with uiMode: 'custom':

ts
const session = await billing.createCheckout(actor, {
  customerId: order.stripeCustomerId,
  mode: 'payment',
  uiMode: 'custom',
  items: [{ priceId: order.stripePriceId, quantity: order.quantity }],
  reference: order.id,
});

await bindCheckout(order, session.id);
return Response.json(
  { id: session.id, clientSecret: session.client_secret },
  { headers: { 'Cache-Control': 'no-store' } },
);

uiMode: 'custom' is SafeStripe's option for an on-page payment form. On the pinned Stripe API, SafeStripe sends ui_mode: 'elements'. The older Stripe value custom is rejected. The server fixes return_url from your configured origin and does not allow browser-controlled redirect destinations or payment-method overrides. A hosted Session and an Elements Session are different operation inputs; use a new order/action identity if you deliberately start a different flow.

A Checkout client secret is intended for the authorized customer's payment form. Do not put it in logs, analytics, query strings, public HTML caches or another customer's response. It is different from your account's secret API key.

Wrap your order summary

The following client component receives a Session from your authenticated endpoint or an authenticated, uncached server page. It never receives the account secret key.

tsx
'use client';

import { SafeCheckout } from 'safestripe/react';

export function OrderPayment({
  session,
}: {
  session: { id: string; clientSecret: string };
}) {
  return (
    <SafeCheckout
      key={session.id}
      publishableKey={process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!}
      clientSecret={session.clientSecret}
      buttonLabel="Pay for my order"
      appearance={{
        theme: 'stripe',
        variables: {
          colorPrimary: '#635bff',
          borderRadius: '12px',
          fontFamily: 'system-ui, sans-serif',
        },
      }}
    >
      <div>
        <p>YOUR ORDER</p>
        <h2>Workshop ticket</h2>
        <p>Your payment is confirmed by our server before delivery.</p>
      </div>
    </SafeCheckout>
  );
}

The wrapper displays your children above the secure payment form. It does not turn ordinary HTML inputs into Stripe inputs. Card details are collected inside Stripe's hosted fields, which keeps them out of your server and application event handlers. Stripe.js is loaded from Stripe through its official loader. Stripe React reference.

In an Express application with a React frontend, use the same component. Pass your build tool's publishable-key variable as publishableKey; NEXT_PUBLIC_ is a Next.js convention, not a Stripe requirement. A plain Express application without React should start with hosted Checkout.

What the component handles

Behavior What happens
Form initialization Loads Stripe.js and initializes the custom Checkout provider
Payment methods Renders Stripe's Payment Element with an accordion layout
Double-click An immediate ref guard prevents overlapping confirmation calls
Validation or decline Displays the message returned by Stripe's confirmation result
Redirect method / authentication Stripe manages the required flow using the server-configured return URL
Successful submission Shows a confirmation-in-progress message and invokes optional onComplete
New Session Supply key={session.id} to remount the provider
Slow or failed loading After 30 seconds, offers a retry that reopens the same Session; no new payment is created
Field readiness Enables payment only after Stripe's Payment Element reports ready

The component uses Checkout Sessions with Stripe's CheckoutElementsProvider; it does not create a PaymentIntent from the browser. Dynamic payment methods remain controlled by Stripe and your account configuration.

Use onLoadStateChange to keep the surrounding page accurate. It receives loading, ready, slow or error; it never receives a key or an upstream error message. ready means the fields have loaded, not that a payment succeeded. A late response can still finish loading after the slow notice. Retry payment form remounts the provider with the original client secret and does not call your create-checkout endpoint.

If the form stays on “Loading secure payment form…”, check connectivity, browser extensions and your Content Security Policy. Allow Stripe's documented script, connection and frame origins, including Checkout and Link when enabled. Do not disable CSP or expose an account secret key to solve a loading failure. See Stripe's security guide. If the Session has expired, check the order's current state on your server before deliberately starting another purchase.

Customize the container

Use className or style to change the outer card. Use appearance for the Stripe fields. They are separate because Stripe fields are isolated from your document's CSS.

tsx
<SafeCheckout
  key={session.id}
  publishableKey={publishableKey}
  clientSecret={session.clientSecret}
  className="checkout-card"
  style={{ maxWidth: 560, boxShadow: 'none' }}
  appearance={{
    theme: 'night',
    variables: { colorPrimary: '#a5b4fc', borderRadius: '8px' },
  }}
  buttonLabel="Subscribe securely"
/>;

The default outer card is light; set its background and text color too when choosing a dark field theme. buttonLabel changes the submit label. The current component does not expose every Stripe field or the entire Checkout UI: use the official React Stripe components directly if you need advanced shipping, tax-ID, contact or express-wallet layouts. SafeStripe's server and storage APIs still apply.

Fulfill through the server

onComplete is for UI updates. It is not authority to send a product, grant subscription access or record revenue. The browser can close before it fires, and a client-side callback is not a trusted payment record.

Show a pending screen and query an authenticated order-status endpoint. The webhook worker should verify the Session's current payment state and authorized terms, then update your stored order. Asynchronous payment methods can complete later. Handle the relevant success and failure events for the methods you offer.

Test before deployment

Test loading, a valid sandbox payment, decline, authentication, a duplicate click, browser refresh, redirect return and an interrupted webhook worker. Test keyboard focus, visible labels and screen-reader announcements in your application. A unit test or successful build cannot replace a real browser payment test with your account's enabled methods.

The Next.js example includes an authenticated fetch and a complete local payment form. The local quickstart explains how to run it.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Build your app

Common billing recipes

These examples run on the server after authentication and authorization. They assume billing is the result of createSafeStripe, actor identifies the signed-in tenant and operator, and IDs/amounts come from your trusted records. The framework guide shows where to call them.

Use one stable operation ID for each intended write. A workflow with several writes needs several IDs. Store those IDs before executing the workflow so a restart can resume the same steps.

Create a customer once

ts
const customer = await billing.createCustomer(
  { ...actor, operationId: `customer:${user.id}` },
  { email: user.email, name: user.name },
);

Save the returned customer ID in your tenant/customer mapping. Retrying the same identity returns the recorded resource. Changing the email under the same create identity is a conflict; a customer-profile update is a separate operation. Customer creation itself has no existing customer resource to check, so the authorizer must still enforce who may create a customer and which tenant receives it.

Send a customer to the billing portal

ts
const portal = await billing.createPortalSession(actor, customerId);
// Return this URL only to the authenticated owner, with Cache-Control: no-store.

Configure the portal features in Stripe first. The method authorizes access each time and creates a fresh short-lived Session with a fixed /billing return path. Do not store the portal URL as a permanent account link or cache it publicly.

Create a partial refund

ts
const refund = await billing.createRefund(
  { ...actor, operationId: `refund:${refundRequest.id}` },
  {
    paymentIntentId: refundRequest.paymentIntentId,
    amount: refundRequest.amountMinor,
    reason: 'requested_by_customer',
  },
);

amount is an integer in the currency's minor unit. Do not use floating-point arithmetic to calculate it. Your refund policy must check ownership, permission, currency, remaining refundable amount, previous refunds and approval limits. A successful create response is not the entire refund lifecycle; reconcile its status and relevant events. Do not generate a new refund ID because a response timed out.

Build an invoice in separate durable steps

ts
const draft = await billing.createInvoice(
  { ...actor, operationId: `invoice:${invoiceRequest.id}:create` },
  { customerId, daysUntilDue: 14 },
);

await billing.addInvoiceItem(
  { ...actor, operationId: `invoice:${invoiceRequest.id}:line-1` },
  {
    customerId,
    invoiceId: draft.id,
    priceId,
    quantity: 1,
  },
);

const finalized = await billing.finalizeInvoice(
  { ...actor, operationId: `invoice:${invoiceRequest.id}:finalize` },
  { invoiceId: draft.id },
);

The draft excludes unrelated pending invoice items and has automatic advancement disabled. Review line items, customer, tax treatment and collection policy before finalizing. Finalization in this wrapper keeps auto_advance: false; it does not automatically email the invoice or collect funds. Sending/collection needs a separately authorized workflow. Finalized invoice corrections may require credit notes or other accounting steps rather than editing the original amount.

Start a subscription through Checkout

ts
const session = await billing.createCheckout(
  { ...actor, operationId: `subscription-checkout:${signup.id}` },
  {
    customerId,
    mode: 'subscription',
    items: [{ priceId: recurringPriceId, quantity: 1 }],
    reference: signup.id,
  },
);

Use a recurring Price. Store the Session/customer/subscription mapping and process subscription and invoice events. Access is a business entitlement: define how active, trialing, past-due, paused, unpaid and cancelled subscriptions affect the service. The first Checkout completion is not an enduring entitlement policy.

createSubscription also exists for advanced server-led workflows. It uses default_incomplete; it does not automatically complete authentication or guarantee that the first invoice was paid. Ordinary customer sign-up should usually start with Checkout.

Preview a plan change, then apply the same terms

ts
const change = {
  subscriptionId,
  itemId,
  priceId: newPriceId,
  quantity: 10,
  prorationDate: quote.prorationDate,
};

const preview = await billing.previewSubscriptionChange(actor, change);

Store the exact quote inputs and show the invoice preview to the customer. On a separate confirmation request, re-authorize ownership and confirm the quote is still applicable before applying those inputs:

ts
const updated = await billing.updateSubscription(
  { ...actor, operationId: `plan-change:${quote.id}` },
  quote.change,
);

The update verifies that the item belongs to the subscription, uses the quoted timestamp and requests an invoice with pending_if_incomplete. A pending update is not proof that the customer has paid for the new entitlement. Handle its completion or expiry. Define your quote lifetime and concurrent subscription-edit policy in the application.

Cancel at the end of the period

ts
const subscription = await billing.cancelSubscriptionAtPeriodEnd(
  { ...actor, operationId: `cancellation:${cancellation.id}` },
  { subscriptionId },
);

This schedules cancellation; it does not immediately revoke access, issue a refund or erase the customer. Show the resulting state and let your entitlement rules determine the access end date.

Deliver a saved outbox message

A transaction records a message; an outbox worker performs the external action after that transaction commits.

ts
import { dispatchOutboxOnce, runWorkerLoop } from 'safestripe';

await runWorkerLoop(
  () =>
    dispatchOutboxOnce(billing.storage.jobs, billing.scopeId, async (message) => {
      await notifications.deliver({
        type: message.type,
        payload: message.payload,
        idempotencyKey: message.idempotencyKey,
      });
    }),
  { signal: shutdown.signal, concurrency: 2 },
);

notifications is your own destination client. Its delivery operation must deduplicate the supplied key. Delivery is at least once: a process can die after the destination accepts a message but before the local job is marked complete. SafeStripe cannot make an arbitrary remote email or fulfillment API transactional.

Recover a failed task

Inspect a job by its queue, scope and event/message ID. Authenticate the operator and authorize the affected account before calling administrative methods:

ts
const job = await billing.storage.jobs.inspect('webhook', billing.scopeId, eventId);

if (job?.state === 'dead') {
  await billing.storage.jobs.replayDead(
    'webhook',
    billing.scopeId,
    eventId,
    operator.id,
    'Corrected the order mapping and verified the Stripe Session.',
  );
}

Correct the underlying cause before replaying. resolveForReview handles an ambiguous operation only after you have verified the matching remote Stripe resource. Neither recovery method performs business investigation for you. Keep them out of public customer endpoints.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Build your app

Choose a billing model

Start with how you want to charge, then choose the Stripe price and the SafeStripe operation. A price is your commercial agreement: currency, amount, interval and pricing model. Keep it on your server. The browser should select an approved plan, not invent the amount or submit an arbitrary price ID.

This guide covers the new 0.3.0 workflow methods. The older scoped 0.2.0 npm package does not contain them. Until the unscoped release is published, use the release archive supplied with the test workspace.

What can I build?

Model Start with SafeStripe operation What your application still owns
One-time purchase One-time Price + Checkout createCheckout Order, fulfillment and refund policy
Fixed SaaS plan Recurring Price createCheckout or createSubscription Customer mapping, access and renewal handling
Per-seat SaaS Licensed recurring Price createMultiItemSubscription Seat counts, approval and access
Graduated or volume tiers Tiered recurring Price createTieredPrice, then subscription creation Approved tier boundaries and price changes
Existing basic metered billing Meter + metered Price createMultiItemSubscription, recordUsage Usage ledger, trusted measurements and reconciliation
New usage-based product Evaluate Stripe Metronome Separate Metronome integration Contracts, metrics and ingestion architecture
Phased enterprise agreement Prices + Subscription Schedule createSchedule Signed terms and contract approvals
Sales-assisted quote Customer + approved Prices createQuote, finalizeQuote, acceptQuote Evidence of acceptance
Standalone invoice Customer + Invoice + Invoice Items createInvoice, addInvoiceItem, finalizeInvoice Sending, collection and accounts-receivable policy
Marketplace Accounts v2 recipient + platform payment createMarketplaceAccount, createTransfer Seller identity, allocations, liability and dispute recovery

The methods are deliberately specific. They do not expose every optional parameter in Stripe. If a workflow needs an unsupported option, use the official SDK behind your own authorization and durable-operation design; an arbitrary SDK call does not acquire SafeStripe's protections automatically.

The three inputs every write needs

Initialize billing once with your chosen store and authorizer. Follow Getting started for Firestore, MongoDB, PostgreSQL or local SQLite. Then provide:

  1. An authenticated actor: tenant and operator from your session.
  2. A stable business operation ID, saved before making the request.
  3. Approved parameters loaded from your application's records.
ts
const actor = {
  tenantId: membership.tenantId,
  actorId: user.id,
  operationId: savedBillingRequest.id,
};

Keep the ID when retrying the same action. Create a new ID when the business action changes. An operation ID is not authentication; every retry still passes through your authorizer.

Fixed and per-seat subscriptions

Checkout collects the payment method and handles the initial payment interface. Use it for ordinary customer signup. Direct subscription creation is useful when your application already manages the billing relationship.

ts
const session = await billing.createCheckout(actor, {
  customerId: customer.id,
  mode: 'subscription',
  items: [{ priceId: approvedPlan.priceId, quantity: team.seats }],
  reference: signup.id,
});

A multi-item subscription can combine licensed items or combine a fixed fee with an existing basic metered price:

ts
const subscription = await billing.createMultiItemSubscription(actor, {
  customerId: customer.id,
  items: [
    { priceId: monthlyPlatformPriceId, quantity: 1 },
    { priceId: seatPriceId, quantity: 12 },
  ],
});

The initial status may be incomplete. Do not grant paid access from the create response alone. Handle signed subscription and invoice events, retrieve the current state and apply your access policy. Stripe's subscription integration guide describes the lifecycle.

Graduated and volume tiers

Graduated pricing charges each band separately. Volume pricing chooses the band's rate based on total quantity, then applies it to every unit. Those models can produce very different totals at a boundary.

ts
const price = await billing.createTieredPrice(actor, {
  productId,
  currency: 'usd',
  interval: 'month',
  mode: 'graduated',
  tiers: [
    { upTo: 10, unitAmount: 1000 },
    { upTo: 'inf', unitAmount: 800 },
  ],
});

At twelve seats, this example is $116 monthly: ten at $10 and two at $8. With mode: 'volume', all twelve would cost $8 each, totaling $96. These amounts exclude tax and discounts.

This helper creates licensed recurring prices with integer minor-unit amounts. It requires increasing tier boundaries and a final infinite band. It does not combine transform_quantity with tiered prices, create fractional-cent rates or update an existing price's amounts. Create a new price for a new commercial agreement. Test 1, 10, 11 and 12 seats before publishing this example's plans.

Usage-based billing

For a new usage-based integration, first evaluate Stripe Metronome. SafeStripe does not include its client or implement its contracts and rate cards. The methods below target existing basic Billing Meters integrations with raw sum meters.

Create the meter during administrative setup, then create a metered recurring Price in Stripe that references it. Creating a meter alone does not create a billable subscription.

ts
const meter = await billing.createMeter(actor, {
  eventName: 'api_requests',
  displayName: 'API requests',
});

Subscribe the customer without supplying a quantity for the metered item:

ts
const subscription = await billing.createMultiItemSubscription(actor, {
  customerId,
  items: [{ priceId: meteredPriceId }],
});

Persist an event in your usage ledger before submitting it. Its timestamp and value must be stable across retries.

ts
const acknowledgement = await billing.recordUsage(
  { ...actor, operationId: usageEvent.id },
  {
    customerId: usageEvent.customerId,
    meterId: approvedMeterId,
    value: usageEvent.units,
    timestamp: usageEvent.occurredAt,
  },
);

status: 'accepted' is an ingestion acknowledgement. It does not mean the value has been aggregated, included on an invoice or paid. SafeStripe derives the meter-event identifier from the same scoped business operation used for durable retries. A successful replay returns the saved-input acknowledgement without sending another event; the meter-events API does not provide ordinary resource retrieval for this receipt.

Stripe's basic API accepts timestamps within its documented ingestion window and processes aggregates asynchronously. The helper rejects inactive meters, non-sum aggregation and pre-aggregated windows. Inspect meter-event requirements before choosing this path. Batch or stream ingestion, negative corrections, credit burndown and high-volume ingestion are separate designs. Do not run one synchronous HTTP billing call in every request on a busy product; record usage first and drain a bounded queue.

Trials and promotions

ts
const subscription = await billing.createMultiItemSubscription(actor, {
  customerId,
  items: [{ priceId, quantity: 1 }],
  trialDays: 7,
  promotionCodeId: approvedPromotionCodeId,
});

The helper uses a pause policy when the trial ends without a payment method. The promotion code must exist and be eligible; Stripe checks its restrictions. Your policy must approve the promotion's use by this customer. This release does not create coupons, promotion codes or credit grants.

For customer-entered promotions in Checkout, set allowPromotionCodes: true. For a Checkout trial, set trialDays. Both are optional. Trial terms and cancellation information belong in your customer-facing signup flow.

Pause, resume and retain

These operations mean different things:

Intent Method Effect
Stop collecting new invoices temporarily setSubscriptionCollection({ subscriptionId, behavior: 'keep_as_draft' }) Subscription can remain active; invoices stay draft
Collect future invoices again setSubscriptionCollection({ subscriptionId, behavior: 'collect' }) Clears the collection pause; old drafts still need review
Undo a scheduled period-end cancellation restoreSubscription({ subscriptionId }) Sets cancel_at_period_end: false; cannot resurrect an ended subscription
Resume a subscription with status paused resumePausedSubscription({ subscriptionId }) Starts resumption with a new billing-cycle anchor; payment may still be required

Pass actor as the first argument to every method. Collection changes do not decide application access. Review Stripe's pause-collection behavior and test it separately from a truly paused subscription.

Use the existing preview/apply pair for mid-cycle plan changes. Persist the preview's proration timestamp and approved terms; do not quietly recalculate them on apply.

Quotes and phased contracts

A quote has separate drafting, finalization and acceptance steps. Use one durable ID per step. Never infer customer acceptance from a page visit.

ts
const quote = await billing.createQuote(draftActor, {
  customerId,
  items: [{ priceId, quantity: 10 }],
  daysUntilDue: 30,
});
await billing.finalizeQuote(finalizeActor, { quoteId: quote.id });
// Record actual customer acceptance before running this step.
await billing.acceptQuote(acceptActor, { quoteId: quote.id });

Quote access depends on the Stripe account and product configuration. Acceptance can produce an invoice or subscription; inspect the returned record and its subsequent events. It is not evidence of payment.

For a three-month introductory period followed by nine months on a standard plan:

ts
const schedule = await billing.createSchedule(actor, {
  customerId,
  startAt: approvedContract.startAt,
  daysUntilDue: 30,
  endBehavior: 'release',
  phases: [
    { months: 3, items: [{ priceId: introductoryPriceId, quantity: 1 }] },
    { months: 9, items: [{ priceId: standardPriceId, quantity: 1 }] },
  ],
});

This helper uses net-term invoices and disables phase-change prorations. It does not send an invoice email from the create call. release leaves the subscription running at the final terms after the schedule ends; choose cancel if the agreement should end. Check schedule phase behavior before automating contract changes.

Credits and receivables

createCreditNote reduces an open invoice's unpaid balance. The narrow helper rejects paid invoices and amounts exceeding the remaining balance. A refund for money already collected is a different operation.

ts
await billing.createCreditNote(actor, {
  invoiceId,
  amount: 1000,
  memo: 'Agreed service adjustment',
});

adjustCustomerBalance creates an invoice-balance transaction. A negative amount credits a future invoice; a positive amount adds a debit. Neither direction transfers cash.

ts
await billing.adjustCustomerBalance(actor, {
  customerId,
  amount: -1000,
  currency: 'usd',
  description: 'Service credit',
});

Stripe supports more elaborate credit-note allocations, including paid-invoice refunds and out-of-band adjustments. Those allocations need their own reviewed workflow. Accounts-receivable aging, offline-payment evidence and collection emails are not calculated by these helpers.

Test a subscription without waiting a month

  1. Create a test clock with createTestClock and a saved starting timestamp.
  2. Create a new customer on it using createClockCustomer. An existing customer cannot be attached afterward.
  3. Create a seven-day trial for that new customer.
  4. Call advanceTestClock with a saved target timestamp eight days later.
  5. Wait for Stripe to finish advancing. Inspect the paused subscription and relevant events.
  6. Add a test payment method, resume and exercise a renewal separately.

Clock operations reject live mode. Time advancement is asynchronous and Stripe limits how far you can move a clock based on attached resources. The demo caps a jump at 28 days; that cap is not a guarantee that every attached configuration accepts the jump. See Stripe test clocks.

Tax belongs in the plan

Before setting automaticTax: true on Checkout, configure Stripe Tax and confirm active registrations. SafeStripe checks that settings are active and at least one active registration exists, but that cannot establish coverage for a particular customer. Verify the product tax code, address and a sandbox calculation in each applicable jurisdiction. The tax and account-services guide explains the distinction.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Build your app

Payment surfaces and Stripe account services

Installing a package does not enable every Stripe product. Some features are API operations; others are settings or services managed by your Stripe account. This page separates the two so you know what to test.

Choose a customer-facing payment surface

Surface Use it for SafeStripe support
Hosted Checkout Most checkout and signup flows createCheckout
Payment Element backed by custom Checkout A payment form styled within your application createCheckout({ uiMode: 'custom' }) + SafeCheckout
Hosted payment-method setup Collect consent and save a method for later createSetupCheckout
Custom payment-method setup A custom Stripe.js setup interface createSetupIntent; your UI confirms the returned client secret
Reusable Payment Link A public product purchase link createPaymentLink
Pricing Table Stripe-hosted plan selection embedded in a page Create in Stripe; use its generated embed
Customer Portal Billing details, invoices, plan changes createPortalSession; configure allowed features in Stripe

Stripe decides which enabled payment methods are eligible for the country, currency, device and transaction. SafeStripe does not guarantee that every wallet or local payment method will appear. Its helpers omit a hard-coded card-only payment-method list. Never collect raw card data in your Express or Next.js API.

For saved methods, a created SetupIntent is only the first step. Confirm it through Stripe's UI, follow consent requirements and handle authentication when it is later used. A saved method does not guarantee a future off-session payment will succeed. See save and reuse payment methods.

A Payment Link is reusable and is not tied to one application's authenticated customer. Provide a separate fulfillment policy for its signed checkout events. Do not reuse the demo's fixed-customer order verifier for arbitrary Payment Link or Pricing Table purchases.

Marketplace recipient setup

The new helper supports an Accounts v2 recipient model. The platform takes payment and accepts fee and loss responsibility; a seller receives transfers. That is one Connect architecture, not a universal default for every platform.

ts
const seller = await billing.createMarketplaceAccount(actor, {
  email: approvedSeller.email,
  country: approvedSeller.country,
  displayName: approvedSeller.name,
});

The helper requests a recipient's Stripe balance transfer capability, uses Express dashboard access and assigns fees/losses to the platform. Persist the account ID in your verified seller mapping. Do not let a browser select a destination account.

ts
const link = await billing.createOnboardingLink(actor, {
  accountId: savedSeller.stripeAccountId,
});

Return the onboarding URL only to the authenticated seller with Cache-Control: no-store. It is ephemeral and can be single-use. Implement /connect/refresh to authenticate the seller and generate a new link; /connect/return should retrieve current account state. A redirect is not proof of completed onboarding.

Before a transfer, SafeStripe checks the v2 recipient transfer capability, the source charge's paid state, currency, mode and unrefunded amount.

ts
const transfer = await billing.createTransfer(actor, {
  accountId: allocation.sellerAccountId,
  chargeId: allocation.chargeId,
  amount: allocation.amountMinor,
  currency: allocation.currency,
  group: order.id,
});

This is separate charges and transfers. Retain a platform share by transferring less than the charge. The helper does not set application_fee_amount. A transfer is not a bank payout. Check Stripe's transfer guide for regional and balance constraints.

If funds must return from a seller, use a separately approved reverseTransfer. Refunding the customer and reversing the seller transfer are distinct actions. Record both in your financial ledger and reconcile them. The library does not create reserves, resolve negative balances, submit dispute evidence or manage payout timing.

For platforms where independent sellers accept direct payments, evaluate the merchant configuration and direct-charge model. This release's account-creation helper does not create that configuration. It also does not implement v2 customer-account billing for charging connected accounts themselves.

Include Stripe's onboarding, account management and notification banner components in a production seller dashboard. They help sellers satisfy changing requirements. Accounts v2 thin events require a separate verified receiver and handler; the existing SafeStripe webhook receiver is for the pinned v1 snapshot event contract. Do not send thin events to it and expect them to work. See Accounts v2.

Revenue recovery

Configure Smart Retries, customer emails and final retry outcomes in Stripe Billing. SafeStripe's operation retries deal with uncertain API requests; they are not card-payment retries or a dunning strategy.

Handle invoice.payment_failed, invoice.payment_action_required, invoice.paid and relevant subscription events. Retrieve the current resource before updating your projection, because events can arrive late or out of order. Commit access decisions and outgoing-message intents together. Decide your grace period explicitly.

Card account updates happen through Stripe and participating networks. There is no wrapper setting that guarantees an issuer will update a card. Test failure and recovery using sandbox payment methods and test clocks. See Smart Retries.

Tax setup and verification

ts
const readiness = await billing.inspectTaxSetup(actor);

This read-only helper returns the settings status, up to 100 active registration IDs and a pagination flag. It does not register a business, pick jurisdictions or prove that a particular transaction will collect tax.

For Checkout, automaticTax: true checks basic settings/registration prerequisites before creation, asks for a billing address and updates the existing customer's address from the session. Your authorizer must approve that behavior. The current helper does not expose Connect tax-liability selection; use a reviewed integration for that case.

A zero tax result can be correct. Check the calculation's taxability reason, product tax code, customer location and applicable registration. An active registration somewhere does not prove coverage everywhere. Discuss registration obligations with your tax adviser, then record confirmed registrations in the correct Stripe environment. Sandbox registrations do not configure live mode. Follow Stripe Tax setup and testing.

Collecting tax is also separate from filing returns. Do not describe a successful Checkout tax calculation as end-to-end tax compliance.

Radar, disputes and Identity

Radar rules and risk decisions are configured in Stripe. Use Checkout or Stripe's secure payment fields, verify webhook signatures, restrict API keys and test blocked/challenged payments. A wrapper cannot eliminate fraud or chargebacks.

Identity session creation is available when the Stripe account has access:

ts
const verification = await billing.createIdentitySession(actor, {
  reference: savedUser.id,
});

Authorize the user reference, return the hosted URL only to that user and avoid storing the URL or client secret in logs. Do not collect government-document images in your application to pass them through this helper. Session creation does not mean verification succeeded. Implement verified, requires-input and canceled status handling plus a retention policy before relying on verification. Use Stripe's Identity test options in a sandbox.

Dispute evidence needs a reviewed operator workflow. This release does not auto-submit evidence, create Radar rules or guarantee compliance with identity-verification requirements.

Revenue Recognition and financial reporting

Revenue Recognition is a Stripe account product. Your finance team must review service periods, recognition rules and adjustments. The operational metrics helper in Revenue metrics does not calculate recognized revenue, profit, fees, bank settlement or taxes.

For accounts receivable, build aging from open invoices and their remaining amounts/due dates, separating currencies. Handle partial payments, void invoices, credit notes and offline-payment evidence. Use the existing balance-transaction importer and reconciliation helpers for settlement data, not the MRR calculator.

Readiness for a large deployment

This release has automated unit, SDK-request and storage tests. It has not demonstrated a million-user deployment or passed an independent security audit. A test workspace is not evidence of production capacity.

Before serving a large account:

  • Load-test the chosen shared database with realistic tenant distribution, worker concurrency and retained operation history.
  • Measure queue age, retry rates, Firestore reads/writes, contention and Stripe rate-limit responses.
  • Use a durable usage ledger, bounded ingestion workers and account-wide backpressure. The default in-process gate is not a fleet-wide limiter.
  • Run restore/replay exercises, secret rotation, entitlement reconciliation and financial period-close checks.
  • Verify each enabled Stripe product and payment method in a sandbox, then complete controlled live acceptance.
  • Provide tenant isolation, application authentication, seller/price ownership, approval limits, audit retention and support procedures.

See Enterprise integration for deployment responsibilities. SafeStripe reduces repeated billing infrastructure; it does not remove the work of operating your business.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Build your app

Recurring revenue metrics

Use two customer snapshots to answer a practical question: how did recurring revenue change during this period?

The calculator is a pure function. It does not contact Stripe, read Firestore, infer customer history or require a secret key. It is available through the main server entry point and the browser-safe safestripe/metrics entry point.

ts
import { calculateRevenueMetrics } from 'safestripe/metrics';

const report = calculateRevenueMetrics({
  currency: 'usd',
  start: [
    { customerId: 'acme', monthlyAmount: 10000 },
    { customerId: 'birch', monthlyAmount: 5000 },
    { customerId: 'cedar', monthlyAmount: 5000 },
  ],
  end: [
    { customerId: 'acme', monthlyAmount: 15000 },
    { customerId: 'birch', monthlyAmount: 3000 },
    { customerId: 'delta', monthlyAmount: 10000 },
  ],
});

Amounts are integer monthly minor units, not dollars. In USD, 10000 means $100 per month. Each customer appears once in each snapshot. Combine their subscription items first. Use one currency per call; no exchange-rate conversion is performed.

Read the result

The sample starts with $200 MRR and ends with $280:

Movement Amount Why
Starting MRR $200 Acme $100 + Birch $50 + Cedar $50
New MRR +$100 Delta joins
Expansion +$50 Acme grows
Contraction −$20 Birch reduces its plan
Churned MRR −$50 Cedar leaves
Ending MRR $280 Starting amount plus movements

The annual run rate is $3,360. Net revenue retention is 90%; gross revenue retention is 65%. One of the three starting paying customers leaves, giving customer churn of one-third. New customers do not improve the retention ratios.

Definitions

Result field Definition
startingMrr, endingMrr Sum of monthly amounts in each snapshot
annualRunRate Ending MRR × 12
newMrr Ending amount from customers with no positive starting amount
expansionMrr Increase for customers positive in both snapshots
contractionMrr Decrease for customers positive in both snapshots
churnedMrr Starting amount for customers with no positive ending amount
netMrrChange Ending MRR − starting MRR
netRevenueRetention (Starting MRR + expansion − contraction − churn) ÷ starting MRR
grossRevenueRetention (Starting MRR − contraction − churn) ÷ starting MRR
customerChurnRate Customers lost ÷ starting paying customers
averageRevenuePerCustomer Ending MRR ÷ ending paying customers, rounded to a minor unit

Ratios are fractions: 0.9 means 90%. A missing denominator returns null. Free customers do not count as paying customers. A customer absent at the start but present at the end counts as new, even if an older historical record would describe them as reactivated. Two snapshots cannot distinguish that history.

Build comparable snapshots

Choose a consistent policy before calculating:

  1. Take complete snapshots at known period boundaries in the same timezone.
  2. Include committed fixed recurring charges after recurring discounts and before tax.
  3. Exclude one-off fees, trials and uncertain usage forecasts.
  4. Decide whether past-due subscriptions remain in MRR during a grace period and apply that rule at both boundaries.
  5. Sum each customer's qualifying items, keeping currencies separate.
  6. Save the snapshot time, policy version and source IDs with your report.

Do not pass just the first page of a Stripe subscription list. Missing customers would be interpreted as churn. For a large deployment, build snapshots from a reconciled reporting projection or warehouse rather than synchronously scanning every subscription in an HTTP request.

Normalize a fixed recurring amount

ts
import { monthlyRecurringAmount } from 'safestripe/metrics';

const monthlyAmount = monthlyRecurringAmount({
  amount: 120000,
  interval: 'year',
  intervalCount: 1,
});
// 10000: $100 per month from a $1,200 annual charge.

The function supports days, weeks, months and years. It uses 365 days or 52 weeks per year for normalization, then divides by twelve. Those are reporting conventions, not a calculation of the next calendar invoice. It rounds half up to a minor unit. For multiple items, aggregate comparable amounts before rounding where possible and document any residual rounding in your reporting policy.

All amount arithmetic uses integers internally. Invalid, negative, fractional or unsafe integer amounts are rejected, as are duplicate customer IDs and results outside JavaScript's safe integer range. A call supports up to 100,000 customer rows per snapshot; this is an input bound, not a throughput benchmark. Larger businesses should calculate partitioned, auditable aggregates in their reporting system.

What this report cannot tell you

MRR is not cash collected, recognized accounting revenue, profit, lifetime value or a churn prediction. The calculation has no information about payment processor fees, refunds, credits, cost of service, exchange rates or your accounting policy. Those need separate inputs and reports.

The test workspace includes an editable calculator using the same package function. It labels the sample inputs clearly and runs entirely in the browser. It does not pretend to display your connected account's revenue.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Deploy and scale

Deploy your integration

Deploy the web application, shared database and background worker as three parts of one billing system. They use the same Stripe scope and durable operation history. The browser only talks to authenticated application endpoints and Stripe's payment fields.

A small production deployment

For Express, run the API on your application host and run a separate Node.js worker service. Choose PostgreSQL, MongoDB Atlas or Cloud Firestore. The local SQLite starter is for a sandbox.

For Next.js on Vercel, run Route Handlers with runtime = 'nodejs'. Use a hosted database and a worker host that permits a continuous process. Reuse the database client within each warm instance; set small pool limits and account for the number of application and worker replicas. See the framework walkthrough.

Configure environments

Use separate sandbox and production credentials, databases or namespaces, webhook destinations and origins. Define the secret key, signing secret, trusted application origin and database credentials in your platform's secret manager. Only expose the publishable key to client components.

Set the webhook destination to your deployed /api/webhooks/stripe URL. Select the exact snapshot API version and only the events you handle. Complete a real sandbox payment through the deployed application; a fixture event without an application order does not prove fulfillment.

For PostgreSQL, run safestripe migrate as a deployment step before workers start. For MongoDB, prepare the database user, replica set and queue index. For Firestore, deploy the composite index and payload index exemption. Wait for indexes to become ready before directing traffic to the worker.

Replace the learning app's policy

The repository sample intentionally refuses production mode. A deployable application must have:

  • Verified customer sessions and tenant-aware order queries.
  • An authorizer that checks resource ownership, action permissions, catalog prices and allowed commercial changes.
  • CSRF protection for cookie-authenticated writes and request-rate limits for your endpoints.
  • Durable binding between each order, its intended terms and its Stripe Session.
  • A payment verification handler, subscription entitlement rules where applicable, and idempotent fulfillment.
  • A real outbox recipient that deduplicates delivery keys, or a deliberately disabled message workflow.

Do not remove the refusal and keep the demo token as your production authentication system. It exists to make a local test easy to follow.

Release without losing payment history

Back up the billing database and verify a restore procedure. Apply backward-compatible schema changes before deploying new readers and workers. Keep old workers drained during an incompatible handler rollout. Do not clear pending jobs or operation history to make a deployment succeed.

Treat Stripe API-version changes as a separate migration. Compile against the new SDK, test new event fixtures, upgrade endpoint versions deliberately, and establish which worker owns each version during transition. The receiver rejects unexpected versions.

For a signing-secret rotation, temporarily provide both trusted secrets. Confirm events arrive using the new destination secret, then remove the old value. For API-key rotation, keep the account scope unchanged and avoid logging either key.

Operate the system

Monitor webhook acceptance errors, oldest pending-job age, failed/dead jobs, operation review state, worker duration, database latency, local concurrency saturation and Stripe rate-limit responses. A webhook 200 means durable intake; it does not mean the product was delivered.

Run reconciliation independently of webhook delivery. Compare Stripe's current objects and money movements against your application ledger. Investigate mismatches before replaying mutations. The advanced testing runbooks and financial workflows cover these tasks.

Size the worker pool from measured latency and database contention. There is no published capacity claim for this package. Enterprise architecture explains how to establish a capacity target and failure budget.

Package contributors should use the separate maintainer and publishing guide. Application developers do not need to rebuild SafeStripe's documentation, install its development tools, or publish a package to use it.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Deploy and scale

Design for a larger application

A larger payment system needs the same basic guarantees as a small one, under more concurrency and more partial failures. SafeStripe provides reusable controls for the billing boundary. Your organization still needs capacity measurements, operational ownership, access control and a recovery plan.

This release has no published throughput benchmark. Test the design against your expected peak load and recovery requirements before choosing worker counts or database capacity.

A practical deployment shape

text
Browser / mobile application
  → authenticated API (Express or Next.js)
  → order ownership + catalog + authorization policy
  → SafeStripe operation record
  → Stripe API

Stripe webhook
  → signature / scope / version / body validation
  → durable inbox
  → bounded workers
  → current Stripe resource + stored order verification
  → one database transaction: billing state + effect + outbox
  → outbox workers
  → idempotent fulfillment / notifications / accounting services

Scheduled reconciliation
  → Stripe resources and balance movements
  → application records and ledger
  → discrepancy queue for investigation

Web replicas are replaceable. The shared billing database carries the state. Webhook requests do only verification and durable admission; workers own the slower business logic. External systems receive explicit, replayable messages.

Start with one billing owner

Create a billing service/module that owns Stripe credentials, operation identities, customer mappings and event processing. Other services request an intended action using a stable business ID. They should not independently retry direct Stripe mutations with newly generated keys.

Define a supported command contract: who can request it, the amount/currency or catalog terms, the tenant, the relevant resource mapping, and the acceptable state transition. Persist these terms before accepting a commercial order. Treat approvals, refunds and subscription edits as separate workflows with their own permissions.

For Connect, derive connected accounts from an authorized server mapping. Partition worker routing by the complete account/mode scope. Do not use a client-provided account header to select arbitrary tenants' payment accounts.

Choose a transactional boundary

Keep a small billing record in the same storage transaction as its effect guard and outbox message. Your order catalog may be elsewhere, but a reliable paid-state decision needs a durable binding between the accepted terms and Stripe resource.

Cross-database updates are not atomic. If your main app uses Firebase but billing uses PostgreSQL, write an outbox message and apply it idempotently in Firebase. Do not call two independent writes and describe them as a transaction. If you use the Firestore adapter for both billing records and effects, stay inside the supplied BillingTransaction API for this atomic work.

Native SQL helpers (effectOnce, refreshProjection, SQL reconciliation) belong to the legacy PostgreSQL API. Portable transactions use tx.get, tx.set, tx.effectOnce and tx.enqueue. They cannot run arbitrary MongoDB or SQL writes in the supplied transaction. Extend an adapter deliberately if your application needs a different atomic boundary.

Control concurrency before adding replicas

ts
import { ConcurrencyGate, createSafeStripe } from 'safestripe';

const billing = await createSafeStripe({
  secretKey: process.env.STRIPE_SECRET_KEY!,
  storage,
  appOrigin: process.env.APP_ORIGIN!,
  authorize: billingPolicy,
  gate: new ConcurrencyGate(8, 32, 5000),
  observer: (event) => metrics.record(event),
});

These limits apply to one process. Ten processes with a limit of eight can issue far more requests than one process. Implement the ExecutionGate interface using your organization's distributed quota service if you need an account-wide budget. The package does not install Redis or a broker for you.

The SDK retries selected transient network failures, with bounded request timeouts. Application retries still use the same operation identity. Classify BUSY, upstream failures, payload conflicts and review-required states separately. Do not run an unbounded retry loop or reset operation history to resolve a timeout.

Portable queue claims read a bounded group of due candidates, then try transactions. Under heavy contention, many workers can examine the same candidates. Tune worker count and partition by independent account scopes; benchmark hot scopes. The original PostgreSQL queue uses SKIP LOCKED for its claim path and remains available to existing SQL integrations. There is no automatic broker connector or universal throughput guarantee.

Process events as notifications of state

Stripe can deliver an event more than once and events can arrive out of order. The inbox deduplicates event IDs; a business effect key handles two different events that describe the same fulfillment. Those are different checks.

Retrieve the current resource and verify it against the stored binding. Commit the decision while maintaining a transaction dependency on the affected billing record, so concurrent state refreshes cannot blindly overwrite one another. Keep remote reads bounded. Database transaction retries may repeat reads; do not put new financial writes inside the handler transaction.

For subscriptions, define an entitlement state machine covering payment recovery, pending plan updates, cancellation, pause/resume, trial end and asynchronous invoice settlement. Reconcile it periodically. A boolean called hasPaid is insufficient for a recurring product.

Monitor customer impact

Record the age of the oldest pending job, not just job count. Ten delayed fulfillment events may matter more than a thousand harmless subscription refreshes. Measure webhook acknowledgment latency, worker duration, retry counts, dead jobs, operation review count, database contention and Stripe request errors.

The observer emits bounded metadata and safe error classifications. It intentionally avoids payloads and raw database/Stripe error messages. Do not attach client secrets, customer emails or card data when forwarding those events to logs. Avoid unbounded tenant/resource IDs as metric labels; use protected traces or audit records for investigation.

Set alerts from an explicit service objective. For example, choose how quickly a successful payment should become available to the customer, then budget webhook delivery, queue delay and processing latency against it. The number is your product's objective, not a package default.

Prove a recovery path

Exercise a network timeout after Stripe accepts a mutation, a crash after webhook admission, a crash after remote fulfillment acceptance, expired worker ownership, wrong event versions, database failover and restore from an older backup. Verify that money-changing work does not silently replay as a fresh action.

An unresolved operation beyond the default 23-hour retry window enters review. Investigate the remote object before resolving it. Replaying a dead job should identify an authenticated operator and reason. Preserve that audit trail and the original operation identity.

Database restoration can erase knowledge of remote actions that still exist in Stripe. Freeze uncertain writes, reconcile affected intervals, restore bindings/effect history and obtain an operational sign-off before normal processing resumes. A backup restore by itself does not restore agreement between two systems.

Establish capacity with measurements

Build a load profile from your business: new checkouts, subscription renewals, failed-payment bursts, refunds, webhook replay storms and slow downstream services. Test the database adapter you will actually deploy, with representative payload sizes and account-scope concentration.

Start at expected peak, include a defined burst factor, and measure p50/p95/p99 API latency, queue age, duplicate-effect count, transaction retries, CPU, memory, database connections and storage/read costs. Inject provider throttling and temporary outages. The acceptance criterion must include zero extra committed business effects and a bounded recovery time, not merely requests per second.

Use sandbox or synthetic workloads that respect Stripe's testing and rate-limit guidance. Do not benchmark against live customer payments. Document the tested hardware, region, database tier, SDK version and concurrency so the result can be reproduced.

Production readiness is a release decision

Before enabling live payments, complete sandbox end-to-end checks, tenant-isolation tests, database-specific integration tests, secret rotation, incident drills, retention/backups, access reviews and the relevant payment/security assessment for your business. Independent security review and real payment-method/browser testing remain outside a library build's guarantees.

For day-to-day operations, continue with security and scaling, financial workflows and testing/runbooks.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Deploy and scale

Upgrade without losing history

SafeStripe 0.2 adds portable storage and a setup factory. The original SafeStripe, PostgresOperations, PostgresJobs, SQL effectOnce and SQL projection helpers remain available for existing PostgreSQL integrations.

Existing 0.1 PostgreSQL applications

Continue constructing the original SQL classes against their existing tables. Your stored operations, jobs, effects and audit history remain the source of truth. Applying migration 002_portable_storage.sql creates a separate sf_records table; it does not copy old operation history into the new portable format.

Do not replace new PostgresOperations(db) with postgresStorage({ db }) and assume the old records are reused. A fresh operation store can forget that an action already happened, especially after Stripe's idempotency retention window. There is no automatic cross-format migration in this release.

The original SQL guide is retained in SQL integration details. The legacy Express sample is available through npm run dev:express:legacy; its worker uses npm run worker:legacy. The main Express and Next.js quickstarts now use the portable adapter and a separate learning workflow.

New applications

Use createSafeStripe with one of the four portable adapters. All replicas serving one Stripe scope must point to the same durable billing store. Keep the account, mode and connected-account scope stable when changing credentials for the same account.

Moving between databases or formats

A safe migration is a project-specific data migration, not a connection-string edit. Inventory pending and ambiguous operations, unfinished jobs, effect keys, Session bindings, outbox deliveries and audit records. Freeze or route new writes, drain workers, take a recoverable snapshot and transform the full history with checksums and count reconciliation. Preserve operation IDs, fingerprints, idempotency keys, resource IDs and scope identities exactly.

Verify representative successful, pending, retry, review and dead records after import. Test that a completed old purchase replays without issuing a new create. Establish a rollback procedure that cannot leave two stores accepting independent writes. Reconcile remote Stripe resources before reopening traffic.

SQLite-to-hosted migration is not required for a disposable sandbox exercise if you deliberately use a new sandbox and new order identities. Do not apply that shortcut to live payments or reuse forgotten business actions.

Compatibility notes

The current SDK is pinned to Stripe 22.6.2, with snapshot API version 2026-08-26.dahlia. Node.js must be at least 22.19. The package is ESM. The browser component is exported separately as safestripe/react and uses React 18 or 19.

MongoDB driver 7 and Firestore server SDK 9 are optional peers. Only install the driver you use. They are compiled and exercised by the adapter checks described in the verification record; a version range alone is not proof that every provider configuration has been tested.

Moving from 0.2 to the 0.3 preview

The package name is now safestripe. The old published scoped 0.2.0 package remains available, but it does not contain the new scenario methods. Until 0.3.0 is published under the shorter name, install the preview archive rather than assuming npm install safestripe is available.

The existing Checkout calls keep their defaults. New optional tax, trial and promotion settings must be approved explicitly in your authorizer. Subscription Checkout can omit quantity for metered items.

The new billing-model methods send validated camelCase inputs to the authorizer and introduce new action/resource names. An existing deny-by-default policy should reject them until you add ownership and commercial-term checks. Do not change the policy to allow every action just to make an example run.

The pinned Stripe SDK and snapshot API version are unchanged. Accounts v2 thin events still require a separate receiver. Storage schemas are unchanged; retain existing operation records so retry identities survive the upgrade.

The browser-only revenue helpers are exported from safestripe/metrics. This subpath does not initialize a Stripe client or need a secret key.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Deploy and scale

What SafeStripe solves

The Stripe SDK can create a payment object in a few lines. The difficult part comes when your application cannot tell whether those lines finished.

A customer clicks twice. Your server times out after Stripe accepts a refund. Two webhook events describe the same purchase. A deployment stops a worker between updating an order and notifying another service. These are ordinary failure modes in payment systems, even when every API call is written correctly.

SafeStripe gives these situations a durable identity, a recovery path, and records that an operator can inspect. This guide explains the controls individually, what they save you from building, and the decisions that still belong in your application.

1. Retrying a request without creating another purchase

Example: A customer buys a $40 product. Stripe creates the Checkout Session, but your server loses the response. The browser retries.

Without a stable operation identity, the retry can create another session. Hashing the cart does not solve the whole problem: the customer might intentionally buy the same product again tomorrow.

SafeStripe uses an operation ID supplied by your application, such as checkout:order-184. It derives a Stripe idempotency key from the account scope, tenant, operation ID, and action. It separately stores a fingerprint of the normalized input. The configured operation store binds that identity to one set of terms.

Next request SafeStripe behavior
Same operation and same terms, still in progress Returns BUSY; the caller backs off
Same operation and same terms, retry allowed Reuses the original Stripe idempotency key
Same operation already completed Retrieves the recorded Stripe resource
Same operation with a different price or amount Returns PAYLOAD_CONFLICT
New intentional purchase with a new operation ID Creates a separate operation

What you supply: A permanent business identity, approved terms, and an application record that links the result to the order. Keep the ID across browser, server, queue, and support retries. A newly generated UUID on every attempt removes the benefit.

What changes for the developer: Retry code no longer needs to guess from a timeout whether it should create a new object. It repeats the same command and lets the durable record determine the next step.

2. Handling an uncertain result after a long outage

Example: A refund request lost its response. The service was unavailable for two days. A support job now wants to retry it.

Stripe's idempotency records have a retention boundary. Reusing an old key after it has been pruned can execute another request. SafeStripe keeps its own operation record and defaults to a 23-hour automatic retry window, measured from the local operation's creation. After that window, an unresolved operation enters review and further mutation is blocked.

An operator then checks Stripe's request history and the associated payment. If the original refund exists, the privileged resolveForReview method can bind its resource ID to the operation and record the operator and reason. The application must verify that the resource actually belongs to the operation before calling this recovery method.

What this prevents: An outage recovery script that quietly issues another refund because an old key looks safe.

What you supply: Retention of the operation record, a restricted recovery tool, and an investigation procedure. Deleting the local history or restoring an older database snapshot can remove knowledge of a completed remote action. Reconcile after a restore before resuming financial writes.

Stripe documents its key retention and replay behavior in Idempotent requests.

3. Keeping a webhook after acknowledging it

Example: Your endpoint receives checkout.session.completed, returns HTTP 200, and starts a background promise. The hosting platform freezes the process before the promise finishes.

A successful HTTP response tells Stripe that delivery succeeded. It does not prove that your application's background work finished.

SafeStripe verifies the original request bytes, signature, account scope, mode, payload shape, and API version. It inserts the event into the configured billing store before returning a successful response. A worker processes the stored record later. If storage fails, the endpoint returns an error so delivery can be retried.

What this prevents: A payment event disappearing because work was detached from a short-lived request.

What you supply: A reachable HTTPS endpoint, the correct signing secret, durable database infrastructure, and a running worker. Monitor the age of pending work. A healthy endpoint can continue accepting events while every worker is stopped.

4. Distinguishing duplicate delivery from duplicate fulfillment

Example: Stripe delivers the same event twice. Later, a different event and a manual repair job both refer to the same paid order.

There are two identities here. The inbox uses the event ID to suppress repeated delivery of one event. Your fulfillment code uses a business-effect key such as tenant-a:order-184:fulfill to suppress repeated fulfillment of the order.

effectOnce inserts that key within the worker's database transaction. The order update and the effect guard commit together. If the handler fails, both roll back, allowing a later attempt to finish the work.

What this prevents: Shipping twice or granting credits twice just because two valid events point to one purchase.

What you supply: The correct business key and the local writes made through the supplied transaction. Sending an email or calling a shipping API inside effectOnce does not make that remote service transactional. Use the outbox for those effects.

5. Recovering from a worker crash

Example: A worker claims an event and stops during deployment. Another worker needs to finish it.

SafeStripe jobs have a lease and a random ownership token. Once a lease expires, another worker may claim the job. The ownership token prevents an old worker from committing after ownership has changed. Local handler writes and the completion marker share a database transaction.

Failures retry with exponential backoff and jitter. Jobs reach a visible dead state after the attempt limit, including a crash on the last attempt. An authorized operator can replay a dead job after fixing its cause; the audit records who requested the replay and why.

The worker loop supports bounded concurrency and an abort signal. On shutdown, it stops starting work and waits for handlers already in progress. Configure network and database deadlines so that this wait has a practical bound.

What this prevents: Permanently stuck jobs after a crash, stale workers overwriting recovered work, and endless silent retries.

What you supply: Process supervision, alerts for dead jobs, bounded handler execution, and a policy for replay. More workers do not fix a handler that consistently rejects the same order.

6. Delivering work to another service

Example: An order is marked fulfilled, but the service crashes before asking the email provider to send the receipt.

The outbox stores the receipt intent in the same transaction as the order update. A separate dispatcher reads it, calls the destination, and records completion. The message carries a stable idempotency key.

There is still a possible gap: the destination accepts the message, but its response is lost. The dispatcher then sends it again. The destination must honor the key or provide an equivalent deduplication rule. SafeStripe provides at-least-once delivery, with enough identity for the recipient to make repeated attempts safe.

What this prevents: Losing a downstream task because a local commit and a remote request happened on opposite sides of a crash.

What you supply: An idempotent destination, a delivery function with a deadline, and recipient deduplication retention that covers your retry and replay period. A plain SMTP send has no automatic business-idempotency contract.

7. Keeping old events from restoring old state

Example: A subscription becomes active. An earlier event saying it was incomplete arrives afterward.

A handler that copies every event snapshot into the database can move the application's state backward. SafeStripe provides refreshProjection: it locks one resource's projection, fetches current state from Stripe, and updates the projection while holding that lock.

This favors a clear correctness rule over maximizing throughput. The network read holds a database connection and resource lock. Keep it short, disable layered read retries in that handler, and measure contention. At higher volume, consider partitioned processing by resource with an explicit refresh protocol.

What this prevents: Blindly overwriting current application state with an older event snapshot.

What you supply: The fields your product needs, a bounded retrieval function, and reconciliation. A projection is a current view. It is not a journal of every financial change or a full subscription entitlement policy.

8. Requiring permission checks at the payment boundary

Example: A logged-in user submits another organization's cus_... ID to create a billing portal session.

Stripe IDs are identifiers, not permission grants. SafeStripe requires an authorizer and calls it before wrapped commands, including replays. It supplies the account scope, actor, action, resources, and normalized parameters. Records are also scoped by account, environment, and tenant where appropriate.

The hook gives your application one place to check ownership and approved commercial terms. Strict input schemas reject extra fields, and Checkout return URLs come from a trusted configured origin.

What this prevents when correctly configured: A payment integration that treats possession of a resource ID as permission, accepts browser-selected prices without review, or trusts a request header to build a redirect origin.

What you supply: Authentication, tenant membership, resource mappings, approval limits, CSRF protection where needed, and a policy that denies unknown actions. An authorizer that always returns true disables the business-access boundary.

9. Limiting load instead of accumulating it

Example: A sale causes a burst of requests. Every incoming request starts a Stripe call, and the process accumulates work faster than it can finish.

The default concurrency gate permits eight active wrapped tasks, queues up to 32 more, and limits queue waiting to five seconds. Excess work receives BUSY. The worker loop has a separate concurrency setting. The official Stripe client has bounded timeouts and retries.

You can provide an ExecutionGate backed by a shared limiter or scheduler when several processes use one Stripe account. The default gate is local to one instance. Reuse it deliberately; creating a new gate per request defeats its limit.

What this prevents: Unbounded local request queues and uncontrolled retry fan-out inside one instance.

What you supply: Account-wide rate control, ingress limits, tenant fairness, connection budgets, and workload measurements. Raw SDK calls and handler reads need capacity controls too. The wrapper does not apply its gate to arbitrary SDK usage.

10. Investigating failures without logging payment payloads

Example: A refund fails in production. A developer adds console.log(error) and unintentionally logs customer data or request parameters.

SafeStripe's public errors use stable codes. Optional observer events include operation names, durations, outcomes, and selected failure metadata. Recognized Stripe error types and properly formed request IDs can help an operator find the corresponding request in restricted Stripe tools. Raw error messages, card fields, customer IDs, and payloads are excluded from the built-in diagnostics.

A telemetry callback can fail without changing a successful financial result. The library does not keep an unbounded telemetry queue; your exporter must be fast and bounded.

What this prevents: Treating logging as part of payment success or casually exposing full upstream errors to clients.

What you supply: A secure telemetry system, useful dashboards, alert routing, and careful labels. Application-defined job types should be fixed names, not customer data.

11. Checking whether financial records agree

Example: Your database says ten payments completed, but the Stripe balance report contains a refund and processing fees that your order totals omit.

importBalanceTransactions imports a fixed creation window from Stripe, follows pagination, and upserts scoped transaction IDs. Repeated imports refresh settlement availability. reconcile compares IDs, currencies, and exact bigint net amounts without floating-point rounding.

What this helps you build: A repeatable comparison that names missing, unexpected, or mismatched entries.

What you supply: The local financial model, scheduled overlapping imports, refreshes for older pending entries, discrepancy ownership, and bank or payout matching. These helpers are not a double-entry ledger, tax engine, or revenue-recognition system.

Where SafeStripe fits

Use SafeStripe when payment workflows need durable coordination with your database and you can run a worker. Shared deployments can use PostgreSQL, MongoDB or Firestore; SQLite is intended for local development. A SaaS billing service, marketplace back office, or order system can use the same primitives while enforcing different business rules.

For a simple payment link or a site without local fulfillment state, Stripe's hosted products may be enough. SafeStripe's portable adapters support SQLite, PostgreSQL, MongoDB and Firestore; another database needs a compatible transactional adapter. Organization-context events, thin events, complete Connect onboarding, dispute evidence submission, and full accounting are outside this release's wrapper surface.

The important review question is specific: does each control cover the failure your product can experience? The architecture, library reference, and verification record provide the details needed to answer it.

14. Starting without a database server

The portable SQLite adapter keeps the same operation and job API while storing data in one local file. A new developer can run a signed-webhook and fulfillment test without Docker. Shared PostgreSQL, MongoDB and Firestore adapters provide the same transaction-facing methods for deployment. Moving live history between stores is a deliberate migration; changing an environment variable does not copy that history.

15. Reducing payment-form wiring

SafeCheckout composes Stripe's custom Checkout provider, Payment Element and confirmation controls. An application supplies a server-created Session secret and may wrap an order summary inside the component. Prices, authorization and fulfillment stay on the server. It reduces repeated UI plumbing without pretending that an arbitrary HTML form becomes a secure card collector.

16. Keeping setup understandable

The SDK installs with the package. Account discovery removes a routine manual configuration step. Database drivers are selected explicitly, and only the React subpath belongs in a browser bundle. The separate consumer and maintainer guides keep package publishing instructions out of application setup.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Deploy and scale

Stabilizing 0.3

The 0.3 feature surface is frozen. The release work now focuses on a reliable first integration, reproducible failures and honest evidence. A version number in package.json is not a publication record.

Work in progress

Work Acceptance evidence
Reliability contracts and ADRs Contracts linked to mechanisms, tests and limitations
Process failure suite Real SIGKILL/SIGTERM, recovered work, effect/outbox counts
Stripe sandbox E2E Real remote state and signed webhooks from a dedicated sandbox
Benchmarks Reproducible workload, environment and raw measured results
Installation footprint Core-only and optional-feature clean consumer installations
Release supply chain Checks, signed tag, SBOM, provenance and registry consumer test
Hosted sandbox Isolated visitors, private credential handling, real deployed walkthrough
Independent onboarding Consented observations and fixes from unfamiliar developers

Each issue describes remaining work. An open item is not evidence of completion. Changes move through branches, pull requests and CI. Review findings belong in reproducible issues; sensitive security details belong in private reporting.

First-run target

The target is five minutes from a prepared environment to a local integration. It has not yet been validated with independent developers. Measure dependency installation and local startup separately from Stripe/Firebase account setup and provider index creation.

Start with the local payment tutorial. It uses SQLite and needs no Docker. Hosted Checkout avoids frontend dependencies. Add a dedicated sandbox restricted key, customer, price and webhook listener; then complete payment and verify the stored receipt. A success-page redirect alone is not a passing test.

For an initial reliability check without credentials:

sh
npm ci
npm run test:chaos

This runs process-failure tests against a disposable local database. It is not a real payment test. PostgreSQL process tests run separately on CI or with an explicitly supplied disposable database.

Release gates

Before publishing stable 0.3, complete real sandbox evidence for its supported first-run path, fix critical findings, review the package archive, and verify the release workflow identity. Keep the preview notice until the shorter npm name is published and a clean consumer successfully installs it.

Do not remove the earlier scoped release. Explain the migration and preserve existing users' operation history. A missing signing key, publisher configuration or independent review must remain visible as unfinished work.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Payment concepts

Stripe objects and state

Model the business before choosing endpoints

An order is your promise to deliver something. A Checkout Session is a payment experience. A PaymentIntent manages a payment attempt lifecycle. An invoice records an amount owed. A subscription schedules recurring commercial obligations. None of these alone is your entire business transaction.

Choose a clear ownership graph:

text
Organization / tenant
  └─ application customer mapping → Stripe Customer
       ├─ order → Checkout Session → payment resources
       └─ contract → Subscription → Invoices → invoice payment resources

Successful payment → business fulfillment record → external delivery intent
Financial movements → Balance Transactions → payout / bank reconciliation

Store account and environment alongside every Stripe ID. Treat (Stripe account, sandbox/live, object ID) as the resource identity. A cus_... string supplied by a browser is an identifier, not proof of ownership.

Resource field guide

Resource What it represents Operational question Frequent mistake
Customer A billing relationship and reusable billing information Is this the correct legal/customer record in the correct account? Assuming email uniquely identifies a tenant
Product / Price What is sold and its commercial terms Is this the approved recurring or one-time price and currency? Letting the client choose arbitrary prices or quantities
Checkout Session Customer-facing checkout state Did this session complete and is payment settled enough for this product? Treating arrival at a success URL as proof of payment
PaymentIntent Lifecycle of a payment Does it require a method, authentication, capture, or more processing time? Creating a new intent after every timeout
PaymentMethod / SetupIntent Tokenized method and setup flow Is future usage authorized and configured correctly? Collecting raw card numbers in application forms
Charge Payment attempt information within modern flows What charge is linked to this payment/refund/dispute? Building new acceptance flows using legacy charge creation
Invoice Receivable and billing document Is it draft, open, paid, void, or uncollectible? Confusing a refund with correcting an invoice
Subscription Recurring agreement and lifecycle Which items, dates, collection rules, and status apply? Equating active with all historical invoices being paid
Refund Return of funds against a payment What amount has been requested and what is its actual status? Treating submission as completed settlement
Dispute Cardholder/issuer challenge What is the deadline, reason, amount, and evidence requirement? Refunding independently while a dispute is in flight
Balance Transaction A movement in the Stripe balance What gross, fee, net, currency, and availability apply? Summing charges and calling the result bank cash
Payout Transfer of eligible balance to an external account Which settlement movement reached the bank? Assuming a payout equals one sale

Payment state is asynchronous

A custom PaymentIntent flow must distinguish missing payment details, required customer action, ongoing processing, authorized-but-uncaptured funds, successful payment, and cancellation. The UI should display actionable messages; your server makes the fulfillment decision using a verified current resource and your policy. A client secret enables a client flow and must not be exposed to another customer or logged.

For Checkout, keep a pending state while delayed methods resolve. Handle both completion and asynchronous success. A completed session with payment_status='unpaid' must not unlock paid goods. A zero-cost or trial scenario can legitimately be no_payment_required; entitlement rules must explicitly account for it. See payment-status verification and Checkout fulfillment.

Example application states:

text
order:    created → checkout_pending → payment_confirmed → fulfilled
                               └──→ expired / payment_failed
payment:  separate record of processor status and timestamps
delivery: pending → accepted_by_provider → delivered / exception

Do not roll fulfilled back to pending because an old event arrives. Refunds and disputes are compensating business events, not rewrites of the original delivery history. A shipped item remains shipped even if money is later returned.

Invoice and subscription decisions

Invoice draft content can change before finalization. An open invoice is a receivable awaiting settlement. Paid, void, and uncollectible have distinct accounting meanings. Void cancels the obligation under the applicable workflow; uncollectible records that it will not be collected. Do not mark paid outside Stripe merely to remove an overdue badge. Use that action only when an authorized, evidenced payment occurred elsewhere. See invoice transitions.

A subscription can be trialing, incomplete, active, past due, unpaid, paused, canceled, or incomplete-expired. Cancellation scheduled for period end is a future instruction, not necessarily immediate termination. Pausing collection differs from a subscription whose status is paused. Implement an explicit access policy rather than a single isPaid boolean. See subscription lifecycle.

Suggested application policy, requiring product approval:

Observed condition Candidate access policy Additional evidence
Eligible trial Trial-scoped access Trial end, abuse checks and contract
First payment incomplete Keep activation pending Required action / payment result
Current billing accepted Paid features Contract, subscription items, relevant invoice or entitlements
Renewal past due Time-limited grace Dunning settings, customer tier, recovery deadline
Unpaid or terminated Restrict new paid usage Retention/export policy and legally required access
Scheduled cancellation Continue to agreed boundary Effective end time per item/contract
Dispute or suspicious activity Risk review Never infer fraud solely from the presence of a dispute

This table describes product choices, not automatic Stripe behavior. Never send an API request that attempts to set an arbitrary subscription status such as past_due.

Data boundaries

Keep a table mapping tenant, Stripe account, environment, and Customer ID. Use explicit subscription/order tables for your own concepts. Avoid hidden reliance on email, name, or mutable metadata as an authorization boundary. Metadata may help investigation; it is not a secure tenancy directory.

Suggested application records include billing_customers, immutable order_attempts, subscription_contracts, entitlement_grants, refund_requests, and finance_adjustments. These are host-application tables; SafeStripe does not silently create a full commercial schema for you.

Map asynchronous events through the Stripe object graph to your known Customer, Subscription, payment, or Checkout Session. If a webhook arrives before the API response has been bound, retry processing or reconcile the operation. Do not guess the tenant and grant access. SafeStripe's example intentionally retries an unknown Checkout Session until its mapping is established.

Design review questions

Before accepting an integration, ask: Can two browser tabs buy twice intentionally? Can they accidentally create two attempts for one immutable order? Who decides which is allowed? What happens if the payment succeeds after the order expires? Which system can approve a refund? How is that decision represented after the approver leaves the company? What does the customer see while the financial state is unresolved?

Answers should identify records, transitions, owners, and recovery paths. “Stripe handles it” is not an answer to a question about your own business state.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Payment concepts

Distributed architecture and invariants

The SQL implementation details on this page describe the original PostgreSQL API. For the portable SQLite, PostgreSQL, MongoDB and Firestore setup, start with database adapters and framework integration. The current local sample defaults to SQLite; legacy SQL example commands use the :legacy suffix.

The two independent systems

Stripe and your database do not participate in one atomic transaction. An API call can succeed at Stripe and time out before your service sees a response. Your database can commit and your HTTP response can disappear. A worker can stop after delivering an email but before recording delivery.

Build from invariants:

  1. One immutable business operation binds to one request payload.
  2. Remote retries use that operation's stable Stripe idempotency key.
  3. A verified event is durably stored before it is acknowledged.
  4. Local fulfillment and its deduplication guard commit together.
  5. External side effects have their own durable delivery intent and deduplication contract.
  6. Every object and effect belongs to an explicit account, mode, tenant, and business identity.
  7. Uncertainty is visible and recoverable; it is never silently converted to success.

These are design requirements you can test. “Exactly once” without a boundary is not a useful requirement.

End-to-end flow

mermaid
sequenceDiagram
  participant U as Customer
  participant A as Authenticated API
  participant D as PostgreSQL
  participant S as Stripe
  participant W as Worker
  U->>A: Buy existing authorized order
  A->>D: Claim immutable business operation
  A->>S: Create Checkout with stable idempotency key
  S-->>A: Session ID and URL
  A->>D: Save remote ID and bind order
  A-->>U: Redirect to Checkout
  S->>A: Signed event, possibly repeated
  A->>D: Insert inbox event with unique account/event key
  A-->>S: 200 only after durable commit
  W->>D: Claim with lease and fencing token
  W->>S: Retrieve current resource when required
  W->>D: Commit business effect + outbox + event completion
  U->>A: Read order status
  A-->>U: Pending or fulfilled from application state

The redirect page is read-only. A reconciliation job can repair missing fulfillment through the same transactional business function used by a webhook worker. This preserves a single mutation rule without requiring a globally single worker.

Three different identities

Request identity identifies a business command: tenant-17:order-742:checkout-attempt-1. It is allocated when the order attempt is created, not randomly on every browser request. A deliberate second purchase gets another identity.

Transport identity identifies an event delivered by Stripe, such as evt_.... It removes repeated delivery of that event.

Business-effect identity identifies the local action, such as tenant-17:order-742:fulfill. It removes the same action requested by different event types or a recovery job.

Conflating them causes bugs. Both a Checkout completion and a later asynchronous success may concern the same order. Conversely, identical carts can represent two valid purchases. SafeStripe therefore hashes operation identity for the remote key and hashes canonical parameters separately to detect conflicts.

Stripe's idempotency layer retains results for eligible requests, compares reused parameters, and may prune keys after they are at least 24 hours old. Some pre-execution failures are not retained. Review Stripe idempotent requests before designing automatic replay.

Durable command protocol

SafeStripe first records (scope, tenant, operation ID, kind, fingerprint, key) in the configured billing store. A short transaction claims that operation. Competing live requests receive BUSY; a changed fingerprint receives PAYLOAD_CONFLICT.

The Stripe call happens outside the database transaction. On success, the object ID is recorded. On an ambiguous failure, the operation becomes retryable. A retry uses the original key. Completed calls retrieve the current object by saved ID instead of reissuing the mutation. This means the response is current state, not a historical HTTP-body replay.

If the operation is still unresolved 23 hours after initial creation, automatic mutation stops with REVIEW_REQUIRED. The earlier deadline creates margin before possible key pruning. It can stop an operation that never actually reached Stripe; that is the intentional cost of failing closed under uncertainty.

Do not delete old successful operations while their business IDs remain reusable. A missing record removes the conflict guard. Archive to a durable tombstone or retain it for the domain's replay horizon. Restoring a database backup also changes what you know: reconcile lost writes before reopening payment commands.

Failure timeline

Failure point Known facts Safe recovery
Before operation claim No command admitted Retry request after authentication
After claim, before Stripe Request may not have been sent Wait for lease, retry same key within window
Stripe succeeded; reply lost Local outcome uncertain Retry unchanged key; inspect request history if unresolved
Stripe succeeded; DB update failed Remote object may exist Same key recovers response; no new business ID
Lease expired while old worker runs Two processes may overlap remotely Stripe key deduplication plus local fencing
More than retry window elapsed Stripe may no longer deduplicate Operator reconciliation, then bind proven remote ID

Stripe may cache server errors as part of an idempotent result. Do not generate a new key simply because the cached result is inconvenient. Its low-level error guidance explains indeterminate outcomes; use business evidence and request history to resolve them.

Durable event protocol

Verify the original bytes with Stripe's SDK and the endpoint secret. Check account, mode, payload family, API version, and event shape. Save accepted events using a unique (queue, scope, event ID) key, then return success. Storage failure returns a retryable HTTP error. Invalid signatures never enter the inbox.

Events can be duplicated and reordered, and delivery retries are finite. Therefore combine event ingestion with periodic reconciliation. The queue's presence does not prove the handler succeeded. Watch oldest pending age, dead letters, and business-effect completion. Stripe documents the delivery and verification rules in webhooks.

Worker leases and fencing

FOR UPDATE SKIP LOCKED lets multiple workers claim independent jobs without selecting the same live row. Each claim gets a random token and a lease. Completion locks the job and verifies its current token and unexpired lease before any local handler writes. A stale process cannot commit another worker's job.

The handler and done marker use the same database connection and transaction. If a handler writes through a global pool instead of the supplied tx, it has escaped the atomic boundary. If it emails a customer inside that transaction, rolling back cannot unsend the email. Those are integration errors the library cannot automatically undo.

effectOnce inserts a business guard and performs local work inside the caller's transaction. A crash rolls both back; a subsequent attempt can retry. The guard must be kept as long as old events or recovery commands can reappear. Per-event deduplication is insufficient for one business action triggered by several events.

Outbox and external systems

Within the local transaction, insert an outbox intent. A separate dispatcher claims it, sends to a recipient with a stable delivery key, and records completion. A response lost after external delivery means another attempt may send the same message. Only a recipient that honors that key: or another domain-specific deduplication scheme: can prevent the duplicate external effect.

The default example leaves outbox intents visible for inspection. It does not pretend that an email was sent. Production must configure a delivery consumer, retry budget, dead-letter procedure, and data-retention policy. Refunds, inventory release, shipments, and emails need separate business semantics; a generic “undo” callback is not adequate.

Out-of-order events and current state

An old event should usually act as an invalidation signal for a mutable subscription projection. refreshProjection locks a resource row, retrieves the current Stripe resource, and writes a minimal projection under that lock. This avoids a slower stale fetch overwriting a newer fetch from another worker.

The example deliberately holds a database lock across a bounded read to Stripe. This is easy to reason about but consumes a connection during network latency. Keep read timeouts short and disable nested read retries. At higher volume, replace it with per-resource partitioning or a versioned refresh-command protocol; retain the same state invariant. Do not remove the lock and assume event.created gives a total order: it does not.

Financial history needs a different strategy. Import immutable financial movements by balance-transaction identity. A mutable “current total paid” snapshot cannot replace a journal of payments, refunds, fees, disputes, and reversals.

Architectural decision record

PostgreSQL is the initial durable queue because command records, effects, and application writes can share a transaction. Redis is useful for rate limits or caches, but adding it as another authoritative ledger increases failure modes. A dedicated broker becomes justified when measured backlog, fan-out, or throughput requires it. Publish from a transactional outbox; do not dual-write a database and broker and hope both succeed.

Start with one write region per account/domain. Cross-region failover must preserve the authoritative operation and effect records. Active-active payment writers with asynchronously replicated deduplication tables can double-admit a purchase. Choose consistency and recovery objectives before selecting deployment topology.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Payment concepts

Billing and financial engineering

Money is a typed quantity

Represent API amounts as integer minor units and always carry the currency. USD 10.00 is commonly represented as 1000; a zero-decimal currency follows different scaling, and Stripe has special rules for some currencies and payout contexts. Do not apply a universal multiplication by 100. Read the current currency rules.

Validate amount syntax at the edge and business bounds in the service. An integer of 10 million might be syntactically valid and commercially wrong. SafeStripe validates positive safe integers for its amount-taking methods; it does not claim to validate every currency's processor minimum, maximum, or your approval limit.

Use database bigint or appropriate exact decimal types for aggregation, and BigInt for integer comparison beyond JavaScript's safe range. Never sum different currencies into one total. FX conversion requires the actual rate, effective time, rounding policy, and a separate gain/loss treatment.

Proration is a quote workflow

For a seat upgrade, persist a change proposal containing subscription ID, item ID, new Price ID, quantity, proposed effective time, and the timestamp used for proration. Preview through invoices.createPreview, show the result, and record acceptance. Apply the same timestamp and intended parameters when updating the subscription. Re-fetch after the change and reconcile the actual invoice.

An identical proration timestamp addresses one source of drift; it cannot freeze future taxes, discounts, exchange rates, usage, or concurrent edits. Give quotes an expiry and a clear acceptance policy. Do not promise an exact final invoice solely because the preview succeeded. See invoice preview and prorations.

SafeStripe's previewSubscriptionChange and updateSubscription share the same explicit input shape. The update requests immediate invoicing with a pending update if collection is incomplete. This policy fits paid upgrades; it is not a universal downgrade or renewal policy. Pending updates have eligibility and field restrictions that must be tested for your payment methods and billing configuration.

The library verifies that the item belongs to the specified subscription. The application must additionally serialize competing commercial changes, verify the quote is still current, and authorize the new Price and quantity. Two accepted proposals with different operation IDs can both run unless your contract table prevents it.

A worked upgrade review

A fictional customer has five seats. They request eight seats halfway through a period. Do not calculate “three seats times half the monthly price” and bill that amount yourself. That mental estimate is useful for detecting gross errors, but discounts, tax behavior, billing mode, and precise timestamps can change the invoice.

The approver should see: old and new seat counts, effective time, previewed debit or credit, currency, tax treatment, collection behavior, and what happens if payment needs authentication. The engineering record should bind those facts to an immutable proposal ID. After execution, verify the resulting item quantity and the invoice state independently.

Off-session authentication and recovery

Collect consent and set up the payment method for its intended future use. A later off-session payment can still require the customer's participation. Do not interpret that as a permanent card failure or silently issue unrelated PaymentIntents until one succeeds.

For subscription invoices, process payment-failure and action-required events, retrieve current state, and enqueue a customer recovery intent. Let the customer return through an authenticated page or appropriate Stripe-hosted flow. Avoid putting secrets or full billing data in notification URLs. Re-check the invoice before sending a reminder; a delayed job may refer to an already paid invoice.

Stripe Billing controls collection attempts and subscription status according to configuration. Your application controls the grace period and access policy. These are separate state machines. Review subscription webhook events and subscription payment behavior.

Invoice changes, refunds, and credits

A refund returns money against a payment. A credit note adjusts an invoice under the applicable billing/accounting workflow. Canceling a subscription changes future service/billing behavior. These operations can be related, but none is a substitute for the others.

Refund approval should identify the original payment, refundable amount, prior refunds, reason, approving actor, and whether a dispute is open. Use a business refund-request ID as the operation identity. Distinct approved partial refunds need distinct IDs. Stripe can enforce processor limits, but your system still needs approval controls and reconciliation when an operator also issues a Dashboard refund.

Refunds may remain pending or fail. Account for their actual status and related balance movements, not just the success of the create API call. Consult refund behavior before designing settlement notifications.

A ledger example

The following is a simplified accounting design example, not an automated posting policy shipped by SafeStripe. Assume a USD 100.00 sale with an illustrative USD 3.20 processing fee:

Journal event Debit Credit
Payment settles into processor receivable Stripe clearing 100.00 Sales or deferred revenue 100.00
Processing fee recognized Processing expense 3.20 Stripe clearing 3.20
USD 96.80 payout arrives Bank cash 96.80 Stripe clearing 96.80

Each journal must balance within a currency and accounting entity. Subscription revenue may be deferred and recognized over time according to your accounting policy. Refunds and disputes add compensating entries; they do not edit historical journal lines. Use unique source references to prevent duplicate posting, explicit journal versions, and approvals for manual adjustments.

SafeStripe includes balance-transaction ingestion and comparisons. It does not include a complete double-entry engine, chart of accounts, revenue recognition, FX accounting, or bank feed. Building those incorrectly is worse than making their boundary explicit.

Reconciliation design

Use three independent comparisons:

  1. Application versus processor: expected orders, refunds, and subscription obligations versus actual Stripe resources. Investigate missing or duplicated objects and mismatched amounts.
  2. Processor movement versus journal: every relevant Balance Transaction has one classified journal source; gross, fee, net, currency and account agree.
  3. Processor versus bank: payouts, reversals, timing differences, fees, and actual bank receipts reconcile.

Scan fixed UTC windows using half-open ranges [from, to). Persist a successful window checkpoint only after all pages finish. If a scan fails halfway, repeat the window and upsert by identity. Refresh pending movements and overlap recent windows to catch availability changes; do not depend on a once-only daily scan. Long-term backfills and exception handling require an operator-owned schedule.

Stripe's Balance report explains balance activity, while the Payout reconciliation report associates eligible automatic payouts with their transactions. They answer different questions. Document report timezone, currencies, filters, and row completeness when comparing them.

importBalanceTransactions streams API pages and records movements. reconcile compares supplied expected and actual rows using exact integers. Neither schedules itself, invents the expected ledger, closes accounting periods, or repairs differences automatically.

Connect and financial responsibility

Choose Connect architecture from the actual commercial relationship, account configuration, charge ownership, and loss responsibility. New account design should follow Stripe's current Accounts v2 guidance. Dashboard access, fee collection, and negative-balance responsibility are distinct dimensions. Consult SaaS account setup and marketplace setup.

Direct charges, destination charges, and separate charges/transfers produce different money paths. A platform-side refund does not automatically imply the desired connected-account recovery. Separate transfers require explicit tracking of transfer/reversal relationships; fee retention is modeled in transfer amounts, not an application-fee field on that separate-transfer operation. See separate charges and transfers.

Before releasing funds, evaluate available balance, pending liabilities, dispute exposure, contractual reserve policy, account capabilities, and permissions to control payout timing. A balance.available event is an input, not a universal authority to freeze a seller's money. Negative balances do not imply one fixed debit behavior across all Connect arrangements.

SafeStripe scopes ordinary API requests and snapshot webhooks to a configured connected account. It does not implement Accounts v2 onboarding, capability management, organization events, transfer reversals, payout controls, or seller reserve calculations. Those require a platform-specific design and separate tests.

Tax is explicit configuration

The examples do not enable automatic tax. Before adding it, establish the applicable tax obligations, registered jurisdictions, liable entity, product classification, price tax behavior, and customer location. Confirm active registrations in the intended Stripe environment; merely enabling a flag does not establish collection everywhere. Inspect taxability reasons in sandbox calculations, including valid zero-tax cases. See Stripe Tax setup and testing Stripe Tax.

Registration, calculation, collection, reporting, filing, and remittance are different responsibilities. Obtain the appropriate tax advice for the business and region. A technical wrapper cannot decide legal liability or repair historical tax treatment by changing a future Checkout setting.

Usage billing and large SaaS contracts

Keep usage measurement separate from monetary settlement. Define event identity, allowed lateness, aggregation windows, corrections, tenant ownership, credit consumption, and invoice finalization boundaries. Duplicate usage is a billing defect, even if the payment itself is perfectly idempotent.

Stripe's current guidance recommends evaluating Metronome for new usage-based systems; existing Billing Meters integrations have their own supported paths. SafeStripe does not implement either metering engine. Preserve fixed-fee subscription and customer mappings when adding usage rather than automatically canceling the existing commercial agreement. Review current product documentation before selecting a metering API.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Payment concepts

Security, performance, and large-scale operation

The SQL implementation details on this page describe the original PostgreSQL API. For the portable SQLite, PostgreSQL, MongoDB and Firestore setup, start with database adapters and framework integration. The current local sample defaults to SQLite; legacy SQL example commands use the :legacy suffix.

Threat model

Name what you are protecting: customer payment authorization, tenant billing privacy, entitlement correctness, financial integrity, operational credentials, and the ability to investigate a failure. Separate an unauthenticated attacker, a malicious tenant, a compromised application service, a mistaken operator, and a delayed legitimate event. They require different controls.

Threat SafeStripe mechanism Host/application responsibility
Forged webhook SDK signature verification over raw bytes TLS, secret storage, clock synchronization, edge controls
Replay or duplicate delivery Unique inbox identity and local effect keys Guard retention and correct business-key design
Cross-tenant resource ID Mandatory authorization callback Authenticated membership, resource mapping, role and financial policy checks
Price/amount tampering Narrow validated methods; fixed demo order Authoritative catalog, quantity limits, frozen quote/order
Lost API response Stable keys and durable operation record Stable business ID and remote reconciliation
Worker crash/race Row locks, leases, fencing, atomic effects Every local write uses the supplied transaction
Database outage No successful webhook acknowledgment before persistence Highly available storage, backups and tested recovery
Secret/PII disclosure Sanitized HTTP errors; no full API result cache Logging controls, encryption, access review, retention
Request flood Body limits and bounded local API gate Distributed rate limiting, admission control, ingress timeout
Unauthorized financial action Authorization integration point Refund approvals, separation of duties, audit of business intent

Authorization is part of the payment design

Authenticate before invoking the wrapper. Derive tenantId and actorId from a trusted session/service identity. Resolve the Stripe account from server-side configuration. Never accept these values as authoritative because they appeared in a JSON body, header, query parameter, or Stripe metadata.

The authorizer receives the action, scoped resources, and normalized parameters. Verify that the actor is an active tenant member, has the required billing role, and can act on every resource. For a refund, also verify the approved refund-request record and amount. For checkout, confirm the order is owned by that tenant and the Price/quantity match its frozen terms.

Conceptual service logic:

text
authenticate request
→ load tenant membership and allowed billing role
→ load immutable order/refund/change proposal by internal ID
→ resolve Stripe resources through trusted mappings
→ compare requested action and normalized parameters to approved proposal
→ invoke SafeStripe with the proposal's stable operation ID
→ persist the returned remote identity and audit the business action

A permissive authorize: async () => true defeats the boundary. The demo uses a fixed sandbox-only identity and permits one configured Checkout operation; replace the whole policy before production. The supplied internal replay/review helpers are not authenticated admin endpoints. Protect any UI/API built around them separately.

Database row-level security may strengthen tenant boundaries in a larger product, but SafeStripe's schema does not enable it automatically. Review connection roles, SQL access, migration privileges, and whether a compromised worker could edit other tenants' records. Parameterized queries prevent this library's ordinary SQL injection paths; they do not make a stolen database credential harmless.

Secrets and browser exposure

Use restricted Stripe keys per service where possible. Put production secrets in your platform vault and grant read access only to the service identity that needs them. Separate sandbox and live credentials; rotate on exposure and when access changes. A webhook secret authenticates a particular destination and differs from the API key. Rotation overlap should be short and monitored. See Stripe key practices.

Use Checkout or properly configured Stripe Elements so raw card data goes directly to Stripe. This reduces the scope of data your servers handle, but does not eliminate your business's compliance responsibilities. Serve payment pages through HTTPS, review third-party scripts, and apply the CSP directives appropriate to the actual Stripe integration. See integration security.

For cookie-authenticated mutation routes, enforce CSRF defenses, validate origin against trusted configuration, use appropriate SameSite cookie settings, and keep state-changing actions off GET. A webhook route uses signature authentication; it should not require the customer's session cookie. Exempt only the exact webhook path from browser-specific CSRF checks.

Do not return raw Stripe errors to browsers. Do not log client_secret, authorization headers, signing secrets, full webhook payloads, hosted payment URLs, or full customer objects. Use allowlisted structured fields such as operation kind, request ID, event ID, stable error code and elapsed time. Even these identifiers need access controls and a retention policy.

Data retention

Inbox payloads can contain customer information. Store them with encryption at rest, restricted access, and a defined retention period. After that period, keep the minimum deduplication tombstone and operational fields needed for safe replay prevention; do not delete the uniqueness boundary inadvertently. SafeStripe currently stores payload JSONB and does not implement automatic redaction or expiry.

Successful operation rows retain remote IDs rather than full responses. Do not purge them just because Stripe's key cache is short-lived. Your business can receive old retries, operator replays and restored backups much later. Decide retention with security, finance, privacy and recovery requirements together.

Latency budgets and overload

Separate webhook acknowledgment latency from business processing latency. The ingress path performs verification and one database insert. It should not call Stripe, calculate proration, send email, or fulfill inventory. The worker owns slower work and exposes its backlog.

The default client has a 10-second request timeout and two SDK network retries. The local gate admits eight concurrent wrapped calls, queues up to 32, and expires a queue wait after five seconds. These are conservative starting parameters, not measured optimal values. A supplied custom Stripe client can alter timeout/retry behavior; keep its worst-case duration below the operation lease and deployment request budget.

Use Little's law for an initial concurrency estimate: concurrency is approximately arrival rate multiplied by average service time. If a workload needs 40 calls/second and observed service time is 0.25 seconds, about 10 active requests are needed just for the average load. Add headroom only after considering Stripe limits, tail latency and database capacity. This example is arithmetic, not a throughput claim about SafeStripe.

Limit account-wide requests across all pods. A gate of eight in each of 100 processes allows 800 concurrent calls. The default gate is local to one instance. The ExecutionGate interface lets you supply a shared limiter or scheduler. Use a centralized scheduler or shared limiter when traffic warrants it, and account for Dashboard/other service traffic as well.

Stripe distinguishes rate and concurrency constraints. Classify rate-limit feedback, back off with jitter, and avoid multiplying retries at the gateway, service, SDK and worker simultaneously. Defer batch reports and backfills during interactive incidents. See Stripe rate limits.

Database and queue capacity

Use a bounded connection pool and budget total connections across web replicas, worker replicas, migrations and administrative tools. Pool exhaustion can convert an upstream slowdown into a complete payment outage. In serverless environments, use a suitable connection proxy/pooler and a small per-instance pool.

Measure inbox insert latency, claim latency, lock wait time, dead tuples, WAL volume, index size, oldest pending age and worker throughput. SafeStripe's partial indexes target ready and abandoned jobs. Verify query plans with representative data; do not assume the same plan at ten million rows. Establish archival procedures that preserve deduplication keys and avoid long blocking transactions.

For a backlog of B jobs, arrival rate a, and processing capacity c > a, estimated drain time is B / (c - a). If capacity is below arrival rate, waiting longer will not recover the system. Increase safe worker capacity, reduce nonessential incoming work, or fix the dependency bottleneck.

The projection helper locks a resource while reading Stripe. A very active subscription can become a hot row. Partition by account/resource, coalesce refresh requests where semantics permit it, and avoid fetching the same resource for every redundant event at extreme volume. Coalescing must not discard historical financial events that require individual accounting entries.

Cache boundaries

Cache public catalog data with explicit versioning. Cache customer-facing billing summaries only with tenant/account/mode in the key and a bounded freshness contract. Never cache a secret-bearing response in a shared CDN. Payment/Portal URLs and customer billing routes require careful cache policy; the example uses no-store for API responses.

A cache cannot be the only deduplication store for money. Eviction, failover and TTL expiry are normal cache behavior. The authoritative command identity and business-effect guards belong in durable storage.

Observability and service objectives

Candidate objectives to validate with the business: 99.9% of valid admitted events durably stored within one second; 99% of supported business effects completed within 30 seconds when dependencies are healthy; zero unexplained cross-tenant access; all monetary differences assigned an owner by the next reconciliation cycle. These are proposed objectives, not guarantees delivered by the repository.

Track admission success/error rate, signature/scope/version rejections, command conflicts, operations in review, oldest pending/dead job age, retry count, outbox age, reconciliation mismatches, connection wait and API latency. Avoid unbounded customer or event IDs as metric labels. Put those identities in restricted traces/logs instead.

Alert on actionable symptoms: growing backlog, unreconciled paid orders, dead financial jobs, or operations approaching the retry cutoff. A short Stripe timeout spike may be tolerable if durable work recovers; a quiet worker with no effects can be more serious than a noisy endpoint.

Deployment and disaster recovery

Apply migrations before traffic reaches code that requires the new schema. Keep old and new workers compatible during rollout. Upgrade Stripe SDK and destination API versions as one reviewed contract change, using fixtures and parallel observation where appropriate. An old event payload does not retroactively acquire the shape of a newer SDK type.

Restore backups in an isolated environment and compare operation/effect records with Stripe activity after the restore point. Lost local records can cause duplicate operations after recovery. Keep payment writes disabled until those gaps are understood. Document RPO/RTO targets and test the runbook with the people who will execute it.

A large deployment needs measured capacity, security review, incident ownership, financial controls, and tested infrastructure. Review these responsibilities with the teams that will operate the service.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Operate and review

Stripe payment-operations workbook

Working standard

Use this procedure for every assigned task: read the instruction, confirm the account and sandbox/live context, identify the exact records, inspect prerequisites, perform only authorized changes, verify the resulting state, and record evidence. If instructions conflict with an observed financial fact, document the conflict rather than improvising another financial action.

The labs below are synthetic exercises for a dedicated sandbox. They have not been performed in your Stripe account. Replace fixture labels with object IDs created during setup. Dashboard navigation can change; use the relevant resource search and detail pages. Never use real customer contact details for training data.

Maintain a run sheet:

Field Value to record
Task and run ID Unique identifier for this attempt
Operator and reviewer Named authorized participants
Account and environment Exact account ID and sandbox label
Input identities Customer, payment, invoice, subscription, refund or dispute IDs
Authorized change Amount, currency, dates, reason, scope and any approval reference
Starting state Facts inspected before action
Actions Actual sequence, including deviations and failed attempts
Result Object ID, observed status, important totals and timestamps
Evidence Recording timestamps and approved screenshots or exports
Exceptions Pending outcomes, unavailable controls, conflicts, escalation owner

Lab 1 : Create and verify a customer

Scenario: A fictional organization, “Northstar Training Ltd,” needs a billing customer. Use billing+northstar@example.invalid for a non-deliverable synthetic address. No notification is required.

Before acting: Search for an existing fixture by the assigned run label. If it exists, inspect its ID and task history rather than creating another customer. Confirm the account is the sandbox and that the name/address supplied by the task are synthetic.

Procedure: Open Customers, choose the create/add action, and enter the approved name and email. Add only task-specified fields. Save, reopen the customer, and verify the persisted details. Record its cus_... ID as CUSTOMER_A in the run sheet. If correcting a field, describe the before/after value and verify after saving.

Evidence: Environment indicator, customer ID, name, email, and final detail view. Mask unrelated customers.

Pass condition: One intended customer exists with the exact supplied fields and no unintended payment or subscription. A success banner alone is insufficient.

Recovery: If you created a duplicate, identify both records and ask the project owner which to retain under the task's correction policy. Do not delete a customer with attached financial history merely to tidy the list. The library's corresponding action is createCustomer; application mapping remains a separate responsibility.

Lab 2 : Complete a one-time sandbox payment

Scenario: CUSTOMER_A buys one approved training product at USD 49.00. Use a one-time Price created for this fixture.

Before acting: Verify the Price ID, currency, recurring/one-time classification, quantity, and task policy for tax. If the price is tax-inclusive or a discount is present, the expected amount must reflect the approved setup. A flat 49.00 expectation assumes neither additional tax nor discounts.

Procedure: Create Checkout through the SafeStripe demo or the task's approved Stripe payment surface. Confirm the displayed item and total. Complete the sandbox flow with an appropriate test method. Return to the Dashboard and inspect the actual payment record. Follow linked Checkout/PaymentIntent/Charge resources where available. Then inspect the application's order state after webhook processing.

Evidence: Session or payment ID, customer linkage, USD 49.00 expected total, payment status, and one fulfillment result. Do not record real card information or secrets.

Pass condition: A successful payment belongs to the intended customer and exactly one business fulfillment exists. A redirect with no verified payment is a failure; an asynchronous payment still processing is pending, not automatically failed.

Recovery: If the browser disconnects, retrieve the original session or inspect the existing payment. Do not create a new payment merely because the success page did not load. See Stripe test scenarios.

Lab 3 : Create and finalize a manual invoice

Scenario: Invoice CUSTOMER_A for two consulting units at USD 75.00 each, due in 14 days. Fixture tax and discounts are disabled unless the task explicitly says otherwise. The draft subtotal is USD 150.00.

Before acting: Confirm the customer ID and billing terms. Decide whether the authorized task ends at draft, finalization, or delivery. These are separate actions. In a real project, sending an invoice or attempting collection must be explicitly in scope.

Procedure: Open Billing → Invoices or find Invoices via search. Create a draft for CUSTOMER_A, add the approved item and quantity, set the due terms and currency, and review the line items. Save the draft and record its in_... ID. If finalization is authorized, review the immutable billing fields again, finalize, and verify the resulting status and due date. Deliver only through the approved channel and only if requested.

Evidence: Customer ID, invoice ID, line descriptions, quantities, subtotal, tax, discount, total, collection method, and actual due date. For a task ending at draft, prove it remains draft.

Pass condition: Correct terms and arithmetic, no unrelated pending items swept into the invoice, and exactly the requested final state.

Recovery: Correct a draft before finalization. For a finalized error, use the appropriate invoice correction, void, or credit-note workflow under the project policy. Do not mark an unpaid invoice paid to make it look complete. SafeStripe's API sequence is create draft → add explicitly attached items → finalize, using one stable operation ID per step. Stripe's Dashboard invoicing guide describes the relevant controls.

Lab 4 : Diagnose and recover a failed invoice

Scenario: A sandbox renewal has failed. Determine whether it requires a new payment method, customer authentication, or investigation.

Before acting: Read the invoice ID, subscription ID, attempt history, and current status. Confirm that a later successful payment has not already resolved the case.

Procedure: Open the invoice and associated payment information. Record the observed failure or action-required condition without copying sensitive request payloads. Inspect configured automatic retry behavior. Use the task's approved test method or customer recovery flow. After recovery, retrieve the invoice again and inspect subscription status and application access independently.

Evidence: Before and after invoice status, relevant attempt timestamps, recovery action, and current customer-facing state. If no recovery was authorized, provide a diagnosis and recommended next action only.

Pass condition: The outcome is correctly classified, no duplicate collection was initiated, and access matches the approved policy. A pending authentication requirement is reported as pending.

Recovery: Do not run a competing manual retry loop alongside Billing's configured recovery. For recurring-state practice, use Billing simulations and test clocks. Wait for the simulation to finish advancing before interpreting its resulting objects.

Lab 5 : Create a subscription and inspect its lifecycle

Scenario: CUSTOMER_A subscribes to an approved monthly training plan. Choose whether the fixture has a trial before beginning.

Procedure: Confirm the recurring Price ID, interval, currency, quantity, collection method and any trial terms. Create the subscription through approved Checkout or Billing controls. Record sub_..., the initial invoice, the payment state, and the next billing boundary shown by the current API/UI. Verify the application projection after the lifecycle webhook arrives.

Evidence: Customer, Price, quantity, trial/billing dates, status, initial invoice, and application entitlement decision.

Pass condition: The expected subscription exists once, the initial payment/trial state is accurately explained, and access is not granted solely because a subscription object was created.

Recovery: An incomplete initial payment needs its existing confirmation/recovery flow. Do not repeatedly create subscriptions. If a terminal incomplete-expired subscription must be replaced, first reconcile the original obligation and use an explicit new attempt.

Lab 6 : Preview and apply a seat change

Scenario: Move from five to eight seats with the approved immediate proration policy.

Procedure: Inspect current subscription items and pending updates. Record the change proposal and proration timestamp. Generate a preview; note debit/credit, taxes, discounts, total, currency, and collection policy. Apply only the approved proposal. Retrieve the subscription and resulting invoice. If authentication is required, record the pending update and recovery requirement rather than claiming the upgrade is paid.

Evidence: Original quantity, proposed quantity, quote details, accepted timestamp, resulting invoice, final/pending subscription state.

Pass condition: No duplicate item was added accidentally, the correct item was changed, and the resulting bill is explained. The same proration timestamp was used where the API workflow supports it.

Recovery: If another operator changed the subscription meanwhile, stop and produce a new proposal. Do not silently overwrite the competing change. See proration guidance.

Lab 7 : Schedule cancellation

Scenario: Cancel renewal at the end of the paid service period; do not end service immediately and do not refund automatically.

Procedure: Inspect subscription and schedule state. Select the end-of-period cancellation policy. Review the effective date and any pending invoice implications. Save and re-open the subscription. Verify that the cancellation instruction is scheduled and that the current service entitlement remains consistent with the task.

Evidence: Subscription ID, current status, cancellation flag/effective boundary, and customer access policy.

Pass condition: Renewal is scheduled to stop at the intended boundary, with no unintended immediate termination or refund.

Recovery: If immediate cancellation was selected accidentally, document it and follow the project recovery procedure. Do not assert that setting a flag back will revive a terminal canceled subscription. Stripe's cancellation guide covers available workflows.

Lab 8 : Issue and verify a partial refund

Scenario: Return USD 10.00 against the USD 49.00 payment from Lab 2 because of a requested service adjustment. This is a synthetic sandbox refund authorized by the exercise.

Before acting: Verify the exact payment and customer, successful captured amount, earlier refunds, refundable remainder, and whether a dispute is open. Check that this task's refund-request ID has not already been completed.

Procedure: Open the payment detail and choose its refund action. Enter the approved partial amount and reason. Review the confirmation before submitting. Record the refund's re_... ID, status, amount and currency. Re-open the original payment and verify cumulative refunded amount.

Evidence: Original payment ID, prior refunded amount, the new USD 10.00 refund, cumulative total, reason and actual refund status.

Pass condition: Exactly the authorized refund was requested against the correct payment. The operator distinguishes pending from succeeded. A bank-arrival claim requires additional evidence; the Dashboard action alone cannot establish it.

Recovery: If the result is unclear, retrieve the refund or inspect the payment before trying again. Another refund ID is another financial instruction. Refer to refunds.

Lab 9 : Triage a dispute and prepare evidence

Scenario: A sandbox dispute fixture concerns a training order. Prepare a review package; submission is a separate action unless explicitly authorized.

Procedure: Open Disputes and the assigned case. Record the reason, amount, currency, response deadline and linked payment. Check fulfillment/customer communication evidence from the authorized fixture. Match each evidence item to the dispute reason. Preview the response where available, identify missing facts, and save a draft only if that is the assigned outcome.

Evidence: Case ID, deadline with timezone, linked payment, relevant evidence inventory, draft/submitted distinction and any missing requirements. Use only permitted synthetic files.

Pass condition: Correct case, complete reason-specific analysis, truthful evidence, and no unauthorized submission or acceptance of the dispute.

Recovery: Missing evidence should be documented, not invented. Escalate close deadlines through the approved project process. Do not issue an independent refund without understanding dispute-specific restrictions and potential double reimbursement. See responding to disputes.

Lab 10 : Reconcile transactions and a payout

Scenario: Explain the movement from a small set of sandbox payments and refunds into the Stripe balance. If the sandbox does not provide an authentic bank/payout artifact for the exercise, mark bank settlement as unverified.

Procedure: Choose a fixed reporting window, timezone and currency. Export the appropriate authorized transaction report or inspect Balance Transactions. Match each payment, refund, fee and adjustment by identity. Compute net movement and compare with the application records. For an eligible payout exercise, use the payout's reconciliation details and compare the actual bank evidence supplied by the task.

Evidence: Report settings, transaction IDs, gross/fee/net, separate currency totals, payout identity where relevant, and an exception list.

Pass condition: Every included row is matched or explained; cutoff and currency differences are explicit. A total that happens to match while rows differ is not sufficient.

Recovery: Investigate missing rows, duplicated imports, timezone boundaries, pending availability, currency conversion and adjustments. Preserve the original export. Do not overwrite a discrepancy just to balance a spreadsheet. Use Balance and Payout reconciliation documentation to select the right report.

Lab 11 : Investigate a failed webhook delivery

Scenario: A payment is successful but the application order remains pending.

Procedure: Inspect the relevant event in Workbench. Confirm its endpoint, attempt time, HTTP response and environment. Check whether SafeStripe admitted it, whether a worker claimed it, and whether it is pending, done, or dead. Read stable error codes and look up the related operation/order mapping. Fix the actual cause, then replay through the authorized mechanism. Verify one business effect and the resulting order state.

Evidence: Event ID, delivery status, inbox state, root cause, reviewed replay action, business-effect identity and final order status.

Pass condition: The repair changes the intended business record exactly once. An HTTP 200 without a completed effect is not considered a finished repair.

Recovery: For a bad signature, fix body handling or secret selection. For an unknown order mapping, reconcile the API operation. For an account mismatch, repair routing; do not bypass scope checks. See Workbench event delivery inspection.

Independent work and remote handoff

At the beginning of a remote session, record the task version and acceptance criteria. During execution, keep a short decision log. At the end, provide a concise handoff: completed changes, observed final states, evidence references, unresolved issues and next owner. Do not promise completion for a task whose underlying state is still pending.

Use the minimum permissions needed for each assignment. Separate setup fixtures from the evaluated run. If the project changes its rubric mid-run, preserve the original run evidence and record which criteria changed rather than retroactively describing different work.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Operate and review

Human-data tasks, recordings, and evaluation rubrics

What makes a useful task

A realistic task gives a goal, a starting state, constraints, and observable acceptance criteria. It leaves enough judgment to test competence without hiding facts the operator needs. A task that says only “manage Stripe” is too vague. A task that dictates every click measures instruction copying more than operational judgment.

Separate the task prompt shown to the operator from the reference outcome and rubric used by reviewers. Build the rubric from a verified workflow in the assigned environment. The examples here are proposed sandbox tasks; do not claim they are ground truth from an account session that has not been performed.

After you complete a lab, replace each fixture alias with the actual created ID and observed state. A reviewer should be able to tell which claims came from the prompt, which came from the recording, and which remain inferred.

Task prompt schema

json
{
  "task_id": "refund-partial-001",
  "environment": "dedicated sandbox name and account ID",
  "goal": "Issue the approved partial refund and verify it",
  "inputs": {
    "payment_id": "fixture payment ID",
    "currency": "usd",
    "amount_minor": 1000
  },
  "constraints": ["Do not refund any other payment", "Do not contact the customer"],
  "preconditions": [
    "Original payment succeeded",
    "At least 1000 minor units remain refundable"
  ],
  "expected_evidence": [
    "Original payment identity",
    "Refund ID and actual status",
    "Cumulative refunded amount"
  ],
  "stop_conditions": [
    "Wrong account",
    "Open dispute",
    "Prior execution found",
    "Insufficient refundable balance"
  ]
}

The environment and identifiers must be supplied before an evaluated run. A free-form customer name without a stable identifier creates avoidable ambiguity. Amounts must include currency and units.

Prompt A : Partial refund with prior activity

“In the assigned sandbox, inspect payment PAYMENT_A for CUSTOMER_A. The original amount is USD 49.00 and an earlier approved refund of USD 5.00 is already recorded. Issue one additional refund of USD 10.00 for the service adjustment in case CASE_A, using the requested-by-customer reason. Do not cancel the subscription, alter the customer, send a message, or refund another payment. If a dispute is open, the previous refund differs from the stated amount, or case CASE_A is already completed, stop and report the discrepancy. Record the refund ID, actual status, and cumulative refunded amount.”

Reference outcome after valid setup: one new USD 10.00 refund against the intended payment; cumulative refunds USD 15.00; remaining unrefunded amount USD 34.00. “Remaining unrefunded” is not a claim about pending funds or availability. Status may require follow-up rather than immediate success.

Criterion Points Full-credit evidence Partial / zero guidance
Context and identity 15 Correct sandbox, payment and customer IDs visible 5 if context inferred; 0 for wrong object
Preconditions 20 Checks prior USD 5 refund, available remainder, dispute and duplicate case 10 for incomplete check; 0 if knowingly bypassed
Mutation accuracy 30 Exactly one USD 10 refund with correct reason 15 if correct amount but reason missing; 0 for wrong amount/object
Verification 20 Refund ID, status and cumulative USD 15 shown 10 if ID shown without totals; 0 for banner-only claim
Evidence quality 10 Readable trace with timestamps and no sensitive leakage 5 for one missing reference; 0 if unusable
Handoff 5 Concise result and pending issues accurately stated 0 for unsupported completion claim

Critical failures override the score: live-mode mutation in a sandbox task, wrong-payment refund, duplicate refund, unauthorized customer contact, or exposure of real payment credentials. If preconditions fail and the operator correctly stops, evaluate the diagnostic path; do not penalize them for refusing an invalid mutation.

Prompt B : Draft invoice with a deliberate ambiguity

“Create a draft invoice for CUSTOMER_B for two units of the approved consulting Price at USD 75.00 each, due in 14 days. Do not finalize, email, or collect payment. The task fixture specifies no tax or discount. Before saving, inspect the draft total. If current account settings add tax or an unexpected item, report the mismatch and keep the invoice unfinalized. Record the invoice ID and draft status.”

Reviewer emphasis: customer identity, exact Price and quantity, detection of automatic settings, correct draft boundary, and no unauthorized sending. Give 25 points for correct items/currency, 20 for correct customer, 20 for draft-only behavior, 15 for due terms, 10 for detecting/reporting deviations, and 10 for evidence. Finalizing or sending when explicitly prohibited is a critical task-boundary failure.

Do not award full credit to an invoice totaling USD 150 if it accidentally uses two unrelated USD 75 items. Judge record structure as well as totals.

Prompt C : Cancellation timing

“For SUBSCRIPTION_A, schedule cancellation at the end of the currently agreed service period. Preserve access until the effective boundary specified by the contract. Do not cancel immediately and do not create a refund. Verify the subscription ID, current Price, cancellation instruction, and effective date. If a schedule or pending update conflicts with this instruction, stop and report it.”

Rubric: identity and current contract 20, conflict inspection 20, correct scheduling 30, resulting state and date verification 20, evidence/handoff 10. Immediate cancellation or an unrequested refund is a critical failure. Showing active after scheduling is not inherently wrong; the operator must explain scheduled versus terminal state.

Prompt D : Repair a payment/order mismatch

“Order ORDER_A remains pending even though its assigned sandbox Checkout Session shows paid. Inspect the related webhook delivery and SafeStripe inbox. Identify the cause. Apply the provided approved repair procedure, then verify exactly one fulfillment effect. Do not create another payment, alter payment amounts, delete event records, or manually mark the order paid outside the reviewed business handler.”

Rubric: establishes payment/order relation 20, diagnoses delivery versus processing failure 25, follows approved repair path 25, proves one effect and correct order state 20, records limitations 10. A second financial charge, deleted audit evidence, or unreviewed manual fulfillment is a critical failure.

The reference solution depends on the injected failure. Examples include a stopped worker, a missing session binding, or an intentionally failed handler. Do not use the same reference answer for all three.

Prompt E : Read-only dispute review

“Review DISPUTE_A in the assigned sandbox. Identify its amount, currency, deadline, reason, and linked payment. Use the supplied synthetic fulfillment and communication records to prepare an evidence inventory organized by relevance to the stated reason. Do not submit evidence, accept the dispute, issue a refund, or contact the customer. Explain any missing facts.”

Rubric: case/deadline identity 20, factual evidence linkage 30, completeness and missing-fact analysis 20, preservation of the read-only boundary 20, clear handoff 10. Fabricated evidence or unauthorized submission fails the task regardless of presentation quality.

Screen-recording procedure

Before recording, sign in with the approved role and choose the correct sandbox. Close unrelated tabs and chat applications, hide password managers, disable notification previews, and prepare synthetic fixtures. Keep API-key screens, environment files, terminals that display secrets, personal email, and unrelated customer records out of the capture area.

Use the operating system's approved recorder or the project's designated tool. Record one application window when possible. Use readable zoom and a resolution that makes IDs, amounts and statuses legible. Run a short audio/video check. Narrate decisions: “I am verifying the refundable balance before submitting” is more useful than narrating every cursor movement.

Suggested sequence:

  1. Show task ID, account context and intended outcome.
  2. Inspect starting records and preconditions.
  3. Explain the decision before the irreversible step.
  4. Perform the authorized action once.
  5. Re-open the result and verify identity, amount, currency and state.
  6. Summarize completed work, pending state and evidence references.

Pause only according to project rules. If a pause conceals relevant setup or changes, disclose it. Do not edit a recording to make an error look like it never happened. Corrections can demonstrate competence when honestly explained.

Review the entire clip before sharing. If a secret appears, stop distribution and follow the incident procedure; blurring a later export does not revoke an exposed key. Use the approved private storage, access group and retention period. Share only where the project directs. A publicly accessible video link is not an appropriate default for financial workflow evidence.

Evidence manifest

text
Run ID: refund-partial-001-run-02
Prompt version: 1.1
Rubric version: 1.0
Account / sandbox: supplied fixture context
Recording: approved private artifact reference
00:00–00:25  Task and environment
00:25–01:10  Payment identity and prior refund
01:10–01:45  Preconditions and authorized action
01:45–02:20  Refund ID, actual status and cumulative amount
Observed deviations: none / factual description
Unverified claims: bank arrival, if no bank evidence exists
Reviewer: assigned reviewer ID

Actual timestamps must come from the completed recording. Do not prefill them as if the run occurred.

Reviewer calibration and disagreement

Have two reviewers independently score a small calibration set before evaluating many runs. Compare criterion-level disagreements, not just overall scores. A 90 and a 70 may differ because one reviewer assumed that “refund submitted” means “refund succeeded.” Fix the criterion or evidence requirement rather than averaging an unresolved semantic disagreement.

For each finding, record the claim, evidence timestamp, criterion, severity and rationale. Distinguish a task defect, a system failure, an operator error and missing evidence. Avoid inferring competence, intent or honesty from speed, accent, narration style, or unrelated personal information.

Use a four-state outcome where appropriate: completed, correctly stopped, failed, or insufficient evidence. A safe and accurate stop can be the correct outcome of an invalid task. “Insufficient evidence” means the reviewer cannot establish the fact, not that the operator necessarily performed it incorrectly.

Capstone

Set up a fictional customer, one-time payment, recurring subscription, manual invoice, partial refund and failed renewal. Inject a duplicate webhook and one missing local mapping. Ask the operator to complete the authorized operations, diagnose the mismatch, record a walkthrough and create a new prompt/rubric based on their actual run.

Acceptance requires correct financial identities and totals, no duplicated effect, clear pending states, an evidence manifest, and a rubric another reviewer can apply. The engineer must also explain the lost-response recovery path and the production controls still required. This capstone connects practical Stripe operations, engineering reliability and human-data evaluation in one inspectable artifact.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Operate and review

Testing, incident response, and release review

The SQL implementation details on this page describe the original PostgreSQL API. For the portable SQLite, PostgreSQL, MongoDB and Firestore setup, start with database adapters and framework integration. The current local sample defaults to SQLite; legacy SQL example commands use the :legacy suffix.

Test layers establish different facts

Layer What it establishes What it cannot establish
Strict compilation Internal type/API compatibility with installed declarations Processor behavior or business correctness
Offline unit/contract tests Identity, authorization, input, hashing and failure logic Real Stripe account configuration
Embedded PostgreSQL tests Executable SQL and transaction behavior on a PostgreSQL engine Independent networked connections and deployment failure modes
Real PostgreSQL tests Multi-connection claims, row locks, constraints and transaction behavior Production topology, failover or capacity
Sandbox Stripe tests Actual API permissions, resource schemas and simulated payment flows Real issuer behavior, bank settlement or every production edge case
Production canary/reconciliation Real operational and financial outcomes Proof that every future case is safe

The repository's tests exercise malformed signatures, tampering, secret rotation, scope and API-version rejection, duplicates, distinct events producing the same effect, rollback, stale workers, review cutoff, outbox ambiguity, reconciliation and framework adapters. Use VERIFICATION.md for the exact executed results.

Failure-injection matrix

Experiment Expected behavior Evidence
Send identical event ten times One inbox identity Unique event row; duplicates acknowledged
Send two event types for one order One local fulfillment One business-effect key and one delivery intent
Change price under same operation ID Conflict before new API mutation PAYLOAD_CONFLICT; unchanged remote-call count
Interrupt after remote success Retry original key Same remote object; no second purchase
Crash after claim Lease can be reclaimed New fencing token; old token cannot commit
Throw after local write Transaction rolls back No partial effect or notification intent
Stop database at ingress Non-success response No falsely acknowledged event
Deliver older subscription event last Current state preserved Projection reflects current retrieval
Cross tenant/customer/account Denied No remote write, no leaked response
Restore backup before payment Manual recovery boundary Reconciliation completes before writes reopen
External recipient accepts then disconnects Same delivery key on retry Recipient deduplication prevents second effect
Repeated poison job Dead letter after budget Visible state and operator-owned replay

Sandbox exercises should additionally cover authentication-required cards, declined payments, delayed methods, trial transitions, renewal failures, partial refunds, pending refunds, subscription changes and tax configuration. Keep deterministic fixtures separate from recordings and manual experiments. Use test clocks for eligible recurring scenarios; real-time waiting is slower and less reproducible.

Runbook: paid customer, missing service

First establish the payment identity, account and environment. Read the order's session binding and current Stripe state. If the payment is not actually successful under the product's policy, explain the pending condition rather than forcing access.

If payment is confirmed, inspect the event's delivery history, inbox row, job attempts, dead-letter state and business-effect guard. A transport failure needs delivery repair; a stopped worker needs worker recovery; an unknown session mapping needs command reconciliation. Use the same transactional business handler for repair. Verify exactly one resulting fulfillment and one external delivery identity.

Do not create another payment or delete the guard. If a manual action is necessary, record the operator, reason, supporting IDs and approved procedure. Communicate the observed outcome without claiming bank settlement or service delivery beyond the evidence.

Runbook: operation requires review

Locate the durable operation by scope, tenant and operation ID. Inspect Stripe request logs and the associated business record. Determine whether the operation created a remote object, failed before execution, or remains uncertain. Search is supporting evidence; absence from an eventually consistent search result is not proof of no side effect.

If the exact successful resource is proven, verify its account, tenant mapping and immutable commercial parameters, then invoke the privileged review-binding action with actor and reason. If no remote mutation can be established conclusively, keep the case open or follow an approved new-attempt policy. Do not simply shorten timestamps, reset the row, or allocate another ID until the uncertainty is resolved.

SafeStripe's resolveForReview records the claimed resolution and an audit entry. It trusts the privileged caller's investigation; it does not perform the remote proof itself.

Runbook: signature failures

Check whether Express parsed JSON before the webhook route, whether a proxy altered or decompressed the body, whether the configured secret belongs to the listener/destination, and whether clocks are synchronized. Confirm mode, account, API version and snapshot versus thin payload. Inspect safe error metrics without dumping payloads or secrets.

Deploy the correction, validate a new signed request, and replay legitimate missed events. Do not change the route to accept unsigned JSON or disable checks to clear an alert. If a webhook secret was exposed, rotate it and investigate which false events might have been admitted during exposure.

Runbook: duplicate fulfillment or refund

Stop the affected business mutation path if the defect is ongoing. Preserve operation rows, effects, event records, logs and approvals. Determine whether the duplicate arose from two business IDs, two different events sharing no business guard, missing transaction boundaries, a lost database history, or an operator action outside the application.

Scope affected customers using business/financial identities rather than raw event counts. Reconcile remote payments and local effects. Any compensation is a new authorized action with its own identity and audit trail. A duplicate charge may require a refund; duplicate fulfillment may require a different commercial remedy. Do not automatically compensate without understanding the actual side effects.

Runbook: backlog or rate-limit incident

Measure arrival rate, processing rate, oldest age, Stripe latency, database pool wait and errors. Pause nonessential imports and backfills. Reduce retry amplification. Increase workers only when the dependency and database can absorb the added concurrency. If one resource is hot, more workers may worsen lock contention.

After recovery, calculate how long the backlog will take to drain and prioritize financially sensitive work. Verify no jobs aged out of their recovery window and that invoices or entitlements were not left inconsistent. Review the incident against the service objective, not just whether CPU returned to normal.

Runbook: key or recording exposure

Revoke or rotate the exposed credential through the authorized Stripe/security process. Restrict the exposed recording or artifact, preserving evidence according to the incident policy. Inspect relevant request history and financial actions. Rotate dependent credentials only where the incident scope warrants it, and validate services with replacement credentials.

Do not rely on deleting a repository commit or blurring a new video copy to revoke a secret. Record the exposure window and affected capabilities. The repository's secret check is an additional guard, not an incident detector or a substitute for key management.

Production release review

The release owner should verify a concrete implementation of authentication and billing authorization; approved tax and entitlement policies; restricted credentials; database backup/restore; durable ingress; supported event inventory; outbox consumer; reconciliation schedule; monitoring and on-call ownership; and a sandbox flow for every offered payment method.

Inspect the exact artifact being released: lockfile, API version, migration set, route configuration, secret injection, worker concurrency and retention jobs. Review pending updates and historical events before a version upgrade. Deploy gradually, inspect real outcomes, and preserve a rollback path compatible with data already written by the new version.

Do not label unexecuted cloud CI, a proposed load target, or a sandbox-only result as a completed production validation. Evidence should distinguish design, implementation, local testing, external-system verification and live operation.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Operate and review

Stripe idempotency is not the same as an idempotent payment system

A customer asks for a refund. Your server sends the request. Stripe accepts it. Before the response reaches your server, the connection closes.

Your logs say the request failed. The customer's money may already be on its way back. Sending a new refund with a new identity can make the mistake worse.

This is the point where a payment integration becomes a state-management problem.

Keep the intent when the answer disappears

Give the refund a business identity before making the request. For example, refund:order-842:approval-17 identifies one approved refund. A browser retry, another server process and a restarted worker must all use that identity and the same approved amount.

SafeStripe records the operation in your database and derives its Stripe idempotency key from its scope, tenant, operation ID and operation kind. A fingerprint detects changed parameters. After a successful write, it retains the Stripe resource ID; a later replay retrieves that resource.

If the response disappears, the operation remains recoverable. Retrying uses the original key. It does not guess that a timeout means nothing happened.

This depends on retaining the local record. It also has a deadline: Stripe can prune idempotency keys after at least 24 hours. SafeStripe's automatic recovery window is shorter. An unresolved operation outside that window needs reconciliation, not an automatic write with a fresh key. See Stripe's idempotency contract and operation identity.

A webhook answers a different question

Stripe can notify your application after the browser leaves. That event is evidence about remote state, but its delivery is not a promise that your fulfillment ran once.

The same event can arrive several times. Two different events can also describe the same business outcome. Deduplicating only evt_… therefore solves delivery duplication, not duplicate fulfillment.

SafeStripe verifies the original signed bytes and durably admits an accepted event before acknowledging it. A worker then claims it with a lease. If the process disappears, another worker can recover it after expiry. An ownership token prevents the old worker from committing as if it still owned the job.

The handler still needs a business key such as fulfill:order-842. Use that key for an effect guard, even if multiple event types can reach the same handler.

Put the local decision in one transaction

Suppose fulfillment grants a subscription entitlement and sends a receipt. Sending the receipt during the database transaction creates a dangerous gap: the email service can accept the message before the database rolls back.

Instead, the transaction writes the entitlement, records the effect key and adds a receipt intent to the outbox. Those local records commit together. A dispatcher sends the message afterward.

This boundary covers records written through the same SafeStripe storage transaction. It does not automatically absorb arbitrary application writes made through a different ORM, database or transaction.

The outbox cannot promise one delivery

The dispatcher has the same ambiguous-response problem as the refund endpoint. A recipient can accept a receipt and lose its acknowledgment. Retrying is necessary to avoid losing the message, but it can deliver it twice.

The recipient must durably deduplicate by the supplied idempotency key. SafeStripe provides at-least-once delivery. It does not turn an arbitrary HTTP endpoint into an exactly-once recipient.

Test the gaps, not just the successful response

The process failure suite starts actual child processes and kills them at explicit checkpoints: after a claim, during an uncommitted effect transaction and after a simulated recipient commits. The assertions inspect stored fulfillment, effect and outbox counts after recovery. They do not stop at a successful HTTP response.

The optional sandbox suite sends a real customer write through the Stripe SDK, deliberately discards its successful HTTP response, and retries the same operation. It then checks the remote customer count. This suite requires a dedicated sandbox; its existence does not mean it has been run. Consult the verification record for actual evidence.

These layers have distinct identities and responsibilities:

Layer Stable identity Protects against
Stripe operation Business operation ID plus account/tenant scope Repeating a remote mutation after an uncertain result
Webhook inbox Event ID plus account scope Processing repeated delivery as new work
Local effect Business outcome key Different events repeating one local outcome
Outbox recipient Delivery idempotency key Repeated delivery repeating a downstream effect

Good operational practice keeps these identities visible without logging secrets or sensitive payloads. When something fails, an operator should be able to find the intent, the remote resource, the event and the local decision—and know which one is still uncertain.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Operate and review

Release and sandbox evidence

SafeStripe 0.3 is in stabilization. A green unit suite is one release input. The naming transition, real sandbox walkthrough and public deployment are separate gates.

Run the real Stripe service checks

Use a dedicated sandbox containing no real customer information. A restricted key needs account read; customer, product, price, Checkout Session, PaymentIntent, refund, subscription and billing portal access required by the test. You can also explicitly select a standard sk_test_… secret key for this disposable sandbox. Save a default portal configuration in that sandbox first. These tests create test objects and archive or cancel their fixtures afterward. Stripe retains the associated history.

Set STRIPE_SECRET_KEY, the expected STRIPE_ACCOUNT_ID, and STRIPE_E2E_CONFIRM=disposable-sandbox privately in your local environment, then run:

sh
npm run test:stripe:e2e

Restricted test keys are accepted by default. To use a standard test secret key locally, also set STRIPE_E2E_ALLOW_SECRET_KEY=true privately before running the command. The runner rejects live keys, publishable keys, a different account and a standard secret key without that explicit opt-in. It uses the actual Stripe SDK and test API. It tests an ambiguous customer write by discarding a successful remote HTTP response, then verifies one remote customer after replay. It also checks hosted and Elements Checkout, refund, subscription and portal creation. uiMode: custom maps to Stripe’s elements parameter on the pinned API. Missing permissions fail the run; they do not produce a passing skip.

pk_test_… is the publishable key for the browser payment form. This server-side suite does not use it. Test secret keys can read and change sandbox data: keep them in your private environment or GitHub secrets, never source files, browser code, chat or a public issue. Using a test secret key does not remove the disposable-sandbox confirmation or expected-account check.

Its report in artifacts/stripe-e2e.json records the SDK, API version and completed checks without keys, portal URLs or customer payloads. The local operation database is under ignored .data/. If the runner is killed or cleanup fails, inspect that sandbox for SafeStripe E2E products and synthetic example.invalid customers before another run.

The retained service report records six successful checks on 6 October 2026. Its temporary sandbox limitations are explicit; it is not evidence that the protected release gate has passed. The benchmark report records actual PostgreSQL measurements and recovery counts separately.

For a locally provisioned, unclaimed Stripe CLI sandbox, the runner also accepts STRIPE_E2E_TEMPORARY_SANDBOX_FILE: a private JSON file containing the CLI's provisioning response. Keep it under ignored artifacts/, set its permissions to owner-only, and never attach it to an issue. The manifest must contain a temporary rkcs_test_ key, the expected account ID and an unexpired short lifetime. This mode records that account details cannot be read remotely. It creates a default portal fixture only in that temporary sandbox. Its evidence is useful for API compatibility and replay; the release workflow does not accept it as account-verified release evidence. The public demo accepts normal test keys, not these temporary CLI credentials.

The first protected run verified the owner-configured account and one remote customer after response loss, then failed with StripePermissionError during Checkout creation/replay. It is retained as a failed run. After the maintainer explicitly selected the dedicated sandbox's test secret key, the second protected run passed all six service checks on clean revision 5f06e28 at 21:04 UTC on 6 October. Account identity was verified, and no cleanup failure was reported. This result applies to that commit; the release workflow still requires successful checks on the exact eventual tag commit.

The GitHub workflow Dedicated Stripe sandbox is manual. In Settings → Environments → stripe-sandbox, save STRIPE_SANDBOX_ACCOUNT_ID as a secret or variable, then configure one of these credential choices:

Workflow key_type Environment secret Value
restricted (default) STRIPE_SANDBOX_RESTRICTED_KEY A dedicated rk_test_… key with the permissions above
secret STRIPE_SANDBOX_SECRET_KEY The dedicated sandbox's sk_test_… key

Open Actions → Dedicated Stripe sandbox → Run workflow, select main, and choose the matching key_type. Review the exact commit and approve the protected job. Only the selected key is supplied to the test step. Never make either secret available to arbitrary pull-request code. Account verification remains required in both modes.

This script does not complete a browser Checkout or receive a real network webhook. Those checks belong in the deployed demo: pay with a test card, confirm the verified Firestore receipt, resend the event, restart the host, and check the same receipt again. Record the URL, commit, time and observed result without exposing payment data.

The separate public payment lifecycle suite automates browser payments, actual signed network deliveries, refunds, delayed ACH outcomes and test-clock renewal recovery against the published package and deployed Firestore demo. Its workflow is protected by the same sandbox environment and records its deployment boundary separately from the service release gate.

Release provenance

The Publish verified release workflow requires an existing annotated tag with a GitHub-verified signature, a tag commit on main, a matching package version and an npm trusted publisher. Before building, it requires successful database CI, CodeQL and account-verified Stripe service evidence on that exact tag commit; a passing run from an older revision is insufficient. It then runs the local release checks again. It generates a CycloneDX SBOM and SHA-256 checksums, publishes with provenance, and attaches the evidence to the GitHub release.

Before enabling it:

  1. Set required reviewers and deployment restrictions for the npm-release GitHub environment. Require the database and security CI jobs on the release commit.
  2. Configure your own signing identity and register its public key with GitHub. Create and verify an annotated signed tag; do not substitute another person's identity.
  3. If the unscoped package does not exist, complete its first checked publication through your npm account, then configure its trusted publisher for this repository, release.yml and the npm-release environment. Explicitly allow direct publishing: newer npm trusted-publisher configurations otherwise default to staged publishing. A local first publication has no CI provenance; keep that limitation visible. If provenance on the first release is required, arrange an approved first-publication CI path before publishing.
  4. Dispatch the workflow for an unpublished version's tag. A version published during initial setup cannot be published again: prepare and verify a subsequent distinct version for the trusted workflow. Confirm the npm package, provenance statement, GitHub artifacts and website all refer to the same version before marking the release published.

The workflow uses npm 11.15.0 on Node 24 and does not restore a dependency cache in the publishing job. Trusted publishing requirements can change; check npm's current setup when configuring the account. Credentials are deliberately absent from the workflow.

A verified tag identifies a signer. Provenance links the package to a build. An SBOM describes dependencies. None is a security audit. CodeQL, dependency review, Dependabot, runtime audit and the repository's limited Stripe-secret scan provide additional signals; review and resolve their findings.

A three-minute recovery demonstration

Start with an isolated PostgreSQL test database. Docker is optional; a local PostgreSQL service or disposable hosted database works. Keep its connection string in the environment as CHAOS_DATABASE_URL.

sh
node --import tsx --test --test-name-pattern='postgres: SIGKILL at claim' tests/chaos/recovery.test.ts

Explain the test as it runs: worker A claims the job; the parent sends SIGKILL; the database retains the lease; after expiry worker B commits fulfillment, an effect guard and one outbox intent. Show the assertion in the source alongside the result. Then run the duplicate-admission case:

sh
node --import tsx --test --test-name-pattern='postgres: 100 repeated' tests/chaos/recovery.test.ts

The repeated-event test includes 20 competing PostgreSQL child processes. Show the final stored counts. This is an executable demonstration script, not a claim that a video or independent review already exists.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Operate and review

Payment lifecycle verification

A successful API request is only one step in a payment. The public lifecycle suite follows the payment through Stripe, the signed webhook endpoint, the worker and the saved Firestore state.

It uses the published safestripe@0.3.0 package in the deployed demo. The test runner comes from this repository. Those are separate revisions: the report records the runner commit, backend commit and installed package version. A passing run does not verify an unpublished package built from a newer source commit.

The journeys

Journey What the test must establish
Hosted card purchase Chromium completes Stripe Checkout; the real signed event creates a Firestore receipt for the approved customer, order, Session, USD amount and currency
Duplicate delivery The official Stripe CLI requests ten replays; ten additional authenticated duplicate admissions are recorded, while the original receipt and paid time remain unchanged
Decline and retry An insufficient-funds card leaves the order unpaid; a successful retry uses the same Checkout Session and produces its receipt
Partial refund and replay A 250-cent refund succeeds and reaches its signed Firestore state; retrying its business operation returns the same refund
Remaining refund A second 250-cent refund closes the original 500-cent payment; Stripe's charge shows the full refunded amount while the original sale receipt remains intact
Bank payment processing An ACH fixture remains processing with no received amount; cancellation is saved after Stripe's signed event
Bank payment success The ACH fixture starts processing, later succeeds remotely and reaches the signed Firestore state with the expected received amount
Bank payment failure The ACH fixture starts processing, later fails remotely and reaches the signed failure state without a received amount
Subscription start A saved test payment method pays the initial subscription invoice; the signed invoice event updates Firestore
Failed renewal and recovery A test clock reaches the next period, the renewal actually fails, and a corrected method pays that invoice
Out-of-order delivery The actual paid-invoice event arrives before the earlier failed-invoice event; the latter retains its old snapshot but cannot replace the current paid state
Cancellation Stripe cancels the fixture subscription; the signed event produces the durable canceled state

The delayed bank fixtures use Stripe's test tokens and synthetic mandate details. The runner creates and confirms its own ACH PaymentIntents through the Stripe SDK, then checks their genuine signed deliveries through the published SafeStripe receiver, worker and Firestore adapter. These checks verify asynchronous admission and saved state; they do not verify an ACH creation or confirmation command in the wrapper. The wrapper's creation command returns an unconfirmed intent using the account's dynamic payment methods. No real bank account or customer information is used. The suite does not change merchant-wide payment settings or enable products on an account; its sandbox must be eligible for ACH Direct Debit. See Stripe's ACH test options.

The separate service suite verifies customer response loss and replay, hosted and Elements Session creation, refund replay, subscription creation and portal ownership. The public Elements walkthrough includes a card decline and a completed authentication challenge. Synthetic regression tests exercise rollback, worker ownership and stale snapshots; they are retained separately from real Stripe observations.

Run the public suite

Use the dedicated disposable sandbox configured for the protected service workflow. The lifecycle workflow also needs customer, catalog, PaymentIntent, subscription, invoice, refund, payment method, Test Clock and Webhook Endpoint access. A standard test secret key requires an explicit secret selection. Neither secret nor restricted test keys are public credentials.

  1. Deploy the reviewed demo revision on Render and Vercel. Its authenticated status response includes the backend's Render commit and installed npm version.
  2. Open Actions → Public Stripe payment lifecycle → Run workflow on main.
  3. Set demo_commit to the full deployed backend commit and select the configured key type.
  4. Review and approve the protected stripe-sandbox job. The workflow installs Chromium only on its isolated CI runner.
  5. Inspect the stripe-lifecycle-report artifact. All twelve checks, account verification, matching deployment and fixture cleanup must pass. A timeout, unavailable payment method or permission error is a failure, not a passing skip.

The runner creates its own customer, prices, webhook destinations and two private demo workspaces. It never uses an existing visitor's payment records. The public frontend proxy carries authenticated API calls; Stripe delivers signed events directly to the Render endpoint. The runner holds workspace cookies in memory. Keys, signing secrets, Checkout URLs, client secrets and raw customer payloads are excluded from its output.

The card journey, each bank outcome and the subscription journey run independently after shared setup. A browser failure does not hide the bank and renewal checks. Card replay runs after decline and refund checks so a delivery timeout does not prevent those checks. The report retains every failed checkpoint and the checks that completed; any failure keeps the overall result failed. All twelve checks and cleanup are required for a passing run.

Refunds or cancellations close the one-time payment fixtures. The runner deletes its webhook endpoints, disconnects its demo workspaces, deletes synthetic customers and test clocks, and archives its prices and products. Stripe keeps financial history. A private fixture journal is written before creation and updated atomically as resource IDs are received. Its one-day artifact contains no credentials. If the process stops before a creation response arrives, the journal's run ID can identify tagged Stripe fixtures. Lost browser cookies cannot be recovered from it; interrupted public workspaces use the server's one-hour expiry and cleanup. Do not treat an interrupted run or failed cleanup as complete.

The official CLI replay runs with closed input and a bounded native process. The runner validates each returned sandbox Event before discarding its payload; an API error cannot pass merely because the process exits successfully. The report keeps only identity-validation results and numeric delivery counts. It observes each duplicate admission before requesting the next replay, with a shared three-minute deadline. Ten additional duplicate admissions are required before counting replay as passed.

How the demo avoids stale state

An event describes the object when that event was created. A failed invoice snapshot may arrive after the invoice has been paid. The demo reads Stripe's current object and writes that status to a customer-scoped Firestore record. It reads the shared record before the remote lookup so competing transactions conflict and retry rather than silently commit an earlier read after a later one.

The original snapshot status remains in the minimal event record for diagnosis. The saved current status drives the aggregate record. Your application still supplies its own entitlement policy: an active subscription does not automatically authorize every product or user.

For the ordered invoice check, the runner temporarily enables only invoice.paid on its own fixture endpoint. It waits for that durable paid record and verifies that the older failure has not been admitted. It then restores the fixture's event list, requests the older signed failure and requires its saved timestamp to be later than the paid record. The report keeps those timestamps without event or invoice identifiers. Resend request order alone is insufficient evidence of receiver order.

Signed admission counts are demo diagnostics. They add a transaction after the inbox write and before acknowledgment. If that diagnostic fails, Stripe gets an error and can retry; the inbox job is already durable. Business effects and receipts use their own keys and transaction boundaries. An increased delivery count does not represent another payment or fulfillment.

Coverage boundaries

This is selected lifecycle coverage, not a claim that every Stripe capability or payment method has been tested. Manual capture and partial capture, disputes, reversal policies, failed refunds, subscription schedules, pause/resume, tax decisions, Connect money movement and country-specific methods need their own application scenarios. The package does not currently expose a dedicated capture or dispute-management command. Do not replace those gaps with synthetic events and describe them as real end-to-end tests.

Production review also needs the application's authorization and fulfillment rules, its database restore procedures, actual infrastructure limits and independent security review. The public Render service is an evaluation environment; these checks are not a capacity or uptime commitment. See the release assessment.

Recorded results

On 7 October 2026 at 09:32 UTC, the protected workflow passed all twelve journeys, remote account verification and fixture cleanup. The original sanitized report identifies clean runner revision a79d70b, deployed demo revision 8b01d90, published safestripe@0.3.0, Stripe SDK 22.6.2, API 2026-08-26.dahlia and Node 22.23.3.

The card event's admission count rose from one to eleven, with ten duplicates. Its receipt and original paid time stayed unchanged. A declined card recovered in the same Session. Two 250-cent refunds closed the original 500-cent charge; replay returned the first refund and Stripe retained only two refunds. All three delayed ACH outcomes and all four subscription checks passed.

The failed renewal event had not been admitted when the recovered invoice was already saved as paid. The paid record was written at 09:32:13.863Z; the older failure was recorded at 09:32:18.782Z with its original open snapshot, while the current invoice remained paid with 1,000 cents received. These are server observation times, not customer-facing payment timestamps.

An earlier full run passed at 09:21 UTC before the independent admission/timestamp assertion was added. The attempt history retains both passing reports and eight failed runs. Hosted form selectors, dynamic bank-method configuration and unobserved duplicate deliveries failed during runner development; they were corrected and rerun. Failed attempts are not counted as passing coverage. Every retained attempt completed its fixture cleanup.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Operate and review

Review an integration before adopting it

Independent review is still open. The following exercises give an outside developer something concrete to test and a useful way to report findings. A maintainer running these exercises is a self-review, not an independent audit.

Try the quickstart without coaching

Use a new folder and a dedicated Stripe sandbox with synthetic customer details. Follow Make your first payment, starting a timer before installation. For a separate application, install safestripe@0.3.0 from npm and record that version. The repository tutorial also includes the source examples and development tooling; record its commit. Do not substitute the older scoped 0.2.0 package.

Try to reach a paid hosted Checkout, a verified webhook and one committed receipt. Record each place you needed help, including an unclear instruction. Save the time to first successful receipt. Run the same operation again and confirm that its Stripe identity stays the same. The five-minute onboarding target has not been established by outside testing yet.

Item What to record
Environment OS, Node, package version and storage adapter
Installation source Registry version, or archive checksum and source commit
Elapsed time Install, configuration, Checkout, webhook and first receipt
Blocker Step, expected result, observed result and help needed
Recovery Whether a retry reused the existing operation or needed a deliberate new action

Do not include API keys, client secrets, customer data, private dashboard links or service-account files in a public report. Replace object IDs with consistent labels when a finding does not require them.

Review the reliability boundaries

Use disposable storage and test keys. Start with the five contracts, architecture and threat model.

Exercise Expected result Where to start
Retry one refund after losing its response Same operation and immutable amount; no second refund scripts/stripe-e2e.ts
Change the terms under an existing operation ID Conflict before another mutation tests/operations.test.ts and tests/storage.test.ts
Request another tenant's customer or payment Application authorizer denies it; no Stripe write src/transport.ts and your application policy
Supply altered bytes or an expired webhook signature Rejected before admission tests/webhooks.test.ts
Stop storage before webhook admission No successful acknowledgment tests/webhooks.test.ts and framework adapter tests
Kill a worker after claim and before commit Recoverable lease; one committed effect and outbox intent tests/chaos/recovery.test.ts
Reuse the expired worker's ownership token Stale completion rejected Storage conformance tests
Deliver different events for the same order One effect under the shared business key PostgreSQL contention case in the chaos suite
Accept an outbox message, then lose the response Delivery may repeat; receiver's durable guard applies once Outbox SIGKILL case in the chaos suite
Run two migration processes One immutable migration history tests/production.test.ts
Restore storage from before a remote write Writes stay suspended until an operator reconciles the gap Restore runbook and application operating procedure

The library requires an application authorizer; it cannot infer ownership from a Stripe ID. External calls inside a transaction callback are unsafe because the database may retry the callback. Review the integration's code as well as the library.

Report a result that someone can reproduce

For a documentation or usability problem, open a GitHub issue. Include the version, environment, shortest reproduction, expected behavior, actual behavior and the effect on the integration. Name the verification layer: mock, local database, real Stripe test API or deployed journey.

For a vulnerability, use the private route in SECURITY.md. Do not post an exploit containing credentials or other users' data. Keep a failing regression with a fix when possible, and retain failed benchmark observations rather than publishing only successful runs.

A useful review record names the reviewer with their consent, the revision and boundaries examined, findings, fixes and unresolved risks. No outside findings, user counts or endorsements are implied by this guide.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Reference

Library contracts and extension guide

Portable API added in 0.2

Export Purpose
createSafeStripe(options) Configure the SDK, resolve account scope and connect a portable store
billing.storage Operations, jobs and application billing transactions
billing.webhooks(options) Receiver bound to the same account and storage
billing.worker(handlers) Worker whose handlers receive BillingTransaction
sqliteStorage({ filename }) Local Node SQLite file; /storage/sqlite
postgresStorage({ db, migrate? }) Portable SQL records; /storage/postgres
mongoStorage({ client, database, collection? }) MongoDB transactions; /storage/mongodb
firestoreStorage({ db, collection? }) Cloud Firestore transactions; /storage/firestore
SafeCheckout React payment form; /react

SetupOptions requires secretKey, storage, appOrigin and authorize. Optional fields include accountId, connectedAccountId, allowLocalhost, gate and observer. Account discovery makes one server API call per initialization. Cache the result/promise in your application.

Portable storage options are leaseSeconds (default 120; shared with operation and job leases), retryWindowSeconds (default 82,800, maximum 82,800) and maxAttempts (default 8). The combined store requires a lease of at least 30 seconds. Its JSON payload limit is 512,000 bytes. BillingTransaction offers get, set, effectOnce, enqueue, scope and a database-derived now timestamp. It does not expose arbitrary native database queries.

createCheckout accepts optional uiMode: 'hosted' | 'custom'; hosted is the default. A custom Session supplies the client_secret required by SafeCheckout. The frontend component accepts publishableKey, clientSecret, children, appearance, className, style, buttonLabel and optional display-only onComplete.

See database setup, framework routes, payment UI and recipes. The reference below retains the original SQL classes for compatibility; they use separate tables and are not automatically migrated into portable storage.

Core construction

Use createStripeClient(key, livemode) for the pinned SDK settings. Construct PostgresOperations and PostgresJobs with a pg.Pool or an implementation of the exported Database interface. Construct SafeStripe with the SDK, scope, operation store, trusted origin and mandatory authorizer.

ts
const safe = new SafeStripe({
  stripe,
  scope: { platformAccountId, connectedAccountId, livemode: false },
  operations: new PostgresOperations(pool),
  appOrigin: 'https://your-application.example',
  authorize: yourBillingAuthorizationPolicy,
});

This is an integration sketch; the fully executable composition is in examples/shared/runtime.ts. The authorizer receives { actor, scope, action, resources, parameters }. Reject unknown actions and resource types. The normalized parameters differ by action: some are Stripe-style names such as payment_intent, while subscription-change proposals use subscriptionId and itemId. Validate the expected shape within your policy.

Actor contains tenantId, actorId and operationId. The actor identity is audited by your application; SafeStripe's command table stores tenant/operation identity but does not automatically record a full business approval history. Use a separate append-only audit mechanism for commercial decisions.

Wrapped operations

Method Required input after actor Semantics
createCustomer email; optional name Durable create; replay can return a deleted-customer marker if deleted later
createCheckout customerId, mode, items, reference Hosted Checkout; server-configured success/cancel origin; dynamic methods
createPaymentIntent customerId, amount, currency Creates an unconfirmed intent; amount must be an authorized minor-unit integer
createRefund paymentIntentId, amount; optional reason Explicit partial/full amount; creation result is not bank settlement
createInvoice customerId, daysUntilDue Draft, manual collection, automatic advancement off, unrelated pending items excluded
addInvoiceItem customerId, invoiceId, priceId, quantity Explicitly attaches the item to a draft invoice
finalizeInvoice invoiceId Finalizes with automatic advancement off; does not explicitly send an email
createSubscription customerId, priceId, quantity Direct Billing flow with default_incomplete; application handles confirmation
previewSubscriptionChange subscriptionId, itemId, priceId, quantity, prorationDate Read/preview; checks item membership; no durable mutation record
updateSubscription same proposal fields Immediate invoice, pending update if payment incomplete; not a universal change policy
cancelSubscriptionAtPeriodEnd subscriptionId Sets the future cancellation instruction
createPortalSession customerId Fresh, authorized short-lived session; URL is not persisted by the operation store

Except preview and ephemeral Portal/onboarding access-session creation, mutations use the durable command protocol. Tax inspection is read-only. Basic meter ingestion replays a stable acknowledgement rather than retrieving an event resource. Stable operation IDs bind both method kind and normalized parameters. Reusing an ID for another method conflicts. Replays retrieve current resource state. They do not return a historical snapshot of the original result.

The library deliberately exposes the underlying official SDK for unsupported API calls. Calling it directly bypasses the wrapper's command protocol and authorization checks; do not claim those controls apply to arbitrary SDK calls. Add another narrow, reviewed wrapper method with contract and failure tests when a new domain requires durable financial mutation.

Error contract

Code Typical HTTP status Caller behavior
INVALID_INPUT 400 Correct the input; do not mutate a previously bound operation
FORBIDDEN 403 Fix authenticated permissions or resource mapping
PAYLOAD_CONFLICT 409 Investigate reused identity or changed immutable terms
BUSY 409 or 503 Back off; reuse the same operation identity
REVIEW_REQUIRED 409 Investigate remote outcome before any replacement mutation
LEASE_LOST 409 Current worker must stop; another owner may have recovered
INVALID_WEBHOOK 400 Inspect signature/scope/version/body contract
BODY_TOO_LARGE 413 Review ingress limits and legitimate event size
UPSTREAM_FAILED 502 Treat outcome as potentially ambiguous; preserve the operation identity
TEMPORARILY_UNAVAILABLE 503 Infrastructure/unknown failure; response contains no internal details

Errors intentionally expose stable codes rather than raw Stripe or SQL messages. Configure separate restricted telemetry for request IDs and diagnosis. An optional observer receives safe operation, job, and worker events. It is a hook for your exporter; it does not map every issuer decline to customer-facing instructions. A direct payment-confirmation product needs a carefully reviewed, customer-safe error mapping.

Webhooks

WebhookReceiver requires one trusted account scope, 1 to 3 signing secrets, and an explicit event-type list. It accepts raw buffers up to the configured limit, verifies using the official SDK, and checks the exact pinned API version. Register snapshot events and keep server clocks synchronized. Its account binding comes from endpoint configuration; the platform account's identity is not independently discovered from the API key.

Platform events and connected-account events should use deliberately configured routes/receivers. Do not derive an authorized account from an unsigned header. This implementation rejects organization context and thin-event shapes. For a multi-account shared route, add a verified account resolver and allowlist before generalizing the receiver.

Express requires express.raw({ type: 'application/json', limit, inflate: false }) before JSON parsing. Next.js uses the Node runtime and reads bounded raw bytes. Upstream hosting platforms must enforce body-size and request-duration limits too: a buffer limit does not stop a slow sender from occupying a connection indefinitely.

Jobs and local effects

WebhookWorker.runOnce() returns idle, done, or failed. Run it from a long-lived worker or a scheduler that awaits completion; do not start unawaited work in a serverless request and expect it to survive the HTTP response.

The handler receives (event, tx). Use only tx for local writes that need to commit with job completion. effectOnce(tx, scope, key, work) must be called inside that transaction. It is not an independently atomic helper if called with a pool outside a transaction.

PostgresJobs.enqueue('outbox', ...) can use the same tx. Reusing an outbox ID with different type/payload is rejected. dispatchOutboxOnce passes a stable key to the delivery function. The remote recipient's deduplication and retention must cover the complete retry/replay horizon.

Failed jobs back off with jitter up to five minutes and reach dead state after eight attempts by default. A crash on the last claim is also eventually marked dead. replayDead is an internal privileged operation with actor/reason audit. It resets attempts but preserves the job identity and business-effect guards.

Reconciliation and projections

refreshProjection serializes a read-and-update for one resource. Supply a bounded current-state retrieval and persist a minimal non-secret projection. Its lock spans the retrieval. It provides neither global event ordering nor accounting history.

importBalanceTransactions scans a fixed creation window, iterates all SDK pages and upserts by scoped transaction ID. Repeated imports refresh availability/status. Schedule overlapping scans and refresh older pending items explicitly. It has no built-in checkpoint scheduler, period close, anomaly remediation or account-wide rate limiter.

reconcile compares IDs, currencies and bigint net amounts. It rejects duplicate IDs within an input set and reports missing, unexpected and mismatched rows. Supply one known account scope per comparison; identical transaction IDs from separate datasets must not be mixed without a scope-qualified key.

Implemented versus application-specific

Area Delivered Still required for a real product
Reliability Durable operations, inbox, leases, fences, effects and outbox Retention, restore reconciliation, production infrastructure
Tenancy Explicit scopes and authorization hook Identity provider, membership/resource tables, commercial approvals
Checkout Safe creation and sandbox one-time fulfillment example Inventory, shipping, tax, fraud and commercial policy
Billing Wrappers, current-state projections, recovery intents Complete entitlement state machine, customer messaging and quote workflow
Refunds Durable create Approval limits, Dashboard coordination, final-status tracking and journal postings
Disputes Detailed operational guide Evidence storage, submission workflow, deadlines and risk integration
Connect Request scope, Accounts v2 recipient creation, onboarding links, capability-checked transfers and reversals Merchant/customer configurations, thin-event handling, allocations, payouts, reserves and liability policy
Finance Balance import and exact comparisons Double-entry accounting, bank matching, FX, revenue recognition
Security Narrow inputs, signatures, no raw errors, bounded bodies Deployment hardening, secret vault, rate limit, CSRF, audits and access review

No measured production throughput, formal verification, independent penetration test, PCI certification, or universal security guarantee is claimed. The source and tests are provided so these boundaries can be reviewed rather than hidden.

Package exports

Import Contents
safestripe Payment facade, stores, workers, helpers, and public types
safestripe/express expressWebhook
safestripe/next nextWebhook and boundedBody
safestripe/migrations migrate and MigrationOptions

The safestripe command exposes migrate and --help. It reads DATABASE_URL from the environment. It does not load .env automatically or run during package installation.

Configuration defaults

Component Option Default Accepted range or contract
PostgresOperations leaseSeconds 120 30 to 3,600
PostgresOperations retryWindowSeconds 82,800 1 to 82,800; unresolved operations then need review
PostgresJobs leaseSeconds 120 1 to 3,600
PostgresJobs maxAttempts 8 1 to 100
ConcurrencyGate concurrency 8 1 to 1,000
ConcurrencyGate maxQueue 32 0 to 10,000
ConcurrencyGate maxWaitMs 5,000 1 to 60,000
WebhookReceiver maxBytes 1,048,576 1,024 to 10,485,760
WebhookReceiver toleranceSeconds 300 1 to 300
WebhookReceiver signingSecrets Required One to three endpoint secrets
WebhookReceiver eventTypes Required Explicit, nonempty event allowlist
runWorkerLoop concurrency 1 1 to 64
runWorkerLoop pollIntervalMs 500 10 to 60,000, with jitter
runWorkerLoop errorIntervalMs 1,000 10 to 60,000, with jitter
migrate lockTimeoutMs 10,000 1 to 300,000
migrate statementTimeoutMs 60,000 1 to 3,600,000

ConcurrencyGate.status returns current active and waiting counts. SafeStripeOptions.gate accepts any ExecutionGate implementing run<T>(task: () => Promise<T>): Promise<T>. A replacement must hold capacity until the returned promise settles, release it on both success and failure, and bound its queue and waiting time.

runWorkerLoop requires an AbortSignal. It stops starting calls after abort and waits for calls already in progress. It does not forcibly interrupt a Stripe request or database transaction. The host process must enforce a shutdown deadline and arrange recovery if it is killed.

Diagnostic events

Set observer on SafeStripeOptions, the fourth WebhookWorker argument, the fourth dispatchOutboxOnce argument, or WorkerLoopOptions. Events are immutable and have category, action, outcome, and durationMs. Job events include attempt. Failure events may include a stable code, a recognized Stripe error type, and a validated Stripe request ID.

Observers can return a promise, but the library does not await delivery. Rejected observer promises are contained. Use this for operational telemetry, not a mandatory audit write or another business effect. Wrapped durable mutations emit operation events; previews, portal sessions, webhook admission, raw SDK calls, and reconciliation do not currently emit those events.

Migration behavior

migrate(db, options?) returns the filenames applied during the call. It holds a transaction-scoped advisory lock, verifies recorded checksums, applies pending SQL, and commits its history atomically. An unknown applied migration also blocks an older package from silently migrating a newer schema. The default limits bound lock waiting and each statement. Schema files resolve relative to the installed module, so migration works outside the source checkout.

Billing model methods (0.3.0)

See Billing models for inputs and runnable patterns, Account services for product boundaries and Revenue metrics for reporting definitions.

New scenario methods pass their validated camelCase input object as parameters to the authorizer. This differs from some original methods' normalized Stripe parameters. Reject unknown actions and kinds; explicitly add only the operations your product supports.

Method Authorization action Resource kinds
createMultiItemSubscription subscription.create_multi customer, price, optional promotion_code
createSetupCheckout checkout.setup customer
createSetupIntent setup_intent.create customer
createPaymentLink payment_link.create price
setSubscriptionCollection subscription.collection subscription
restoreSubscription subscription.restore subscription
resumePausedSubscription subscription.resume subscription
createTieredPrice price.create_tiered product
createSchedule schedule.create customer, price
createQuote quote.create customer, price
finalizeQuote, acceptQuote quote.finalize, quote.accept quote
createCreditNote credit_note.create invoice
adjustCustomerBalance customer.balance_adjust customer
createMeter meter.create none; require administrative permission
recordUsage usage.record customer, meter
createTestClock test_clock.create none; sandbox-only
advanceTestClock test_clock.advance test_clock
createClockCustomer customer.create_clock test_clock
createMarketplaceAccount account.create_recipient none; require platform permission
createOnboardingLink account.onboard account
createTransfer transfer.create account, charge
reverseTransfer transfer.reverse transfer
createIdentitySession identity.create identity_reference
inspectTaxSetup tax.inspect none; read-only

The original createCheckout also accepts optional trialDays, allowPromotionCodes and automaticTax. Subscription-mode items can omit quantity for metered prices. No trial is permitted in payment mode. The default behavior of existing calls is unchanged.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Reference

Installation and integration

The SQL implementation details on this page describe the original PostgreSQL API. For the portable SQLite, PostgreSQL, MongoDB and Firestore setup, start with database adapters and framework integration. The current local sample defaults to SQLite; legacy SQL example commands use the :legacy suffix.

Add SafeStripe to a server application that already has users and orders. This guide uses Node.js 22.19 or later, PostgreSQL, and a Stripe sandbox. Keep the server entry point and secret keys out of browser components. The separate React payment component is available from safestripe/react.

Install

Install SafeStripe and the PostgreSQL driver in your application:

sh
npm install safestripe pg

TypeScript applications that import pg should also install its declarations:

sh
npm install --save-dev @types/pg

The package uses ES modules. For a plain JavaScript app, use .mjs files or set "type": "module" in your package.json. A CommonJS app can load it with await import('safestripe') inside an async function. Next.js handles the imports in server modules.

Configure the database

Set DATABASE_URL in the environment. For local development, a .env file may contain:

dotenv
DATABASE_URL=postgresql://safestripe:safestripe@localhost:5432/safestripe
STRIPE_SECRET_KEY=
STRIPE_ACCOUNT_ID=
STRIPE_WEBHOOK_SECRET=

Fill the Stripe values from your sandbox. Keep the file out of Git. In deployment, use the platform's secret store and a database connection configured for verified TLS.

Load your local environment file and run the installed migration command:

sh
node --env-file=.env node_modules/safestripe/dist/cli.js migrate

When your environment is already loaded, the package also exposes safestripe migrate through npm scripts or npx --no-install safestripe migrate. Use a database role allowed to create tables. Application processes should use a separate role with only the permissions they need.

A successful first run prints Applied: 001_initial.sql. Repeating it prints that the schema is up to date. The migration runner serializes competing runs and rejects changed or unknown migration files.

You can also run migrations from a deployment script:

js
import { Pool } from 'pg';
import { migrate } from 'safestripe/migrations';

const db = new Pool({ connectionString: process.env.DATABASE_URL, max: 1 });
try {
  console.log(await migrate(db));
} finally {
  await db.end();
}

Run this as a deployment step before starting workers. Do not run migrations on each HTTP request.

First library call: create a sandbox customer

Save this as customer.mjs in your application. It is a local script with a fixed identity and one allowed action. It refuses live mode and is not an HTTP authentication example.

js
import { Pool } from 'pg';
import { SafeStripe, PostgresOperations, createStripeClient } from 'safestripe';

const db = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 2,
  connectionTimeoutMillis: 5000,
  statement_timeout: 15000,
});
const stripe = createStripeClient(process.env.STRIPE_SECRET_KEY ?? '', false);
const safe = new SafeStripe({
  stripe,
  scope: {
    platformAccountId: process.env.STRIPE_ACCOUNT_ID ?? '',
    livemode: false,
  },
  operations: new PostgresOperations(db),
  appOrigin: 'http://localhost:3000',
  allowLocalhost: true,
  authorize: async ({ actor, action }) =>
    actor.tenantId === 'learning' &&
    actor.actorId === 'local-operator' &&
    action === 'customer.create',
});

try {
  const customer = await safe.createCustomer(
    {
      tenantId: 'learning',
      actorId: 'local-operator',
      operationId: 'customer:reader-001',
    },
    {
      email: 'reader@example.invalid',
      name: 'Learning customer',
    },
  );
  console.log('Customer ID:', customer.id);
} catch (error) {
  console.error('Customer creation failed:', error.code ?? 'UNEXPECTED');
  process.exitCode = 1;
} finally {
  await db.end();
}

Run it:

sh
node --env-file=.env customer.mjs

A successful call prints a cus_... ID. Run the same script again: it retrieves the same customer. If you change the email while keeping the operation ID, SafeStripe returns PAYLOAD_CONFLICT. To create a genuinely different customer, use a different operation ID.

This demonstrates the command contract. A failed network request should be retried with its original operation ID and original inputs. Do not generate a new ID just because the first response was lost.

Connect your authorization policy

An Actor describes who is acting and which operation they intend to perform:

ts
const actor = {
  tenantId: session.organizationId,
  actorId: session.userId,
  operationId: `checkout:${order.id}`,
};

Here, session and order are records your application has already authenticated and loaded. They are not values to copy from an untrusted request body.

The required authorize callback receives the actor, account scope, action, resource IDs, and normalized parameters. It must check membership, resource ownership, and the business terms. For Checkout, that includes the customer mapping, allowed price, quantity, order reference, and mode. Reject unknown actions by default.

This integration sketch shows the boundary:

ts
const safe = new SafeStripe({
  stripe,
  scope,
  operations: new PostgresOperations(db),
  appOrigin: 'https://your-app.example',
  authorize: billingPolicy.authorize,
});

const checkout = await safe.createCheckout(actor, {
  customerId: order.stripeCustomerId,
  mode: 'payment',
  items: [{ priceId: order.stripePriceId, quantity: order.quantity }],
  reference: order.id,
});

billingPolicy, session, and order are application-specific services and records. SafeStripe intentionally does not invent a login system or assume all customers in a Stripe account belong to the same tenant. See the runnable sandbox example for a complete composition with a fixed test identity.

Persist the Checkout Session ID against the order before presenting its URL. If a webhook races ahead of that write, the handler must retry until it finds the mapping. If the returned session is expired or complete, use your order state to decide what the customer sees. A replay returns current Stripe state; it does not reopen an old session.

Receive webhooks

Create one receiver for one trusted scope. Its signing secret belongs to that endpoint or local CLI listener:

ts
import { PostgresJobs, WebhookReceiver } from 'safestripe';

const jobs = new PostgresJobs(db);
const receiver = new WebhookReceiver({
  stripe,
  jobs,
  scope,
  signingSecrets: [process.env.STRIPE_WEBHOOK_SECRET!],
  eventTypes: [
    'checkout.session.completed',
    'checkout.session.async_payment_succeeded',
    'checkout.session.async_payment_failed',
  ],
});

Register these snapshot events at API version 2026-08-26.dahlia. The receiver requires an exact version match. Each accepted event is stored before the endpoint returns a successful response. It does not fulfill an order inside the request.

Express 5

Install Express in your application. TypeScript applications should install its declarations too:

sh
npm install express
npm install --save-dev @types/express

Mount the raw-body route before JSON parsing:

ts
import express from 'express';
import { expressWebhook } from 'safestripe/express';

const app = express();
app.post(
  '/api/webhooks/stripe',
  express.raw({
    type: 'application/json',
    limit: receiver.maxBytes,
    inflate: false,
  }),
  expressWebhook(receiver),
);
app.use(express.json({ limit: '16kb' }));

A webhook signature covers the original bytes. Parsing JSON and recreating it before verification changes those bytes. Leave this route outside user-session authentication and CSRF middleware; its authentication is Stripe's signature plus the receiver's scope checks. Your ordinary payment routes still require your application authentication, authorization, and appropriate CSRF protection.

Next.js App Router

Create app/api/webhooks/stripe/route.ts:

ts
import { nextWebhook } from 'safestripe/next';
import { getBillingRuntime } from '@/lib/billing';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  const { receiver } = getBillingRuntime();
  return nextWebhook(receiver)(request);
}

getBillingRuntime is your server-only module that creates or reuses the pool, SDK, and receiver configured above. Initialize it lazily so a build does not require payment credentials. Mark the module with import 'server-only' in a Next.js application. Never call request.json() before passing the request to the adapter.

The library uses Node and PostgreSQL APIs, so this route cannot run on the Edge runtime. Use a supported PostgreSQL pooler and size connection limits for your serverless deployment. Keep the worker in a process or job that the platform awaits through completion.

Process stored events

A worker takes a handler map. Every local write made through the supplied tx commits with the job's completion marker or rolls back with it.

ts
import { WebhookWorker, runWorkerLoop, effectOnce } from 'safestripe';

const worker = new WebhookWorker(jobs, safe.scopeId, {
  'checkout.session.completed': handleCheckout,
  'checkout.session.async_payment_succeeded': handleCheckout,
  'checkout.session.async_payment_failed': handleFailure,
});
const stop = new AbortController();
process.once('SIGTERM', () => stop.abort());
process.once('SIGINT', () => stop.abort());

try {
  await runWorkerLoop(() => worker.runOnce(), {
    signal: stop.signal,
    concurrency: 4,
  });
} finally {
  await db.end();
}

handleCheckout and handleFailure are your application's handlers. A fulfillment handler must look up the order, retrieve current payment state, check the customer, price, quantity, mode, and reference, then record the business effect. Use a key such as tenant:order:fulfill with effectOnce. Checking only the event type is insufficient.

The complete example in examples/shared/handlers.ts implements those checks for the sandbox order. It also shows how to enqueue a receipt intent inside the transaction. External email, shipping, and entitlement services need their own idempotent delivery protocol.

Observe and shut down

Pass an observer when constructing SafeStripe or WebhookWorker, and to runWorkerLoop for poll failures:

ts
import type { Observer } from 'safestripe';

const observer: Observer = (event) => {
  metrics.record(event.category, event.action, event.outcome, event.durationMs);
};

metrics represents your telemetry client. Events contain stable operation names, durations, outcomes, and selected failure metadata. They exclude request bodies and raw error messages. Keep the callback fast and use a bounded exporter. Observer failures never change the payment result.

When the stop signal is aborted, the worker loop stops starting new work and waits for current handlers. Give the process enough shutdown time for bounded Stripe reads and database transactions to finish. A handler that never resolves also prevents graceful shutdown; enforce database and network deadlines.

Next steps

Use the library reference for every method and option. Before deployment, complete the deployment guide and review the security model.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia

Evaluation preview. SafeStripe 0.3.0 is for sandbox evaluation. Read the release readiness guide before planning a production integration.

Reference

Sources and compatibility

Research baseline

Reviewed on 24 September 2026. This release pins stripe@22.6.2 and API 2026-08-26.dahlia. Review SDK types, endpoint versions, and handler assumptions together when upgrading. Stripe Dashboard navigation and product availability can vary by account and region.

Topic Primary reference
Official SDK and request configuration stripe-node
Idempotency semantics Idempotent requests
Ambiguous errors and retries Advanced error handling
Webhook delivery, signatures and testing Webhooks
Checkout fulfillment Fulfill orders
Payment state Verify payment status
Subscription lifecycle How subscriptions work
Billing events Subscription webhooks
Current preview API Create an invoice preview
Proration behavior Prorations
Invoice operation Dashboard invoicing
Invoice status transitions Invoice workflow transitions
Cancellation Cancel subscriptions
Refund lifecycle Refunds
Dispute review and evidence Respond to disputes
Currency semantics Supported currencies
Balance movement Balance report
Payout matching Payout reconciliation
API capacity Rate limits
Key management Secret key best practices
Client integration security Integration security guide
Isolated testing Sandboxes
Payment scenarios Testing
Recurring-time simulation Test clocks and simulations
Connect SaaS setup SaaS account creation
Connect marketplace setup Marketplace account creation
Transfer architecture Separate charges and transfers
Tax prerequisites Stripe Tax setup
Tax validation Testing Stripe Tax
Current usage-billing product Usage-based billing
Next.js bundling customization Next.js webpack configuration

Some Stripe pages route to variants based on integration type. Select the hosted Checkout or relevant Connect variant before applying a code example. The repository's compiled SDK types provide an additional check of the exact parameters used here.

Common integration mistakes

Assumption Integration rule
Event-ID uniqueness prevents double fulfillment It prevents duplicate delivery of one event. Different events and repair jobs can still request the same business effect; protect the effect too.
Only a single queue worker may mutate the ledger A single mutation policy is useful; one global worker is unnecessary. Concurrent workers can safely operate with transactions, scope partitioning and business uniqueness.
Webhooks guarantee eventual delivery Delivery can duplicate/reorder and retries are finite. Reconciliation is necessary for durable correctness.
An old update just needs a missing-record upsert Upsert solves absence, not stale overwrite. Serialize current-state refresh or use a justified resource-version protocol.
Use invoices.retrieveUpcoming() This implementation uses the current invoices.createPreview() API with an explicit shared proration timestamp.
The preview is the final invoice amount It is a quote under inputs at a time. Concurrent edits and other billing factors can change the final bill.
Hash user/cart/total to generate the idempotency key Bind a stable unique business operation ID to a separate immutable payload fingerprint. Identical carts can be separate valid purchases.
A retry after any amount of time remains safe Stripe keys may be pruned after their retention window. Keep durable records and stop ambiguous automatic retries before that boundary.
On failed authentication, set subscription to past due/unpaid Stripe controls its lifecycle. Your application controls recovery messaging and access/grace policy.
Every negative connected balance debits the platform bank Liability and recovery depend on account responsibilities, charge model and configuration. Model the actual arrangement.
balance.available lets you impose payout holds universally It is a state signal. Payout control requires the appropriate permissions, contract and supported configuration.
An enterprise wrapper can solve all security/performance issues It can enforce specific invariants. Host authorization, financial policy, deployment and measured capacity remain essential.

Maintaining the handbook

For each release, update the SDK/API baseline, rerun all tests, build both integrations, check changed webhook schemas, and review affected Dashboard procedures. Keep a short changelog explaining what changed and why. Revalidate task rubrics when Stripe UI or product behavior changes; an outdated click sequence should not make a competent operator fail an outcome-based assessment.

Record verification dates separately from publication dates. Link the exact primary page supporting a behavior, and label original design recommendations as design recommendations. Keep measured results separate from proposed capacity targets.

SafeStripe 0.3.0 · Stripe API 2026-08-26.dahlia