@fantastic.dev/better-stripe 0.50.2 → 0.50.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,230 +1,15 @@
1
1
  # better-stripe
2
2
 
3
- A reusable [Convex component](https://docs.convex.dev/components) for the Stripe V2 Accounts API — a **Stripe V2 marketplace/Connect library**, not just a webhook wrapper. Provides a complete billing + marketplace-economics backend: schema, queries, mutations, actions, webhook handling, platform fees, multi-recipient splits, rolling payouts, dispute clawback, per-store statement descriptors, React hooks, and headless UI components.
3
+ A [Convex component](https://docs.convex.dev/components) for Stripe Accounts v2,
4
+ billing, and Connect marketplaces. It provides checkout, subscriptions, webhook
5
+ syncing, marketplace fees and splits, payouts, refunds, and disputes, with React
6
+ hooks and headless UI components.
4
7
 
5
- Built for Convex + Next.js applications. Follows the conventions established by [`@convex-dev/stripe`](https://github.com/get-convex/stripe) and [`@convex-dev/better-auth`](https://github.com/get-convex/better-auth).
8
+ **Version**: `0.50.3` <!-- x-release-please-version --> (pre-1.0). API may change between minor versions until 1.0.
6
9
 
7
- For the component extraction upgrade, see the [migration and release handoff](docs/release-handoff.md), including nested runtime wiring, held operations and rollback boundaries.
8
-
9
- ## Accounts v2 customer preview
10
-
11
- Choose the setup that matches your Stripe account:
12
-
13
- | Integration | Enable “Reusable payment methods for Global Payouts” for Accounts v2 access? | BetterStripe API version |
14
- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------ |
15
- | Connect platform, including ordinary connected-account payouts and marketplace splits | No. Accounts v2 is GA for Connect. | Omit `stripeApiVersion` to keep the GA default. |
16
- | Non-Connect merchant using customer-only Accounts v2 for checkout and billing | Yes, in each intended sandbox/account. | Set `stripeApiVersion: STRIPE_CUSTOMER_PREVIEW_API_VERSION`. |
17
-
18
- For the non-Connect setup, the account owner enables that exact toggle under
19
- [Account previews and features](https://dashboard.stripe.com/settings/previews)
20
- → **Product previews**. If it is missing or disabled, check with the account
21
- owner and request access through [Stripe's customer-account guide](https://docs.stripe.com/accounts-v2/use-accounts-as-customers).
22
- The Dashboard does not always explain why a toggle is disabled. Do not enable
23
- Connect just to bypass the customer-preview requirement.
24
-
25
- The exported preview constant currently selects `2026-09-30.preview`, which
26
- passed our live non-Connect checkout and billing tests. A newer version selected
27
- in Stripe's API documentation does not enable account features or change this
28
- package's supported-version list. Both account enablement and a supported
29
- preview request version are necessary. Use `stripe.registerRoutes` to inherit
30
- the client's version for webhook processing, and pin snapshot destinations to
31
- the same version.
32
-
33
- The table covers **Accounts v2 access**. Actually reusing saved payment methods
34
- for **Global Payouts** is a separate preview feature with its own eligibility,
35
- even for Connect users. See [Stripe's credential-reuse guide](https://docs.stripe.com/global-payouts/credential-reuse).
36
- Enabling this toggle also synchronizes existing Customers into customer-configured
37
- Accounts and changes customer creation in Stripe-hosted integrations. Review
38
- those migration effects before enabling it on an existing account.
39
- See the [customer preview setup and webhook migration guide](docs/accounts-v2-preview.md).
40
-
41
- Recipient-held custom payout policies now have versioned preparation, verified
42
- manual schedule changes, live drift checks, opt-out restoration, and a bounded
43
- deadline-expiry API. See [policy setup and limits](docs/settlement.md#recipient-held-payout-policy-controls).
44
- A [recipient funding reader](docs/settlement.md#verified-recipient-funding-receipts)
45
- verifies original and reversal receipts, maturity, and exact settlement amounts;
46
- received credit is kept distinct from still-unpaid entitlement.
47
- A [payout receipt and reconciliation API](docs/settlement.md#verified-payout-receipts-and-reconciliation)
48
- verifies actual bank-payout debits and returns, adopts an attempted claim's
49
- provider outcome, and books its net payout fees once.
50
- The [combined release API](docs/settlement.md#combined-recipient-release) verifies
51
- complete source and payout history, reserves mature unpaid funds, and creates an
52
- idempotent bank payout. Install a host job to invoke it and expire due policies.
53
- The [automatic worker](docs/settlement.md#automatic-recipient-worker) provides
54
- durable attempt IDs, retry leases, recovery discovery and the next attempt time.
55
- The example installs its five-minute cron in `example/convex/crons.ts`.
56
- A [payout eligibility preview](docs/settlement.md#payout-eligibility-preview)
57
- uses the release qualification checks to report combined mature funds, pending
58
- credits, shared deductions and source categories without creating a bank payout.
59
- The unstyled React [`PayoutProgress`](docs/react-workflows.md#combined-automatic-payout-progress)
60
- displays that assessment with one combined minimum and supports custom cards
61
- and translated copy through render props.
62
- [`PayoutSettings`](docs/react-workflows.md#payout-settings)
63
- adds consent, exact minimum entry, pending-state recovery and account-wide opt-out
64
- through authorized host callbacks. Seller and affiliate payout pages use both.
65
- [Historical imports and explicit funded activation](docs/settlement.md#historical-import-and-funded-activation)
66
- verify old payouts, source ownership and holding age before enabling a custom
67
- schedule. Larger histories and unallocated money still require reconciliation;
68
- schedule controls alone do not enforce a minimum.
69
- [Resumable local collections and reset safeguards](docs/settlement.md#resumable-local-collections)
70
- provide bounded ledger inspection while provider-history continuation and scalable
71
- claim execution are completed.
72
-
73
- ## Status
74
-
75
- **Version**: `0.50.2` <!-- x-release-please-version --> (pre-1.0). API may change between minor versions until 1.0.
76
-
77
- Used in production by its authors. Webhook pipeline is covered by unit tests and a live E2E harness (`npm run e2e:webhooks`) that fires real Stripe-signed events and asserts the ledger.
78
-
79
- ### Releasing
80
-
81
- Releases are automated with [Release Please](https://github.com/googleapis/release-please-action) and published to npmjs.com as `@fantastic.dev/better-stripe`. **Don't bump the version or edit `CHANGELOG.md` by hand.**
82
-
83
- 1. **Give every PR a Conventional Commit title** (it becomes the squash-merge commit):
84
- - `fix: …` makes a patch release.
85
- - `feat: …` makes a minor release.
86
- - `feat!: …` (or a `BREAKING CHANGE:` footer) makes a minor release while the package is pre-1.0.
87
- - `docs:`, `chore:`, `ci:`, `refactor:`, `test:`, `build:` and `perf:` appear in the changelog too. On their own they still open a patch release PR, which auto-merges once its required checks pass.
88
-
89
- Write the title for consumers of the package: it becomes the changelog entry. A title that isn't a Conventional Commit is left out.
90
-
91
- 2. **On merge to `main`**, the `Release` workflow opens or updates a release PR that bumps `package.json`, `CHANGELOG.md`, the version line above and `.release-please-manifest.json`. It formats the generated changelog with the repository's pinned Prettier and commits any formatting changes through the release GitHub App, so CI validates the formatted branch. An already formatted changelog creates no extra commit. After formatting, the workflow enables squash auto-merge for the generated release PR using the release GitHub App.
92
- 3. **Auto-merge waits for green checks**. The active `main` ruleset requires `ci`, `Shadscan UI quality gate (100)` and `codegen`, with no bypass actors. Failed or pending required checks prevent merging. Once GitHub merges the generated release PR, the resulting `Release` workflow run tags the version, creates the GitHub release and publishes to npm through [trusted publishing](https://docs.npmjs.com/trusted-publishers) with provenance. There's no npm token.
93
-
94
- Release policy lives in `release-please-config.json`. Keep the workflow file named `release.yml`, because the trusted publisher on npmjs.com is bound to that filename. A manually pushed `vX.Y.Z` tag also publishes, but only if it matches `package.json` and `CHANGELOG.md` has a section for it (`scripts/release-notes.mjs`). If publishing fails after the GitHub release is created, use **Re-run failed jobs** on that run. Check npm first if the outcome is uncertain: a published version can't be overwritten.
95
-
96
- The private `example` workspace isn't published.
97
-
98
- ### Development toolchain
99
-
100
- Install with `pnpm install` from the repository root, then run `pnpm build`
101
- and `pnpm dev` to start the example at http://localhost:5173. The example needs
102
- Node.js 22.12+ and a configured Convex development deployment; see
103
- [the example setup guide](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md).
104
-
105
- The BetterStripe example separates visitor, customer, affiliate, seller, and
106
- platform-admin workflows. Fresh fictional Maya and Sasha stores explicitly
107
- configure 20% Forever referral commissions to fund the affiliate payout example;
108
- ordinary stores still default to zero, and seed reruns preserve later edits.
109
- Its resumable Stripe sandbox fixtures populate sales,
110
- referrals, refunds, disputes, subscriptions, and payouts. Seller plans include
111
- monthly billing, actual Stripe fee reconciliation, and refund/dispute cost
112
- recovery. The example also demonstrates optional balance-funded subscriptions
113
- using Stripe's Accounts v2 preview. See the setup guide for consent requirements,
114
- renewal tests, and payment-recovery limitations.
115
-
116
- The example compares via API views, BetterStripe React components, Stripe Connect
117
- embeds, and hosted billing where supported. Its checkout chooser demonstrates
118
- Hosted Checkout, Embedded Checkout, custom Checkout Sessions with Payment Element,
119
- Payment Intents with Payment Element, and the preview Embedded Checkout Form,
120
- with pros and cons for each. `createCheckoutSession` accepts `uiMode` values
121
- `"redirect"`, `"embedded"`, `"custom"`, and `"form"`; the latter two map to Stripe's
122
- `elements` and preview `form` modes. See [the integration examples](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md#compare-integration-styles).
123
-
124
- Admins can configure store-plan monthly prices and sale fees. Monthly price changes
125
- create new Stripe Prices; existing store subscriptions keep their current price.
126
- Affiliate payouts accept percentages or fixed amounts in the sale currency, with
127
- optional price, product, store, plan, and platform defaults. Unconfigured payouts
128
- are zero. Subscription commission terms are **Forever** or **One-time**, with
129
- Forever as the default. The example saves the selected term in Stripe subscription
130
- metadata and its Convex ledger, then applies it when paid invoices settle.
131
- See [affiliate configuration and testing](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md#seller-product-and-subscription-affiliate-payouts).
132
-
133
- The public React exports include `AffiliatePayoutEditor`, `PlanPricingEditor`,
134
- `Pagination`, and `useCursorPagination`. The example supplies styling through
135
- render props; its backend owns authorization, rule inheritance, and transfers.
136
- See [the workflow reference](docs/react-workflows.md#percentage-or-fixed-affiliate-payouts)
137
- and [the UI reuse audit](docs/react-workflows-audit.md).
138
-
139
- Run `pnpm run check:all` before submitting changes. It runs the build, lint,
140
- formatting, typechecks, codegen drift check, tests, and repository quality gates
141
- used by CI. Policy lives in `repo-gates.config.json`; measured baselines live in
142
- `gates/`. Fix failures without weakening the gates or raising existing budgets.
143
-
144
- Successful full coverage checks automatically raise the floors in
145
- `gates/coverage-budgets.json`. Run `pnpm run check:coverage` or
146
- `pnpm run check:all`, then commit any budget changes. Each metric retains the
147
- existing 0.5 percentage point margin below its measured baseline, and floors
148
- never decrease. Failed checks leave the budgets untouched. CI checks the same
149
- ratchet and fails if an improvement has not been committed. `pnpm test:coverage`
150
- only generates the report; filtered or skipped runs cannot update floors through
151
- the automatic ratchet.
152
-
153
- Builds and typechecks use TypeScript 7 (`@typescript/native` aliases
154
- `typescript`). ESLint and Convex code generation still need the TypeScript 6
155
- API, so `typescript` aliases Microsoft's `@typescript/typescript6` compatibility
156
- package. Keep both aliases when updating dependencies, as described in
157
- [Microsoft's migration guide](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0).
158
-
159
- Stripe 23 targets API version `2026-09-30.endive`. Account links now collect
160
- requirements without a `configurations` parameter; callers can still pass the
161
- legacy option, but it is not sent to Stripe. See the
162
- [Stripe API changelog](https://docs.stripe.com/changelog) before upgrading an
163
- existing integration to this API version.
164
-
165
- ### Regenerating codegen
166
-
167
- The component ships committed Convex codegen output at `src/component/_generated/{api,component,dataModel,server}.ts` — consumers reach the bindings via the `./_generated/component` subpath export. The example app also commits its own codegen at `example/convex/_generated/`. Running `pnpm dev` (which wraps `convex dev`) regenerates these automatically when the schema or function definitions change, but only against the live dev deployment and only while the dev server is watching.
168
-
169
- The example resolves the workspace package through `dist/`. After changing
170
- component source, regenerate library bindings with `pnpm codegen:lib`, run
171
- `pnpm build`, then deploy the rebuilt component from the example directory with
172
- `pnpm exec convex dev --once`. Run `pnpm codegen:example` afterward. Code generation
173
- alone does not prove that a newly added function is mounted; invoke a representative
174
- query or action against the development deployment before running financial tests.
175
-
176
- If you add, remove, or rename a query/mutation/action on a branch without the dev server watching — or after a rebase — regenerate explicitly before committing:
177
-
178
- ```bash
179
- pnpm codegen # regen the library component + example app
180
- pnpm codegen:lib # regen src/component/_generated only
181
- pnpm codegen:example # regen example/convex/_generated only
182
- ```
183
-
184
- All three require a configured dev deployment (`CONVEX_DEPLOYMENT` env var, normally set by a prior `npx convex dev`). They write only the local `_generated/` files — they don't push code or data to the deployment.
185
-
186
- **CI gate.** Two layers verify the committed files are not stale:
187
-
188
- 1. **Structural drift check** (`pnpm codegen:check`, always runs in CI): two independent scans, each checking both directions (every source export appears in the generated file, and every generated entry still has a matching source), neither needing a deployment:
189
- - Library component — scans `src/component/**/*.{queries,mutations,actions}.ts` and verifies every exported function appears in `src/component/_generated/component.ts`. The reverse direction also flags a stale entry left behind by a _deleted_ query/mutation/action. The export-detection regex intentionally matches only direct `query(...)`/`mutation(...)`/`action(...)` exports — not wrapper or re-export forms like `customQuery(...)` (convex-helpers) or `export { fn as name }`, which this component has none of today; widen the regex (and the reverse scan) rather than assuming that stays true.
190
- - Example app — scans `example/convex/**/*.ts` and verifies every source module is imported and registered in `example/convex/_generated/api.ts`. Catches the common case of adding a new `example/convex/<module>.ts` (or nested file like `example/convex/lib/<module>.ts`) without regenerating. The reverse direction likewise flags a stale import left behind by a _deleted_ module.
191
- 2. **Authoritative regen-and-diff** (runs in CI when `CONVEX_DEPLOYMENT` is configured): runs `pnpm codegen` against the configured dev deployment and fails if `git diff` shows changes. Catches every drift case, including validator-shape changes the structural check can't see. To enable on a fork, set the `CONVEX_DEPLOYMENT` repo secret to a dev deployment name and authorize the CI runner — see Convex's [GitHub Actions guide](https://docs.convex.dev/production/integration/deployments#github-actions).
192
-
193
- ### Relation to `@convex-dev/stripe`
194
-
195
- This component targets the Stripe **V2 Accounts API** (Connect/marketplace-first) with a transactional trigger system. [`@convex-dev/stripe`](https://github.com/get-convex/stripe) targets the classic Customers/V1 API. They are different data models — there is no automated migration. Choose by which Stripe API generation your app uses.
196
-
197
- ## Features
198
-
199
- - **V2 Accounts API** -- Account creation, onboarding, Connect/marketplace, merchant and recipient configurations
200
- - **Products and Prices** -- Full CRUD with trial day management as a first-class feature
201
- - **Checkout** -- Both embedded (custom UI mode) and redirect checkout session creation
202
- - **Subscriptions** -- Lifecycle management including cancel, reactivate, quantity updates, and trial tracking
203
- - **Marketplace fees** -- Platform fee config (percent, fixed, tiered), resolved per-call or as a global default, applied via `application_fee_percent`/`application_fee_amount` or computed per invoice/charge
204
- - **Split engine** -- Single-recipient destination charges or multi-recipient separate-charges-and-transfers (store + affiliate(s)), computed and executed by the webhook engine
205
- - **Invoices** -- Invoice syncing and querying with metadata propagation from subscriptions
206
- - **Payments** -- Payment intent tracking and status management
207
- - **Payouts** -- Automatic rolling payouts for Connect/marketplace flows, with a recipient balance + cadence React surface
208
- - **Refunds** -- Refund tracking with refunded-amount/status denormalized onto the linked payment, plus proportional platform-fee return and transfer reversal (destination charges via Stripe flags, split sales via webhook-driven ledger math)
209
- - **Disputes** -- Chargeback/dispute tracking with evidence submission and close helpers, plus automatic transfer clawback on open, reinstatement on a won dispute, and auto-cancel of the disputed subscription
210
- - **Per-store statement descriptors** -- Buyer-recognizable charge descriptors resolved per seller with a configurable platform fallback
211
- - **Webhook handling** -- Single-endpoint processing with ledger-based deduplication and replay protection
212
- - **Trigger system** -- BetterAuth-style sync triggers (same transaction) and async hooks (scheduled action) for app-layer extensibility
213
- - **React hooks** -- Read hooks and flow hooks for all billing and marketplace-economics domains (fees, splits, earnings, payouts, disputes)
214
- - **Headless UI components** -- Checkout, subscription, payment method, Connect, payout, split, and dispute components with render-prop customization
215
- - **Test utilities** -- Typed fixture factories, mock webhook events, and `assertTestEnvironment` guard
216
-
217
- See [Roadmap / Known Gaps](#roadmap--known-gaps) for what's still in flight.
218
-
219
- ## Roadmap / Known Gaps
220
-
221
- The marketplace economics layer includes platform fees, split transfers, rolling payouts, dispute recovery, refund reversals, and per-store statement descriptors. The former roadmap gaps are covered as follows:
222
-
223
- - **First subscription charge descriptor** — `createProduct` and `updateProduct` stamp the store's descriptor (or platform fallback) onto store-owned Stripe products. The product descriptor covers the first invoice for direct subscriptions and Checkout subscription mode; the invoice-time descriptor still takes precedence on later invoices. Existing products need `updateProduct` to receive the descriptor, and a later store descriptor change requires refreshing its products. Shared products have one descriptor and should not be reused across stores that need different descriptors.
224
- - **First-invoice fees** — finalized first invoices bypass the draft update window. At `invoice.paid`, the processor collects the fixed/tiered fee through a partial reversal of the destination transfer. Invoice markers and invoice-tagged reversals prevent duplicate collection, including recovery after a failed marker write. Renewals whose fees were set on the draft invoice are skipped.
225
- - **Dispute reversal retries** — reversal slices are claimed atomically before any Stripe call. Partial-success retries reuse the recorded amounts and idempotency keys, skip confirmed legs, and reconcile money already moved before a ledger-write failure.
226
- - **Affiliate commission recovery** — original commission snapshots, shared refund/dispute exposure, reversal receipts, and a resumable backfill are available. Currency-scoped future-commission offsets, receipt-backed dispute restoration, payout reservations, and reusable recovery views are included. See [affiliate commission clawbacks](docs/affiliate-clawbacks.md).
227
- - **Earnings and split totals** — `useEarnings` reads exact server-side aggregates with bounded drill-down previews. `listTransfersByAccount` remains a preview API; do not sum it for financial totals. `listTransfersByCharge` now returns every original split leg by default, and reversal claims cover up to 1,000 charge-linked transfer rows, failing explicitly above that bound. An explicit list limit requests a preview. Convex read/write/response limits fail loudly rather than silently truncate financial data.
10
+ Connect platforms use the default GA API version. Non-Connect merchants using
11
+ customer-only Accounts v2 need preview access and an explicit preview version.
12
+ Read the [Accounts v2 setup guide](docs/accounts-v2-preview.md) before integrating.
228
13
 
229
14
  ## Installation
230
15
 
@@ -232,13 +17,14 @@ The marketplace economics layer includes platform fees, split transfers, rolling
232
17
  npm install @fantastic.dev/better-stripe
233
18
  ```
234
19
 
235
- The package bundles `stripe`, `@stripe/stripe-js`, and `@stripe/react-stripe-js` as dependencies. You do not need to install Stripe packages separately.
236
-
237
- Peer dependencies: `convex >= 1.29.3`, `react >= 18.3.1`, `react-dom >= 18.3.1`.
20
+ Requires Node.js 20+, Convex `^1.46.0`, and React/React DOM `^18.3.1` or `^19.0.0`.
21
+ Stripe SDKs are included as dependencies.
238
22
 
239
- ## Quick Start
23
+ ## Quick start
240
24
 
241
- The consumer contract has three steps:
25
+ Set `STRIPE_SECRET_KEY` in your Convex deployment, then wire the component, client,
26
+ and webhook route as follows. See [configuration](docs/configuration.md) for all
27
+ environment variables and TypeScript setup.
242
28
 
243
29
  ### Step 1: Register the component
244
30
 
@@ -249,7 +35,7 @@ import { defineApp } from "convex/server";
249
35
  import { v } from "convex/values";
250
36
 
251
37
  // betterStripe requires STRIPE_SECRET_KEY; declare it at the app level and pass
252
- // it to the component by reference (see "Wiring component env vars" below).
38
+ // it to the component by reference.
253
39
  const app = defineApp({
254
40
  env: { STRIPE_SECRET_KEY: v.string() },
255
41
  });
@@ -260,9 +46,7 @@ app.use(betterStripe, {
260
46
  export default app;
261
47
  ```
262
48
 
263
- > **TypeScript 6+:** `compilerOptions.types` now defaults to `[]`, so installed `@types/*` packages are no longer included automatically. If Convex's typecheck reports `Cannot find name 'process'` for the `process.env` reads below, add `"types": ["node"]` to `convex/tsconfig.json` and make sure `@types/node` is a devDependency.
264
-
265
- ### Step 2: Create a BetterStripe instance with triggers
49
+ ### Step 2: Create a BetterStripe instance
266
50
 
267
51
  ```typescript
268
52
  // convex/stripe.ts
@@ -278,16 +62,6 @@ export const stripe = new BetterStripe(components.betterStripe, {
278
62
  // App-specific transactional logic (same DB transaction)
279
63
  },
280
64
  },
281
- subscription: {
282
- onUpdate: async (ctx, newSub, oldSub) => {
283
- // Update app-owned tables within the same transaction
284
- },
285
- },
286
- },
287
- hooks: {
288
- onCheckoutCompleted: async (ctx, session) => {
289
- // Async side effects: email, Slack, analytics
290
- },
291
65
  },
292
66
  });
293
67
 
@@ -319,1523 +93,36 @@ registerRoutes(http, components.betterStripe, {
319
93
  export default http;
320
94
  ```
321
95
 
322
- The `webhooks: internal.stripe` line passes the function references of the `syncWebhook`/`asyncWebhook` pair you exported in step 2 (here from `convex/stripe.ts`). Don't confuse this with the callback `triggers`/`hooks` on the `BetterStripe` constructor in step 2, which take your raw handlers. When `webhooks` is provided, webhook upserts run through `syncWebhook` so your sync triggers execute in the same transaction as the component write, and your async hooks are scheduled (via `asyncWebhook`) after commit. If omitted, the handler falls back to direct component upserts and no triggers fire.
323
-
324
- > **Why two webhook secrets?** Stripe requires separate event destinations for V1 snapshot events (payments, subscriptions) and V2 thin events (Connect account lifecycle). Each destination has its own signing secret. The handler uses `webhookSecret` for V1 events and `webhookSecretV2` for V2 events. See [Webhook Setup](#webhook-setup) for details.
325
-
326
- ## Client API Reference
327
-
328
- All methods are available on the `BetterStripe` class instance. Methods that call the Stripe API are actions; methods that only read Convex data are queries.
329
-
330
- Methods named `get<Entity>` take the component document ID (exception: `getInvoice`, which takes the Stripe invoice ID); methods named `get<Entity>ByStripeId` take the Stripe ID (`acct_...`, `prod_...`, `price_...`, `cs_...`, `sub_...`).
331
-
332
- ### Account
333
-
334
- `closeAccount` and its `restartAccountOnboarding` alias retain a durable closure
335
- record before contacting Stripe. Successful closure removes the active account
336
- mapping but preserves the original user/organization ownership, close timestamp
337
- and financial rows. A pending attempt pins its owner through retry; delayed
338
- account upserts cannot revive a closed recipient. Retrying after provider success
339
- and local persistence failure retrieves provider state and completes locally
340
- without closing an already closed account again. A required provider lookup that
341
- fails now stops closure rather than submitting an empty configuration guess.
342
-
343
- `getClosedAccountByStripeId(ctx, { stripeAccountId })` retrieves closed provenance;
344
- `listClosedAccountsByUserId(ctx, { userId, paginationOpts })` discovers personal
345
- closed accounts using indexed pages of 1–100 records. Organization accounts are
346
- excluded from personal discovery. These are trusted host APIs: authenticate the
347
- actor and check both original user and organization scope before passing the
348
- historical Stripe account ID to existing payout, transfer or commission readers.
349
- A supplied userId or a replacement account never proves historical ownership.
350
- An untracked legacy closure has no invented owner and is not discoverable as a
351
- personal account. Records deleted before this contract cannot be reconstructed.
352
-
353
- Closure provenance does not evaluate outstanding funds, reservations, recovery
354
- liabilities or permission to create a replacement. Applications must enforce
355
- those policies before exposing `AccountCloseCard`; its render props provide
356
- presentation and confirmation, not financial authorization. Do not use closure
357
- as an automatic delete-and-recreate onboarding reset. Existing active-account
358
- getters keep their signatures and exclude completed closures; historical readers
359
- retain original financial references. The Vite reference's
360
- [closed-account authorization example](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md#closed-account-history)
361
- shows where the host's authenticated-actor check belongs.
362
-
363
- | Method | Description |
364
- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
365
- | `createAccount(ctx, { userId, email?, name?, country?, orgId?, metadata? })` | Create a V2 account in Stripe and the component database |
366
- | `getAccount(ctx, { accountId })` | Get account by component document ID |
367
- | `getAccountByStripeId(ctx, { stripeAccountId })` | Get account by Stripe account ID |
368
- | `getOrCreateAccount(ctx, { userId, email?, name?, country?, orgId?, metadata? })` | Get existing or create new account |
369
- | `getAccountByUserId(ctx, { userId })` | Get account by app-layer user ID |
370
- | `getAccountByOrgId(ctx, { orgId })` | Get account by organization/team ID |
371
- | `getAccountOnboardingStatus(ctx, { accountId })` | Get Connect onboarding status (by component document ID) |
372
- | `updateAccount(ctx, { stripeAccountId, email?, name?, metadata? })` | Update account fields |
373
- | `createAccountLink(ctx, { stripeAccountId, refreshUrl, returnUrl, type })` | Create Connect onboarding or update link |
374
- | `createAccountSession(ctx, { stripeAccountId, components })` | Create embedded account management session |
375
- | `createLoginLink(ctx, { stripeAccountId })` | Create Express dashboard login link |
376
- | `addRecipientConfiguration(ctx, { stripeAccountId })` | Add recipient configuration to an existing account |
377
- | `getV2Account(ctx, { stripeAccountId, include? })` | Retrieve a V2 account directly from Stripe |
378
- | `updateV2Account(ctx, { stripeAccountId, updateParams })` | Update a V2 account in Stripe |
379
- | `listStripeAccounts(ctx, { limit? })` | List V2 accounts directly from Stripe |
380
- | `closeAccount(ctx, { stripeAccountId })` | Close a V2 account; returns `{ closed: boolean }` |
381
- | `restartAccountOnboarding(ctx, { stripeAccountId })` | Close the account so onboarding can restart fresh |
382
- | `setAccountStatementDescriptor(ctx, { stripeAccountId, statementDescriptor })` | Set (or `null` to clear) the account's per-store statement-descriptor suffix |
383
- | `createDisputeSession(ctx, { stripeAccountId })` | Create an embedded Account Session scoped to the seller's disputes |
384
-
385
- ### Product and Price
386
-
387
- `ensurePrice(ctx, { stripeProductId, lookupKey, unitAmount, type, idempotencyKey, currency?, interval?, intervalCount? })` finds a price by its provider lookup key, verifies its immutable terms, and adopts the price and product into the component mirrors. If absent, it creates the price with the supplied idempotency key. A matching provider result repairs a failed mirror write on retry. Inactive prices, different products or pricing terms, and metered or transformed pricing are rejected. Choose a new versioned lookup key when changing price terms; existing subscriptions retain their current price.
388
-
389
- Scope the idempotency key to one catalog operation and reuse it only with identical creation parameters. Authorize product access in your host action. `getStripePriceByLookupKey(ctx, { lookupKey })` reads Stripe without changing mirrors. `adoptProduct(ctx, { stripeProductId, accountId? })` imports an existing provider product, preserving existing ownership and rejecting reassignment. Adoption does not update provider metadata or statement descriptors. `createPrice` also accepts `lookupKey` for callers handling adoption themselves. Tier names, lookup-key version policy, and entitlement mapping remain in the host app.
390
-
391
- | Method | Description |
392
- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
393
- | `createProduct(ctx, { name, description?, active?, accountId?, metadata? })` | Create product in Stripe and component DB |
394
- | `getProduct(ctx, { productId })` | Get product by component document ID |
395
- | `getProductByStripeId(ctx, { stripeProductId })` | Get product by Stripe product ID |
396
- | `listProducts(ctx, { accountId?, active?, limit? })` | List products with optional filters |
397
- | `updateProduct(ctx, { stripeProductId, ...updates })` | Update product fields |
398
- | `deactivateProduct(ctx, { stripeProductId })` | Deactivate product in Stripe and component DB |
399
- | `createPrice(ctx, { stripeProductId, unitAmount, type, currency?, interval?, intervalCount?, nickname?, metadata? })` | Create price in Stripe and component DB |
400
- | `getPrice(ctx, { priceId })` | Get price by component document ID |
401
- | `getPriceByStripeId(ctx, { stripePriceId })` | Get price by Stripe price ID |
402
- | `listPrices(ctx, { productId?, active?, limit? })` | List prices with optional filters |
403
- | `updatePrice(ctx, { stripePriceId, ...updates })` | Update price fields |
404
- | `deactivatePrice(ctx, { stripePriceId })` | Deactivate price in Stripe and component DB |
405
-
406
- ### Checkout and Subscription
407
-
408
- | Method | Description |
409
- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
410
- | `createCheckoutSession(ctx, { userId, stripePriceId, mode, returnUrl, uiMode?, quantity?, trialDays?, accountId?, orgId?, customerEmail?, destinationAccountId?, split?, fee?, amount?, metadata?, sessionOverrides? })` | Create checkout session (embedded or redirect); `destinationAccountId`/`split` route funds, `fee` overrides the platform's configured default |
411
- | `getCheckoutSession(ctx, { sessionId })` | Get checkout session by component document ID |
412
- | `getCheckoutSessionByStripeId(ctx, { stripeSessionId })` | Get checkout session by Stripe session ID |
413
- | `createSubscription(ctx, { userId, orgId?, customerAccount, stripePriceId, destinationAccountId?, split?, fee?, trialDays?, metadata? })` | Create a subscription directly for a V2 buyer (off the checkout flow), with the same routing/fee options as checkout |
414
- | `getSubscription(ctx, { subscriptionId })` | Get subscription by component document ID |
415
- | `getSubscriptionByStripeId(ctx, { stripeSubscriptionId })` | Get subscription by Stripe subscription ID |
416
- | `listSubscriptions(ctx, { stripeAccountId?, status?, limit? })` | List subscriptions, optionally scoped to a Connect account (use `listSubscriptionsByUser` for per-user filtering) |
417
- | `listSubscriptionsByUser(ctx, { userId, status? })` | List all subscriptions for a user |
418
- | `listSubscriptionsByOrg(ctx, { orgId, status? })` | List all subscriptions for an organization |
419
- | `getActiveSubscription(ctx, { userId, orgId? })` | Get the active subscription for a user or org |
420
- | `getTrialStatus(ctx, { subscriptionId })` | Get trial state for a subscription |
421
- | `cancelSubscription(ctx, { stripeSubscriptionId, cancelAtPeriodEnd? })` | Cancel subscription immediately or at period end |
422
- | `reactivateSubscription(ctx, { stripeSubscriptionId })` | Reactivate a canceled subscription |
423
- | `updateSubscriptionQuantity(ctx, { stripeSubscriptionId, quantity })` | Update subscription seat quantity |
424
-
425
- ### Durable recovery claims
426
-
427
- `stripe.costRecovery` is a server-only recovery client backed by the Convex
428
- component. Bookkeeping methods do not use Stripe credentials or move money.
429
- Invoice methods use the configured Stripe client and must run in an action.
430
- Your host authenticates the
431
- caller, approves which costs are owed, authorizes the account and recovery scope,
432
- and verifies provider outcomes before confirming collection. A recovery scope is
433
- an application-defined liability boundary, such as one store. Amounts are signed
434
- integer minor units and currencies never mix.
435
-
436
- ```ts
437
- const recovery = stripe.costRecovery;
438
- const scope = {
439
- accountId: sellerAccountId,
440
- scopeKey: storeId,
441
- currency: "usd",
442
- };
443
- await recovery.recordClaim(ctx, {
444
- ...scope,
445
- claimKey: `cost:${chargeId}`,
446
- sourceChargeId: chargeId,
447
- sourceGross: originalGross,
448
- sourceProcessingFee: originalProviderFee,
449
- amountDue: approvedCumulativeCost,
450
- revision: durableObservationRevision,
451
- });
452
- const result = await recovery.reserve(ctx, {
453
- ...scope,
454
- groupKey: `settlement:${fundingChargeId}`,
455
- operationKey: `settlement:${fundingChargeId}:batch:1`,
456
- sourceKind: "settlement",
457
- sourceId: fundingChargeId,
458
- sourceGross: fundingGross,
459
- sourceProcessingFee: fundingProviderFee,
460
- maxDebit: availableSellerEarnings,
461
- maxCredit: approvedCreditBudget,
462
- });
463
- ```
464
-
465
- Claims retain their original charge, account, scope, currency, gross and provider
466
- fee. Replays of the same revision must have the same amount; lower revisions are
467
- ignored. The host must assign durable, monotonically increasing observation
468
- revisions from authoritative reconciliation, not an unordered event arrival
469
- counter. Use `getClaim(ctx, { claimKey })` to capture the prior revision before
470
- reading provider state, then propose the next revision. On a conflicting revision,
471
- retry the full provider reconciliation, rather than incrementing the revision of
472
- an already-stale snapshot. Later provider observations update cumulative `amountDue`, including
473
- signed credits, without erasing collected or reserved history. Claim keys beginning
474
- with `rollback:` are reserved by the package.
475
-
476
- Reservations use maintained totals across all claims, so a credit beyond the
477
- first history page still reduces the recoverable amount. Each call allocates at
478
- most 100 claims. Repeat with distinct, durable batch operation keys in the same
479
- group until `seal(ctx, { groupKey })` succeeds. The group's debit/credit budgets
480
- apply across all batches. A group identifies exactly one external money boundary;
481
- only one group per account/scope/currency may remain pending. Retry the same batch
482
- key to recover the same allocation after a timeout or host write failure.
483
-
484
- Seal before any provider side effect. New claim observations can require another
485
- batch before sealing; observations after sealing remain owed or credited for a
486
- later group. After verifying the provider's final result, call
487
- `finish(ctx, { groupKey, outcome: "collect" | "release" })`. Completion processes
488
- at most ten reservations per call, each with at most 100 claims. Repeat while
489
- `isDone` is false using separate action/job invocations when needed to respect
490
- Convex transaction limits. Completion is idempotent; a collected group cannot be
491
- released or reused with another outcome. Do not release an unknown provider
492
- outcome just because a request timed out. An unpaid invoice must stay reserved
493
- until its verified payment or cancellation policy resolves it.
494
-
495
- For a collected settlement group whose funding sale is later returned, call
496
- `rollback(ctx, { groupKey, returnedPrincipal, revision })` with the authorized
497
- cumulative principal. This records a separate, source-linked rollback claim,
498
- preserves the original costs and collection history, and rounds positive and
499
- negative amounts symmetrically. Reinstated principal can reduce the rollback
500
- again with a newer revision. This bookkeeping operation does not refund or
501
- reverse a transfer. For invoice groups, use the verified funding adapter below;
502
- do not invent invoice payment allocations.
503
-
504
- Use `balance(ctx, scope)` for exact maintained totals and
505
- `listClaims(ctx, { ...scope, limit, cursor })` for paginated history. `getClaim`, `getGroup` and
506
- `getReservation` resume durable workflows. Integrate these server callbacks with
507
- the existing unstyled React `CostRecovery` display. These bookkeeping APIs leave
508
- consent, provider fee policy and entitlement changes in the host.
509
-
510
- The example uses these package calls for sale reservations, verified collection,
511
- monthly invoice adjustments and source observations. Its host stores source and
512
- display metadata; financial totals come from the component. `CostRecovery` accepts
513
- an optional `reservedAmount` to distinguish reservations from collected money,
514
- while preserving the legacy `invoicedAmount` input. See the example README for
515
- cutover constraints and the sandbox renewal acceptance procedure.
516
-
517
- ### Atomic recovery preparation
518
-
519
- Call `stripe.costRecovery.prepareGroup(ctx, { ...groupOptions, limit: 100 })`
520
- after authorizing the account, scope, currency, source and debit/credit policy.
521
- Each call reserves at most one batch and seals the completed target in the same
522
- component mutation. It returns `{ status: "prepared", group, isDone }`. Continue
523
- with unchanged group options while `isDone` is false; do not run provider effects
524
- until it is true. Sealed or finished replay returns the saved group without
525
- another reservation. Batch identities use a persisted sequence, independent of
526
- pending or completed reservation counts. The optional limit must be 1 through
527
- 100 and can change between bounded calls.
528
-
529
- A competing boundary returns `{ status: "conflict", reason: "scope_busy",
530
- retryable: false }`. Changed group identity or a legacy operation-key collision
531
- returns `identity_changed`; invalid scope or policy returns `rejected`. These
532
- outcomes do not reserve anything. Read current state and let host policy decide
533
- what to do; conflicts are not automatic retries. Existing `reserve`, `seal` and
534
- `finish` methods remain available. Host reporting and provider execution remain
535
- separate from preparation.
536
-
537
- ### Importing opening recovery balances
538
-
539
- When moving an existing ledger into the component, your server can call
540
- `stripe.costRecovery.importClaim(ctx, { ...observation, operationKey, collectedAmount })`.
541
- The observation includes the authorized account/scope/currency, original charge,
542
- gross and processing fee, approved cumulative amount due and a durable revision.
543
- `collectedAmount` is the signed amount already verified as collected before the
544
- cutover. The component retains that opening snapshot and computes outstanding as
545
- amount due minus the imported collection. It does not create a Stripe payment.
546
-
547
- Quiesce the old ledger's writers and verify its invoice and payout outcomes first.
548
- An unpaid invoice is a reservation, not a collection; an unknown provider outcome
549
- must stay held until reconciled. Do not import those amounts as collected or
550
- silently release them. Authorize source identity and original provider economics
551
- in the host before invoking this server-only bookkeeping operation.
552
-
553
- Use one stable import operation key per claim. A replay returns the current claim
554
- even after later observations or collections, without resetting its opening
555
- amount. Changing the opening snapshot or source binding, reusing an operation key
556
- for another claim, importing over a normal live claim, or introducing a new
557
- opening balance while the scope has a pending external recovery group is rejected.
558
- Signed credit collections and currencies stay separate. New observations continue
559
- through `recordClaim` with newer durable revisions.
560
-
561
- ### Invoice recovery adjustments
562
-
563
- After authorizing the seller, invoice and liability scope, reserve with
564
- `sourceKind: "invoice"` and `sourceId: invoiceId`. Allocate bounded batches and
565
- seal the group before calling Stripe. Then attach exactly one signed adjustment
566
- for the entire group:
567
-
568
- ```ts
569
- const receipt = await recovery.attachInvoice(ctx, { ...scope, groupKey });
570
- // Invoke from your invoice lifecycle reconciliation, and repeat bounded completion
571
- // until isDone after payment or release.
572
- const result = await recovery.reconcileInvoice(ctx, {
573
- ...scope,
574
- groupKey,
575
- releaseUncollectible: false,
576
- });
577
- ```
578
-
579
- The invoice must belong to the authorized customer account, use the same currency,
580
- and be draft before a new item is created. The package stores its stable group
581
- identity before the provider call, uses that identity as the idempotency key and
582
- item metadata, and persists the resulting item ID. Every retry scans all items
583
- on that exact invoice, recovering a successful creation even if the subsequent
584
- database write failed or the provider idempotency key expired. A bound item that
585
- has been deleted, changed or duplicated requires reconciliation; the package
586
- never silently recreates it. Negative adjustments are credits. Items are not
587
- discountable.
588
-
589
- Your host must durably serialize provider operations for each group, including
590
- attachment and any calls that finish or release it. Never release a reservation
591
- after a timeout or unknown provider outcome. Draft and open invoices retain their
592
- reservations, blocking recovery from a second payout. A verified paid invoice
593
- commits collection; a verified void releases the obligation for a future boundary.
594
- If an invoice is voided before its adjustment was attached, reconciliation releases
595
- an unbound sealed group only after scanning every item on that exact invoice.
596
- The receipt then has `invoiceItemId: null`. A missing previously bound item, or
597
- an absent adjustment on a paid or unpaid invoice, remains an error and keeps
598
- reservations held.
599
- Uncollectible invoices stay reserved unless your explicit host policy passes
600
- `releaseUncollectible: true`. Do not use that policy while another process might
601
- retry payment on the original invoice. Subscription cancellation alone does not
602
- prove its invoices were voided. These methods never attempt card fallback or
603
- change a payout schedule.
604
-
605
- For a collected invoice fully funded by one PaymentIntent, call
606
- `rollbackInvoice(ctx, { ...scope, groupKey, revision })`. It checks the paid
607
- invoice, completely paginates its payments, verifies the funding charge and its
608
- refund/dispute transactions, retains the original funding economics, and records
609
- a separate proportional rollback claim. Use a durable revision captured before
610
- provider reconciliation, and retry the full read on revision conflicts. Original
611
- cost claims remain intact. Multiple payments, partial allocations, mixed customer
612
- credits and non-PaymentIntent funding return
613
- `{ status: "not_ready", reason: "invoice_funding_allocation_required" }` without
614
- changing claims. Provider processing costs can also return their documented
615
- not-ready reasons. Those cases need a host-approved allocation policy rather than
616
- guessed amounts. Invoice integration in the example is a separate migration.
617
-
618
- Provider methods preserve the configured API version and propagate Stripe errors.
619
- See Stripe's [invoice item creation](https://docs.stripe.com/api/invoiceitems/create)
620
- and [invoice item pagination](https://docs.stripe.com/api/invoiceitems/list).
621
-
622
- ### Refund and dispute processing costs
623
-
624
- `getProcessingCostContext(ctx, { paymentIntentId, stripeAccountId? })` reads
625
- provider costs for an authorized payment, including refunded and disputed
626
- charges. Authorize both the payment and optional connected-account namespace in
627
- your host. The client preserves its configured API version and provider errors;
628
- it does not settle a sale, move money, create debt or decide which costs a seller
629
- owes. The example's cost adapter uses this method while keeping its billing policy
630
- in the application.
631
-
632
- A `ready` result contains every refund and dispute, source-linked balance
633
- transactions, signed fee adjustments and provider amounts in integer minor units.
634
- Dates are milliseconds. `processingFee` is the original charge balance
635
- transaction's total provider-reported fee, which can include application fees on
636
- direct charges. Each transaction exposes `feeDetails` so your approved policy can
637
- distinguish processor, application and other fees. A null breakdown means provider
638
- details were unavailable; the reported total remains authoritative. Negative fee
639
- adjustments remain credits. Failed refunds include their failure reversal instead
640
- of counting their principal as returned.
641
-
642
- `principalReturned` caps the combined economic refund/dispute principal at the
643
- original gross amount. Raw signed provider transactions remain intact, including
644
- any overlapping debits, and are not a seller debt calculation. A won dispute with
645
- an unreinstated principal withdrawal is `not_ready`. Pending refunds, missing cost
646
- transactions or different settlement currencies also return an explicit
647
- `not_ready` reason instead of estimated or mixed-currency totals. Provider
648
- pagination errors throw rather than returning partial data. Retry delayed
649
- provider data; resolve currency conversion through an explicit host policy.
650
-
651
- See Stripe's [balance transaction fields](https://docs.stripe.com/api/balance_transactions/object)
652
- and [refund failure reversals](https://docs.stripe.com/api/refunds/object).
653
-
654
- ### Optional balance-funded subscriptions
655
-
656
- Balance funding requires an eligible connected account and Stripe's Accounts v2
657
- balance-payment preview. It is separate from non-Connect customer-only Accounts
658
- v2 eligibility. Keep your normal client on GA; construct a separate client with
659
- `stripeApiVersion: STRIPE_CUSTOMER_PREVIEW_API_VERSION` for this optional feature.
660
- `getBalanceFundingCapability()` reports whether that client is explicitly
661
- configured. It does not claim the account has provider approval; Stripe validates
662
- eligibility when preparing the payment method.
663
-
664
- After authenticating the seller, authorizing the subscription, and recording
665
- explicit recurring-debit consent in your own database:
666
-
667
- ```ts
668
- const preparation = await balanceStripe.prepareBalanceFunding(ctx, {
669
- customerAccount: authorizedSellerAccountId,
670
- stripeSubscriptionId: authorizedSubscriptionId,
671
- consent: true,
672
- idempotencyKey: durablePreparationRequestId,
673
- });
674
- // Persist this immutable server-side record BEFORE enabling balance payments.
675
- await savePreparationAndConsent(preparation);
676
- await balanceStripe.setBalanceFunding(ctx, {
677
- preparation,
678
- enabled: true,
679
- consent: true,
680
- idempotencyKey: durableEnableRequestId,
681
- });
682
- // Opt-out restores the previous default method and payment-method types.
683
- await balanceStripe.setBalanceFunding(ctx, {
684
- preparation: await loadPersistedPreparation(),
685
- enabled: false,
686
- idempotencyKey: durableDisableRequestId,
687
- });
688
- ```
689
-
690
- `prepareBalanceFunding` creates/attaches a `stripe_balance` method and captures
691
- the prior subscription settings without changing them. `setBalanceFunding`
692
- checks subscription ownership and payment-method ownership, then changes the
693
- settings or recognizes that the requested state already exists. Null prior
694
- settings restore inheritance from the customer's settings. External source
695
- changes cause an error instead of being overwritten. Provider errors are
696
- preserved. Never accept restoration records or account IDs from an unauthenticated
697
- browser as authority.
698
-
699
- The example now uses component-owned
700
- [`balanceFundingWorkflow`](docs/balance-funding-workflow.md) for preparation,
701
- apply, receipts and reconciliation. Its host adapter keeps consent and request
702
- references; it no longer writes a second financial operation ledger. Existing
703
- example installations should follow the
704
- [cutover runbook](docs/example-balance-funding-cutover.md) before retiring legacy
705
- records. The stateless methods above remain supported.
706
-
707
- When using those stateless methods, serialize changes per subscription in the host. Persist the operation identity
708
- before the provider call, reuse it after a timeout or host write failure, and use
709
- a new identity for each later enable/disable cycle. An unfinished operation must prevent an opposite change from racing it; retry
710
- the pending change first. Preserve the preparation through retries. Keys must be
711
- nonempty, contain no line breaks, and be at most 247 characters because the package
712
- adds phase suffixes. Stripe's idempotency retention window still applies.
713
-
714
- Only eligible processing earnings can fund these subscriptions; top-ups cannot.
715
- Insufficient available balance in the invoice currency fails payment and does not
716
- automatically charge a saved card. Handle `invoice.payment_failed` in your host
717
- and offer an explicit alternate-method recovery flow. These operations neither
718
- pay an overdue invoice nor change payout schedules. See Stripe's
719
- [balance-payment eligibility, approval and recovery guidance](https://docs.stripe.com/payments/pay-with-balance).
720
-
721
- ### Upcoming invoice preview
722
-
723
- Authorize the customer account and subscription in your host action, then call
724
- `stripe.getUpcomingInvoicePreview(ctx, { customerAccount, stripeSubscriptionId })`.
725
- The method verifies that the subscription belongs to that account and uses your
726
- configured Stripe API version. It retrieves every invoice line, returns integer
727
- minor-unit amounts and millisecond timestamps, and preserves Stripe errors,
728
- including unavailable previews. Failed pagination throws instead of returning a
729
- partial estimate. `nextBillingAt` uses Stripe's next payment attempt, trial end,
730
- or earliest subscription-item renewal date, in that order.
731
-
732
- Pass the result through an authenticated callback to the React `InvoiceEstimate`
733
- component. It displays the provider `total` without summing line amounts. Totals
734
- can include discounts, tax or credits; `amountDue` can differ from `total` because
735
- of customer balances. Previews are estimates, not payable invoices. Application
736
- recovery costs and credits remain host-owned policy. See Stripe's
737
- [invoice preview documentation](https://docs.stripe.com/api/invoices/create_preview).
738
-
739
- ### Invoice, Payment Method, and Payout
740
-
741
- | Method | Description |
742
- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
743
- | `getInvoice(ctx, { stripeInvoiceId })` | Get invoice by Stripe invoice ID |
744
- | `getInvoiceByStripeId(ctx, { stripeInvoiceId })` | Alias for getInvoice |
745
- | `listInvoices(ctx, { stripeAccountId?, userId?, subscriptionId?, status?, limit? })` | List invoices with optional filters |
746
- | `listInvoicesByUser(ctx, { userId })` | List all invoices for a user |
747
- | `getInvoiceFromStripe(ctx, { stripeInvoiceId })` | Fetch latest invoice data directly from Stripe |
748
- | `getUpcomingInvoicePreview(ctx, { customerAccount, stripeSubscriptionId })` | Preview the next invoice with complete lines, provider totals and millisecond dates |
749
- | `listPaymentMethods(ctx, { stripeCustomerId, type? })` | List saved payment methods |
750
- | `attachPaymentMethod(ctx, { paymentMethodId, stripeCustomerId })` | Attach a payment method to a customer account |
751
- | `detachPaymentMethod(ctx, { paymentMethodId })` | Detach a payment method |
752
- | `setDefaultPaymentMethod(ctx, { stripeAccountId, paymentMethodId })` | Not supported for V2 accounts — throws with guidance to use `createBillingPortalSession()` |
753
- | `createBillingPortalSession(ctx, { stripeAccountId, returnUrl })` | Create a Stripe billing portal session URL |
754
- | `createPayout(ctx, { stripeAccountId, amount, currency?, metadata? })` | Create a payout for a Connect account |
755
- | `getPayout(ctx, { payoutId })` | Get payout by component document ID |
756
- | `listPayouts(ctx, { stripeAccountId?, status?, limit? })` | List payouts with optional filters |
757
-
758
- ### Refund and Dispute
759
-
760
- | Method | Description |
761
- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
762
- | `createRefund(ctx, { stripePaymentIntentId?, stripeChargeId?, amount?, reason?, metadata?, stripeAccountId?, refundApplicationFee?, reverseTransfer? })` | Issue a refund (provide a payment intent or charge); returns/reverses the platform fee and destination transfer by default; synced via `refund.created`/`.updated` |
763
- | `getRefundByStripeId(ctx, { stripeRefundId })` | Get a refund by Stripe refund ID |
764
- | `listRefunds(ctx, { stripeAccountId?, stripePaymentIntentId?, status?, limit? })` | List refunds with optional filters |
765
- | `paginateRefunds(ctx, { paginationOpts, stripeAccountId?, stripePaymentIntentId?, status? })` | Added after 0.16.0: bounded newest-first refund cursor pages with conjunctive host-authorized scopes; verify release before adoption |
766
- | `getDisputeByStripeId(ctx, { stripeDisputeId })` | Get a dispute by Stripe dispute ID |
767
- | `getDisputeWithCountdown(ctx, { stripeDisputeId })` | Get a dispute plus its evidence-due countdown (`daysRemaining`, `isOverdue`) |
768
- | `listDisputes(ctx, { stripeAccountId?, stripePaymentIntentId?, status?, limit? })` | List disputes with optional filters |
769
- | `uploadDisputeEvidence(ctx, { stripeDisputeId, actor, field, file, stripeAccountId? })` | Since 0.14.0: validate and upload file bytes, then attach the returned file ID to an authorized dispute draft; never submits |
770
- | `updateDispute(ctx, { stripeDisputeId, evidence?, metadata?, submit?, stripeAccountId? })` | Submit/stage dispute evidence (`submit: true` finalizes the response) |
771
- | `closeDispute(ctx, { stripeDisputeId, stripeAccountId? })` | Accept a dispute (concede the chargeback) — irreversible |
772
- | `reverseTransfers(ctx, { sourceChargeId, percent?, amount? })` | Reverse split/destination transfers for a charge (the primitive behind automatic dispute clawback; also callable manually) |
773
-
774
- `uploadDisputeEvidence` shipped in [0.14.0](https://github.com/FantasticDevHQ/better-stripe/releases/tag/v0.14.0).
775
- Call it from an authenticated server adapter with a session-derived actor. A seller
776
- can upload only for a dispute whose sale belongs to their merchant account.
777
-
778
- ```ts
779
- const { stripeFileId } = await stripe.uploadDisputeEvidence(ctx, {
780
- stripeDisputeId,
781
- actor: { type: "seller", accountId: authorizedSellerAccountId },
782
- field: "customer_communication",
783
- file: {
784
- data: evidenceBytes, // Uint8Array loaded from authorized private storage
785
- name: "communication.pdf",
786
- type: "application/pdf",
787
- },
788
- });
789
- ```
790
-
791
- The API accepts nonempty PDF, JPEG or PNG bytes up to 5,000,000 bytes, with a
792
- matching MIME type and file signature. Stripe validates the complete document.
793
- Authorization runs before upload and again before attachment. Only the returned
794
- provider file ID is bound to the chosen evidence field, with explicit
795
- `submit: false`. The result contains `stripeFileId` and `stripeDisputeId` after
796
- attachment succeeds. Use a separate authorized `updateDispute` call with
797
- `submit: true` when the user explicitly finalizes evidence.
798
-
799
- The optional `stripeAccountId` identifies the provider account owning the charge;
800
- it is distinct from the seller actor. Resolve it server-side. Do not accept
801
- browser-provided actors or file IDs as authorization. See the
802
- [upload workflow guide](docs/react-workflows.md#dispute-evidence-uploads-and-onboarding-navigation)
803
- for errors, retries and storage/transport limits.
804
-
805
- Refunds denormalize cumulative state onto the linked `payments` row (`refundedAmount`, `refundStatus: "partially_refunded" | "fully_refunded"`) so "is this payment whole?" is a single read.
806
-
807
- ### Operational
808
-
809
- | Method | Description |
810
- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
811
- | `syncAllAccounts(ctx)` | Sync all V2 accounts from Stripe to component DB |
812
- | `syncAllProducts(ctx)` | Sync all products and prices from Stripe |
813
- | `syncAllSubscriptions(ctx)` | Sync all subscriptions from Stripe |
814
- | `setupEventDestination(ctx, { url, eventPayload?, name?, description?, enabledEvents? })` | Create or update a V2 event destination (snapshot or thin) |
815
- | `listEventDestinations(ctx, { limit? })` | List all V2 event destinations |
816
- | `listWebhookEndpoints(ctx, { limit? })` | List V1 webhook endpoints |
817
- | `createWebhookEndpoint(ctx, { url, description?, enabledEvents? })` | Create a V1 webhook endpoint |
818
- | `webhookHandlers()` | Returns the `{ syncWebhook, asyncWebhook }` pair to export from a Convex module |
819
-
820
- ### Standalone Function
821
-
822
- | Function | Description |
823
- | ------------------------------------------ | ---------------------------------------------------------- |
824
- | `registerRoutes(http, component, options)` | Register the webhook HTTP endpoint on a Convex HTTP router |
825
-
826
- ## Webhook API
827
-
828
- ### registerRoutes
829
-
830
- Register the webhook endpoint on your Convex HTTP router:
831
-
832
- ```typescript
833
- import { registerRoutes } from "@fantastic.dev/better-stripe";
834
-
835
- registerRoutes(http, components.betterStripe, {
836
- webhookPath: "/stripe/webhook", // Default path
837
- stripeSecretKey: process.env.STRIPE_SECRET_KEY,
838
- webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
839
- webhookSecretV2: process.env.STRIPE_WEBHOOK_SECRET_V2, // For V2 thin events
840
- webhooks: internal.stripe, // The { syncWebhook, asyncWebhook } pair from webhookHandlers()
841
- events: { ... }, // Optional per-event handlers (advanced)
842
- onEvent: (ctx, event) => { ... }, // Optional catch-all handler (advanced)
843
- });
844
- ```
845
-
846
- ### Webhook Setup
847
-
848
- Stripe event destinations come in two flavors that cannot be mixed:
849
-
850
- - **Snapshot** (`event_payload: 'snapshot'`) — V1 events include the full object in the payload. Used for payments, subscriptions, invoices, products, and payouts.
851
- - **Thin** (`event_payload: 'thin'`) — V2 events include only the event type and object reference. The handler fetches the full object from the Stripe API. Used for Connect account lifecycle events.
852
-
853
- You need **two** event destinations pointing to the same webhook URL, each with its own signing secret.
854
-
855
- #### Programmatic setup
856
-
857
- Use `setupEventDestination()` to create or update destinations:
858
-
859
- ```typescript
860
- // Create V1 snapshot destination
861
- const v1 = await stripe.setupEventDestination(ctx, {
862
- url: webhookUrl,
863
- eventPayload: "snapshot",
864
- });
865
-
866
- // Create V2 thin destination
867
- const v2 = await stripe.setupEventDestination(ctx, {
868
- url: webhookUrl,
869
- eventPayload: "thin",
870
- });
871
- ```
872
-
873
- The method is idempotent — it finds an existing destination matching the URL and payload type, updates its events, or creates a new one.
874
-
875
- #### Admin UI setup
876
-
877
- The example app includes an `/admin/setup` page that handles webhook creation, env var verification, demo data seeding, and Stripe data syncing — all from the browser.
878
-
879
- #### Event constants
880
-
881
- ```typescript
882
- import {
883
- BETTER_STRIPE_WEBHOOK_EVENTS, // V1 snapshot events (20 events)
884
- BETTER_STRIPE_V2_WEBHOOK_EVENTS, // V2 thin events (12 events)
885
- ALL_BETTER_STRIPE_EVENTS, // Combined (32 events)
886
- } from "@fantastic.dev/better-stripe";
887
- ```
888
-
889
- ### Event Processing
890
-
891
- Records synced from Stripe objects without `userId` metadata are stored unattributed (`userId: ""`) and are not returned by user-scoped queries.
892
-
893
- The webhook handler processes events through these steps:
894
-
895
- 1. Verify Stripe signature
896
- 2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `processing`, `processed`, or `ignored`, return 200 immediately. If the previous delivery `failed` (its writes rolled back), the ledger row is reset and the event is reprocessed on Stripe's retry.
897
- 3. Upsert the component-owned domain table. When `webhooks` is configured, the upsert runs through `syncWebhook` — an internal mutation that performs the upsert **and** the sync trigger in the same transaction.
898
- 4. On failure, mark the ledger row `failed` and return 500 so Stripe retries; otherwise mark it `processed`
899
- 5. Schedule the matching `after*` async hook via `ctx.scheduler` (separate action)
900
-
901
- ### Ledger-Based Deduplication
902
-
903
- The component maintains a `webhookEvents` table that tracks every event by its Stripe event ID. This provides:
904
-
905
- - **Replay protection** -- duplicate events are detected and skipped
906
- - **Retry recovery** -- events whose processing failed (and rolled back) are reprocessed when Stripe retries, instead of deduplicating forever
907
- - **Crash recovery** -- if a delivery dies mid-processing (timeout, restart), the `processing` row goes stale after 10 minutes and the event is reprocessed on Stripe's next retry instead of deduplicating forever
908
- - **Failure tracking** -- failed events are marked with status and error message
909
- - **Observability** -- all events (including unsupported types) are logged with `ignored` status
910
-
911
- ### Supported Events
912
-
913
- **Accounts V2 (thin events -- component fetches latest state, requires V2 event destination):**
914
-
915
- - `v2.core.account.created`, `.updated`
916
- - `v2.core.account[identity].updated`
917
- - `v2.core.account[requirements].updated`
918
- - `v2.core.account[configuration.merchant].updated`, `.capability_status_updated`
919
- - `v2.core.account[configuration.customer].updated`
920
- - `v2.core.account[configuration.recipient].updated`
921
- - `v2.core.account[defaults].updated`
922
- - `v2.core.account_person.created`, `.updated`
923
- - `v2.core.account_link.returned`
924
-
925
- **Billing (snapshot events -- payload contains full state):**
926
-
927
- - `checkout.session.completed`
928
- - `customer.subscription.created`, `.updated`, `.deleted`, `.trial_will_end`
929
- - `invoice.created`, `.finalized`, `.paid`, `.payment_failed`
930
- - `payment_intent.succeeded`, `.payment_failed`, `.canceled`
931
- - `payout.created`, `.updated`, `.paid`, `.failed`, `.canceled`
932
-
933
- - `refund.created`, `.updated`, `.failed`
934
- - `application_fee.refunded` -- keeps `feeCollectedAmount`/`feeRefundedAmount` accurate on the linked payment
935
- - `charge.dispute.created`, `.updated`, `.closed`, `.funds_withdrawn`, `.funds_reinstated`
936
- - `product.created`, `.updated`
937
- - `price.created`, `.updated`
938
-
939
- Note: Subscription and invoice events use v1 Billing API event names even when the billing entity is a V2 account referenced via `customer_account`.
940
-
941
- Dedicated payout cancellations use the same signed V1 endpoint, payout record
942
- and connected-account association as other payout events. Generic `onEvent`
943
- and `events["payout.canceled"]` callbacks run after reconciliation. Cancellation
944
- does not invoke the paid/completed convenience hook. Normal verified replay is
945
- deduplicated by the existing event ledger.
946
-
947
- When upgrading from 0.11.0 or earlier, add `payout.canceled` to the existing V1
948
- endpoint's selected events. New endpoints created with the corrected package's
949
- defaults include it. Updating the library alone does not edit an existing provider
950
- endpoint or recover already missed events. Consumers must adopt a published
951
- version containing this correction; a merged source fix is not a package release.
952
-
953
- ## Trigger API
954
-
955
- The trigger system follows the BetterAuth pattern: define callbacks at client init time, export the `syncWebhook`/`asyncWebhook` pair via `webhookHandlers()`, and pass their function references to `registerRoutes` via `webhooks`.
956
-
957
- ### SyncTriggers
958
-
959
- Sync triggers run in the same transaction as the component's database write. They must be DB-only and idempotent. Throwing from a sync trigger rolls back the entire transaction (including the component upsert), causing Stripe to retry the webhook.
960
-
961
- ```typescript
962
- interface SyncTriggers {
963
- account?: {
964
- onCreate?: (ctx, doc) => Promise<void>;
965
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
966
- };
967
- subscription?: {
968
- onCreate?: (ctx, doc) => Promise<void>;
969
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
970
- onDelete?: (ctx, doc) => Promise<void>;
971
- };
972
- checkoutSession?: {
973
- onCompleted?: (ctx, doc) => Promise<void>;
974
- };
975
- product?: {
976
- onCreate?: (ctx, doc) => Promise<void>;
977
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
978
- };
979
- price?: {
980
- onCreate?: (ctx, doc) => Promise<void>;
981
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
982
- };
983
- invoice?: {
984
- onCreate?: (ctx, doc) => Promise<void>;
985
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
986
- };
987
- payment?: {
988
- onCreate?: (ctx, doc) => Promise<void>;
989
- };
990
- payout?: {
991
- onCreate?: (ctx, doc) => Promise<void>;
992
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
993
- };
994
- refund?: {
995
- onCreate?: (ctx, doc) => Promise<void>;
996
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
997
- };
998
- dispute?: {
999
- onCreate?: (ctx, doc) => Promise<void>;
1000
- onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
1001
- };
1002
- }
1003
- ```
1004
-
1005
- ### AsyncHooks
1006
-
1007
- Async hooks run after the component's database write commits, in a separate scheduled action. Use these for external API calls (email, Slack, analytics). Failures do not roll back the component write.
1008
-
1009
- ```typescript
1010
- interface AsyncHooks {
1011
- onAccountUpdated?: (ctx, account) => Promise<void>;
1012
- onCheckoutCompleted?: (ctx, session) => Promise<void>;
1013
- onSubscriptionUpdated?: (ctx, subscription) => Promise<void>;
1014
- onSubscriptionCanceled?: (ctx, subscription) => Promise<void>;
1015
- onTrialEnding?: (ctx, subscription) => Promise<void>;
1016
- onInvoicePaid?: (ctx, invoice) => Promise<void>;
1017
- onInvoicePaymentFailed?: (ctx, invoice) => Promise<void>;
1018
- onPaymentSucceeded?: (ctx, payment) => Promise<void>;
1019
- onPaymentFailed?: (ctx, payment) => Promise<void>;
1020
- onPayoutCompleted?: (ctx, payout) => Promise<void>;
1021
- onRefundCreated?: (ctx, refund) => Promise<void>;
1022
- onDisputeCreated?: (ctx, dispute) => Promise<void>;
1023
- onDisputeClosed?: (ctx, dispute) => Promise<void>;
1024
- }
1025
- ```
1026
-
1027
- ### webhookHandlers()
1028
-
1029
- Returns the `{ syncWebhook, asyncWebhook }` pair that bridges your app callbacks into the webhook processing pipeline. Export them from a Convex module (e.g. `convex/stripe.ts`) so they get function references the webhook handler can call:
1030
-
1031
- ```typescript
1032
- export const { syncWebhook, asyncWebhook } = stripe.webhookHandlers();
1033
- ```
1034
-
1035
- Then pass the module to `registerRoutes` as `webhooks: internal.stripe`.
1036
-
1037
- **How `syncWebhook` works.** It is a single internal mutation that routes by a `dispatcher` discriminator to perform the component table upsert **and** your configured sync trigger inside one transaction. It reads the existing doc (to decide `onCreate` vs `onUpdate` and supply `oldDoc`), runs the upsert, re-reads the doc, and invokes your trigger. If the trigger throws, the whole mutation — including the component write — rolls back, the webhook handler marks the ledger row `failed`, and returns 500 so Stripe retries. On retry, failed ledger rows are reset and the event is reprocessed.
1038
-
1039
- **How `asyncWebhook` works.** It is a single internal action that routes by a `hook` discriminator. After the `syncWebhook` transaction commits and the ledger marks the event `processed`, the webhook handler schedules `asyncWebhook` via `ctx.scheduler` with the committed doc. Hook failures never roll back the component write.
1040
-
1041
- Exactly one hook (at most) is scheduled per event:
1042
-
1043
- | Stripe event | Scheduled hook |
1044
- | ------------------------------------------------- | --------------------------- |
1045
- | `v2.core.account*` (all account lifecycle events) | `afterAccountUpdated` |
1046
- | `checkout.session.completed` | `afterCheckoutCompleted` |
1047
- | `customer.subscription.created` / `.updated` | `afterSubscriptionUpdated` |
1048
- | `customer.subscription.deleted` | `afterSubscriptionCanceled` |
1049
- | `customer.subscription.trial_will_end` | `afterTrialEnding` |
1050
- | `invoice.paid` | `afterInvoicePaid` |
1051
- | `invoice.payment_failed` | `afterInvoicePaymentFailed` |
1052
- | `payment_intent.succeeded` | `afterPaymentSucceeded` |
1053
- | `payment_intent.payment_failed` | `afterPaymentFailed` |
1054
- | `payout.paid` | `afterPayoutCompleted` |
1055
- | `refund.created` | `afterRefundCreated` |
1056
- | `charge.dispute.created` | `afterDisputeCreated` |
1057
- | `charge.dispute.closed` | `afterDisputeClosed` |
1058
-
1059
- All other processed events (e.g. `payment_intent.canceled`, `payout.failed`, `invoice.created`, `refund.updated`, `charge.dispute.funds_withdrawn`) update the component tables but schedule no hook.
1060
-
1061
- > **Note:** async hooks should be idempotent. Duplicate delivery is possible in rare ledger-failure cases (e.g. the event is processed and the hook scheduled, but the ledger update fails and Stripe redelivers).
1062
-
1063
- The raw callbacks you pass to `triggers` and `hooks` on the `BetterStripe` constructor are the source of truth for app behavior. The exported `syncWebhook`/`asyncWebhook` pair is the bridge that makes them callable from the Convex runtime — events whose triggers you did not configure simply run the upsert (no sync trigger) and schedule no hook.
1064
-
1065
- ### Dunning & smart retries
1066
-
1067
- Failed recurring payments are recovered by **Stripe Smart Retries**, not by any retry loop in this library. The component never re-attempts a charge itself — it tracks the delinquency and fires hooks so your app can notify the customer. Retry _timing and count_ are owned entirely by Stripe.
1068
-
1069
- **Required Dashboard settings** (Stripe controls the schedule; enable these once):
1070
-
1071
- - **Subscriptions:** Dashboard → **Billing → Revenue recovery → Retries** — turn on **Smart Retries** (Stripe's recommended, ML-timed schedule). Also set what happens when retries are exhausted (leave `past_due`, mark `unpaid`, or cancel).
1072
- - **One-time invoices:** Dashboard → **Settings → Billing → Invoices** — configure retry behavior for invoices not tied to a subscription.
1073
- - Ensure the `invoice.payment_failed` and `customer.subscription.updated` events are delivered to your webhook endpoint.
1074
-
1075
- **What the component surfaces:**
1076
-
1077
- - The subscription row tracks Stripe's delinquency states — `past_due` (first failed charge) and `unpaid` (retries exhausted) — arriving via `customer.subscription.updated`, which fires **`onSubscriptionUpdated`**.
1078
- - Each `invoice.payment_failed` fires **`onInvoicePaymentFailed`** with the committed invoice. Under Smart Retries the invoice carries `nextPaymentAttempt` (ISO time of Stripe's next retry) and `attemptCount`, so a dunning email can tell the buyer exactly when Stripe will try again. Both clear once the invoice is paid or retries stop.
1079
-
1080
- `onInvoicePaymentFailed` is the **invoice-level** (subscription-cycle) failure — distinct from `onPaymentFailed`, which fires on a one-time **PaymentIntent** failure (`payment_intent.payment_failed`) and receives a payment, not an invoice.
1081
-
1082
- > **Limitation:** `nextPaymentAttempt` is captured from the `invoice.payment_failed` payload, which is correct for Smart Retries. If you instead use a **custom retry _automation_**, Stripe sets `next_payment_attempt` on `invoice.updated` (not `invoice.payment_failed`); the component does not currently process `invoice.updated`, so the retry timestamp may lag until the next handled invoice event.
1083
-
1084
- ## Marketplace Economics
1085
-
1086
- The platform is always the merchant of record (Skool-style marketplace model): sellers are Connect recipients, not merchants. This section covers the fee, split, payout, dispute, and refund/descriptor primitives that implement that model. All amounts are minor units (cents).
1087
-
1088
- ### Fee Model
1089
-
1090
- `PlatformFeeConfig` is the platform's take on a sale:
1091
-
1092
- ```typescript
1093
- type FeeTier = { upTo: number | null; percent: number; fixed?: number };
1094
- type PlatformFeeConfig = {
1095
- percent: number; // base percentage (0–100)
1096
- fixed?: number; // optional fixed surcharge, minor units
1097
- tiers?: FeeTier[]; // optional; overrides the base by charge amount
1098
- };
1099
- ```
1100
-
1101
- Configure a default at construction (`new BetterStripe(component, { platformFee: {...} })`), and/or pass a per-call `fee` override (type `FeeOverride`, same shape as `PlatformFeeConfig`) to `createCheckoutSession`/`createSubscription` — the override wins. `stripe.resolveFee(override?)` resolves the effective config the same way the client does internally, and `stripe.platformFee` reads the configured default back.
1102
-
1103
- ```typescript
1104
- import { computeFee } from "@fantastic.dev/better-stripe";
1105
-
1106
- const { feeAmount, percentApplied, fixedApplied, tier } = computeFee(2999, {
1107
- percent: 10,
1108
- fixed: 30,
1109
- });
1110
- ```
1111
-
1112
- `computeFee(amount, config)` picks the first tier whose `upTo` covers the amount (a final `upTo: null` is the catch-all), rounds half-up, and caps the fee at the charge amount. It's exported so an app can preview "platform keeps $X" client-side before checkout.
1113
-
1114
- **How the fee is charged** depends on shape and charge type:
1115
-
1116
- - **Percent-only** fees (`isPercentOnlyFee(config)` — no `fixed`, no `tiers`) map directly to Stripe's `application_fee_percent` on the subscription/PaymentIntent — no per-invoice computation needed.
1117
- - **Fixed or tiered** fees can't be expressed as a flat Stripe percentage, so they're computed and applied per invoice (`applyPerInvoiceFee`, at `invoice.created`) or per one-time charge (`applyPerChargeFee`) in the webhook processor, via `application_fee_amount`.
1118
- - For synchronously finalized first invoices, `invoice.paid` collects the missed fixed/tiered fee through a partial destination-transfer reversal. See [first-invoice fee handling](#roadmap--known-gaps).
1119
-
1120
- Fees only apply to **destination charges** (`destinationAccountId` set, or a single-recipient `split`). The **separate-charges-and-transfers** path (multi-recipient `split`) never uses `application_fee` — the platform's cut is realized by transferring less than was charged (see Split Engine below).
1121
-
1122
- ### Split Engine
1123
-
1124
- For a sale split across multiple recipients (store + affiliate(s)), pass `split` instead of `destinationAccountId` to `createCheckoutSession`/`createSubscription`:
1125
-
1126
- ```typescript
1127
- type SplitRecipient = {
1128
- destinationAccountId: string;
1129
- role: "store" | "affiliate" | "other";
1130
- amount?: number; // exactly one of amount/percent
1131
- percent?: number; // percent of the gross charge amount
1132
- };
1133
-
1134
- await stripe.createCheckoutSession(ctx, {
1135
- userId,
1136
- stripePriceId,
1137
- mode: "payment",
1138
- returnUrl,
1139
- split: [
1140
- { destinationAccountId: storeAccountId, role: "store", percent: 80 },
1141
- {
1142
- destinationAccountId: affiliateAccountId,
1143
- role: "affiliate",
1144
- percent: 10,
1145
- },
1146
- ],
1147
- fee: { percent: 10 }, // per-call override; omit to use the configured default
1148
- });
1149
- ```
1150
-
1151
- - **A single-recipient `split`** is treated as a plain destination charge (equivalent to `destinationAccountId`) — `application_fee_percent`/`application_fee_amount` applies as above.
1152
- - **A multi-recipient `split`** routes via **separate charges & transfers**: the platform charges the full amount, then the webhook engine (`createSplitTransfers`, on `payment_intent.succeeded`/`invoice.paid`) creates one Stripe `Transfer` per recipient with `source_transaction` linkage. No `application_fee` is used on this path — the platform's cut is the remainder after transfers.
1153
- - **Subscriptions** re-run the split on every billing cycle (each invoice re-reads the subscription's `split`/`feeConfig` markers), so per-cycle recipient amounts stay in sync with the config at charge time.
1154
-
1155
- The core math is exported for previewing splits client-side:
1156
-
1157
- ```typescript
1158
- import { computeSplit } from "@fantastic.dev/better-stripe";
1159
-
1160
- const result = computeSplit(10000, { percent: 10 }, [
1161
- { destinationAccountId: "acct_store", role: "store", percent: 80 },
1162
- { destinationAccountId: "acct_affiliate", role: "affiliate", percent: 10 },
1163
- ]);
1164
- // result.transfers: [{ destinationAccountId, role, amount }, ...]
1165
- // result.platformFee: the resolver's cut; result.platformRetained: amount − sum(transfers)
1166
- ```
1167
-
1168
- `computeSplit` throws if the transfers plus the platform fee would exceed the charge amount — the platform is always left with at least its configured cut. Any rounding remainder stays with the platform.
1169
-
1170
- ### Payouts
1171
-
1172
- Payouts are **automatic and rolling** (Stripe-managed schedule, via hosted Express onboarding) — there is no manual-withdrawal API. `listPayouts`/`createPayout` track/trigger payouts for a Connect account; `PayoutSchedule` (React) and `useEarnings` (React) surface the recipient's balance and next expected payout, with a link out to the hosted Express dashboard for details. See [React Hooks](#react-hooks) and [React Components](#react-components).
1173
-
1174
- ### Disputes
1175
-
1176
- The platform is merchant of record, so a chargeback lands on the platform's Stripe account even for a seller's sale. The dispute pipeline (all webhook-driven, on `charge.dispute.*`):
1177
-
1178
- 1. **Clawback** — a monetary `charge.dispute.created` event uses the disputed charge's original gross amount to calculate affiliate commission exposure. Inquiry/warning, prevented, and already-won payloads do not trigger recovery. Affiliate legs share the original-principal exposure axis with refunds; seller and other legs retain the existing reversal allocation. The dispute ID identifies the operation, and a missing authoritative charge amount causes recovery to retry.
1179
- 2. **Reinstatement** — if the dispute is won (`.closed` with `status: "won"`, or `.funds_reinstated`), the existing `reinstateTransfers` path creates new transfers from the platform balance. Affiliate restoration uses exact reversal/offset receipts, preserves independent successful refunds, and cancels unpaid dispute debt. Failed or uncertain restoration remains visible until reconciled. See [recovery limitations](docs/affiliate-clawbacks.md#verification-evidence).
1180
- 3. **Auto-cancel** — on dispute open, the disputed subscription (resolved PaymentIntent → invoice → subscription) is canceled by default (`registerRoutes`'s `autoCancelOnDispute`, default `true`; pairs with `cancelDisputeAtPeriodEnd`, default `false` → cancel-at-period-end, matching the Skool model of "cancel now, remove access at cycle end").
1181
-
1182
- Sellers respond to their own disputes without platform staff involvement, via an embedded Stripe Connect session:
1183
-
1184
- ```typescript
1185
- // server: expose the account session
1186
- export const createDisputeSession = action({
1187
- args: { stripeAccountId: v.string() },
1188
- handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
1189
- });
1190
- ```
1191
-
1192
- `stripe.createDisputeSession(ctx, { stripeAccountId })` creates an Account Session scoped to `disputes_list`/`payment_disputes` — mount it with the `ConnectProvider`/`EmbeddedDisputes` React components (see [Embedded Disputes](#embedded-disputes-stripe-connect)), or build a custom UI on `updateDispute`/`closeDispute` plus the headless `DisputesList`/`DisputeDetail`/`EvidenceForm` components and `buildDisputeEvidence`/`disputeEvidenceCountdown` helpers (see [React Components](#react-components)).
1193
-
1194
- `stripe.reverseTransfers(ctx, { sourceChargeId, percent?, amount? })` is also exposed directly, for manual clawback outside the automatic dispute flow (e.g. a support-initiated partial reversal). The internal engine additionally accepts an `operationId` for a stable Stripe idempotency key (used by the automatic dispute flow); the public method doesn't expose it yet, so a manual call relies on Stripe's default request idempotency.
1195
-
1196
- For commissions tracked by the recovery ledger, generic manual reversal is
1197
- rejected. Use `createRefund` for a real refund or `stripe.affiliateRecovery.retry`
1198
- for a recovery operation, so existing offsets and uncertain receipts remain
1199
- coordinated.
1200
-
1201
- ### Affiliate commission accounting
1202
-
1203
- The component stores each original affiliate transfer's commission and currency,
1204
- links available payment/invoice references, and separates finalized obligations,
1205
- provisional dispute exposure, reserved slices, and confirmed reversals. New
1206
- commission reversal operations reconcile exact Stripe receipts after interrupted
1207
- ledger writes. Percentage and fixed commissions use the original allocated
1208
- amount, with deterministic rounding in integer currency units.
1209
-
1210
- Trusted host APIs under `components.betterStripe.settlement` provide
1211
- `queries.listAffiliateObligations` and
1212
- `mutations.migrateAffiliateObligations`. Authorize account ownership before
1213
- exposing snapshots and restrict migration to operators. Existing rows with
1214
- unattributed reversal balances require reconciliation. See the
1215
- [API and migration guide](docs/affiliate-clawbacks.md#migration-and-operator-reconciliation).
1216
-
1217
- Insufficient-balance debt is offset atomically against eligible future commissions
1218
- in the same currency before transfer creation. Dispute wins restore only actual
1219
- reversals/offsets and retain independent refunds. `stripe.affiliateRecovery`
1220
- provides snapshots, history, operator retry and legacy review; the reusable
1221
- `AffiliateRecovery`/`AffiliateRecoveryHistory` views consume those records.
1222
-
1223
- Affiliate payouts require a stable idempotency key and pass an atomic debt and
1224
- reservation gate. An optional `minimumAmount` applies a host-authorized currency
1225
- minimum; it is not a discovered provider floor. Transfer reversal does not recall
1226
- a completed bank payout, Stripe-managed automatic bank payouts remain outside
1227
- this gate, and Global Payouts is unsupported. See the guide for account capability
1228
- checks, maintenance jobs and live sandbox verification requirements.
1229
-
1230
- ### Refunds and Statement Descriptors
1231
-
1232
- `createRefund(ctx, { stripePaymentIntentId?, stripeChargeId?, amount?, reason?, refundApplicationFee?, reverseTransfer?, ... })` issues a Stripe refund with marketplace semantics, both defaulting **on**:
1233
-
1234
- - `refundApplicationFee` — return the platform's application fee pro-rata with the refund (destination charges only; Stripe pro-rates partial refunds automatically).
1235
- - `reverseTransfer` — pull the refunded amount back from the destination account (destination charges only; also pro-rated for partials).
1236
-
1237
- Stripe hard-errors if either flag is sent for a charge that doesn't carry an application fee / destination transfer, so `createRefund` resolves the charge first and only sends each flag when the charge can honor it. **Split (separate-charges) sales carry neither** — those go through the same charge, so their clawback is webhook-driven: on `refund.created`/`.updated`, `reverseTransfersForRefund` reverses each recipient's ledger leg pro-rata to the cumulative amount of live refunds whose status is `succeeded`. Pending, action-required, failed, and canceled refunds are excluded; `charge.amount_refunded` alone can include pending refunds. Affiliate legs converge on the larger successful-refund or dispute exposure, capped at the original commission, so the same principal is not recovered twice. A separate `application_fee.refunded` handler keeps the linked payment's `feeCollectedAmount`/`feeRefundedAmount` in sync. The `refunds` table and the linked `payments` row update as the corresponding webhooks arrive; `createRefund` itself returns only the new refund id.
1238
-
1239
- Per-store statement descriptors make destination charges recognizable on a buyer's card statement (`PLATFORMPREFIX* SUFFIX`):
1240
-
1241
- ```typescript
1242
- await stripe.setAccountStatementDescriptor(ctx, {
1243
- stripeAccountId,
1244
- statementDescriptor: "ACME STORE", // or null to clear
1245
- });
1246
- ```
1247
-
1248
- Validated against Stripe's rules (`validateStatementDescriptorSuffix`: 1–22 chars, at least one Latin letter, no `< > \ ' " *`, no non-Latin — rejects rather than truncates) before writing. Resolution order per charge: the store's stored suffix → the platform's configured `statementDescriptorSuffix` default (constructor option) → none. One-time payments set the suffix directly on the PaymentIntent at checkout. Store-owned products carry the descriptor for subscriptions' first charges; the webhook processor sets it on later invoices. Refresh existing products with `updateProduct` after changing a store's descriptor.
1249
-
1250
- ## React Hooks
1251
-
1252
- Import from `@fantastic.dev/better-stripe/react`. All hooks use Convex's `useQuery` and `useMutation` internally.
1253
-
1254
- Read hooks are exported as factory functions that take the app's `useQuery` binding and a query function reference, allowing them to work with any component registration name. Hooks that take a single ID argument accept `undefined` and skip the query (via Convex's `"skip"` sentinel) until the ID is available.
1255
-
1256
- ### Read Hooks
1257
-
1258
- | Hook Factory | Hook Arguments | Returns |
1259
- | ------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
1260
- | `createUseAccount` | `(userId?)` | `{ account, isLoading }` |
1261
- | `createUseProducts` | `({ accountId?, active? }?)` | `{ products, isLoading }` |
1262
- | `createUsePrices` | `(productId?)` | `{ prices, isLoading }` |
1263
- | `createUseSubscription` | `(subscriptionId?)` | `{ subscription, isActive, isTrialing, isCanceling, daysUntilRenewal, daysUntilTrialEnd, isLoading }` |
1264
- | `createUseSubscriptions` | `({ userId?, status? }?)` | `{ subscriptions, activeSubscription, isLoading }` |
1265
- | `createUseCheckout` | `(sessionId?)` | `{ session, status, isComplete, isLoading }` |
1266
- | `createUsePaymentMethods` | `(accountId?)` | `{ methods, defaultMethod, isLoading }` |
1267
- | `createUseInvoices` | `({ userId?, subscriptionId?, status? }?)` | `{ invoices, isLoading }` |
1268
- | `createUseAccountOnboarding` | `(accountId?)` | `{ account, status, isReady, missingRequirements, isLoading }` |
1269
- | `createUseEarnings` | `(accountId?)` | `{ gross, reversed, net, payouts, paidOut, transfers, isLoading }` — recipient balance/earnings |
1270
- | `createUseSplitBreakdown` | `({ sourceChargeId?, saleAmount? })` | `{ breakdown: { legs, store, affiliate, other, recipientsTotal, platform? } \| null, isLoading }` — per-sale split |
1271
- | `createUseDisputes` | `({ accountId?, status? }?)` | `{ disputes, isLoading }` |
1272
- | `createUseDisputeWithCountdown` | `(stripeDisputeId?)` | `{ dispute, countdown: { dueBy?, daysRemaining?, isOverdue } \| null, isLoading }` |
1273
-
1274
- ### Checkout Session Hooks
1275
-
1276
- For Stripe Checkout Session custom UI flows (CheckoutProvider-based):
1277
-
1278
- | Hook / Component | Description |
1279
- | ------------------------- | ----------------------------------------------------------------------------------------------------------- |
1280
- | `CheckoutSessionProvider` | Provider wrapping Stripe's `CheckoutProvider`. Accepts `publishableKey`, `clientSecret`, `appearance`. |
1281
- | `useCheckoutSession()` | Returns `{ type, sessionId, canConfirm, confirm(opts?) }` — discriminated union for checkout state/actions. |
1282
-
1283
- ```tsx
1284
- import {
1285
- CheckoutSessionProvider,
1286
- PaymentElement,
1287
- useCheckoutSession,
1288
- } from "@fantastic.dev/better-stripe/react";
1289
-
1290
- <CheckoutSessionProvider publishableKey={pk} clientSecret={token}>
1291
- <MyForm />
1292
- </CheckoutSessionProvider>;
1293
-
1294
- function MyForm() {
1295
- const checkout = useCheckoutSession();
1296
- if (checkout.type !== "success") return <Spinner />;
1297
- return (
1298
- <>
1299
- <PaymentElement />
1300
- <button
1301
- disabled={!checkout.canConfirm}
1302
- onClick={() => checkout.confirm()}
1303
- >
1304
- Pay
1305
- </button>
1306
- </>
1307
- );
1308
- }
1309
- ```
1310
-
1311
- ### Payment Confirmation Hooks
1312
-
1313
- | Hook | Description |
1314
- | --------------------- | ----------------------------------------------------------------------------------------------------- |
1315
- | `useConfirmPayment()` | Provides `confirmPayment(clientSecret)`, `confirmCardSetup(clientSecret)`, `confirmSetup(returnUrl?)` |
1316
-
1317
- All return `{ success: true } | { success: false, error: string }`.
1318
-
1319
- ### Payment Method Action Hooks
1320
-
1321
- | Hook | Description |
1322
- | ----------------------------- | ------------------------------------------------------------------------------------- |
1323
- | `usePaymentMethodActions(cb)` | Provides `createAndAttach()`, `detach(id)`, `setDefault(id)` with loading/error state |
1324
-
1325
- Accepts app-provided callbacks for backend operations (attach, detach, setDefault, reload).
1326
-
1327
- ### Theming
1328
-
1329
- | API | Description |
1330
- | -------------------------------- | ------------------------------------------------------------------------- |
1331
- | `createStripeAppearance(config)` | Factory: color tokens → Stripe `Appearance` object |
1332
- | `createStripeElementStyles(cfg)` | Factory: color tokens → inline `style` for CardNumber/Expiry/CVC elements |
1333
- | `defaultStripeAppearance` | Light preset |
1334
- | `darkStripeAppearance` | Dark preset |
1335
-
1336
- ### Re-exported Stripe Elements
1337
-
1338
- These are re-exported so apps never need to import from `@stripe/react-stripe-js` directly:
1339
-
1340
- `PaymentElement`, `CardElement`, `CardNumberElement`, `CardExpiryElement`, `CardCvcElement`
1341
-
1342
- ## React Components
1343
-
1344
- Import from `@fantastic.dev/better-stripe/react`. The package includes the
1345
- example's reusable checkout, payouts, refunds, disputes, accounts, onboarding,
1346
- products, subscriptions, billing, referrals, and admin/setup workflows.
1347
-
1348
- Use native unstyled markup, render props, or companion hooks with your own
1349
- design system. Bind authenticated server callbacks and query data in your app.
1350
- Supported workflows can select Stripe Connect embedded presentation; checkout
1351
- supports five integrations. No example router, persona provider, or CSS is required.
1352
-
1353
- See [the React workflow guide](docs/react-workflows.md) for usage, the full
1354
- component/hook matrix, styling, data contracts, and Stripe integration limits.
1355
- Existing low-level components remain available below. Props vary by component;
1356
- Stripe iframe styling uses `appearance`, while custom markup uses render props
1357
- or the low-level component's `className`/label props.
1358
-
1359
- ### Hosted onboarding navigation
1360
-
1361
- Since 0.14.0, `Onboarding` and `useOnboarding` suppress hosted navigation from
1362
- create/continue responses after unmount or authenticated scope replacement.
1363
- Current-scope responses still navigate through `onNavigate` or the default
1364
- `window.location.assign`. Shared pending locks, duplicate-submit prevention and
1365
- error state remain intact. Set `scopeKey` to identify the authenticated
1366
- account/resource; it controls lifecycle isolation and does not authorize access.
1367
- See the [workflow guide](docs/react-workflows.md#dispute-evidence-uploads-and-onboarding-navigation).
1368
-
1369
- ### Provider
1370
-
1371
- | Component | Description |
1372
- | ------------------------- | ------------------------------------------------------------------------------------------------ |
1373
- | `StripeProvider` | Stripe Elements context provider. Accepts `publishableKey` prop. |
1374
- | `CheckoutSessionProvider` | Checkout Session context provider for custom UI flows. Accepts `publishableKey`, `clientSecret`. |
1375
-
1376
- ### Checkout and Subscription
1377
-
1378
- | Component | Description |
1379
- | ----------------------- | --------------------------------------------------------- |
1380
- | `EmbeddedCheckout` | Headless embedded checkout with render-prop loading state |
1381
- | `CheckoutStatus` | Checkout session status display |
1382
- | `PricePicker` | Plan/price selection with render-prop customization |
1383
- | `PriceCard` | Individual price card (controlled or uncontrolled) |
1384
- | `IntervalSelector` | Billing interval toggle (month/year) |
1385
- | `SubscriptionCard` | Current subscription display |
1386
- | `SubscriptionLineItems` | Line item breakdown |
1387
- | `PriceBadge` | Price/plan badge |
1388
- | `TrialAlert` | Trial status and renewal alert |
1389
- | `BillingPortalLink` | Link/button to Stripe billing portal |
1390
- | `SubscriptionActions` | Cancel/reactivate action buttons (status-aware) |
1391
-
1392
- ### Payment Methods
1393
-
1394
- | Component | Description |
1395
- | --------------------------- | -------------------------------------------------- |
1396
- | `AddCardForm` | Headless add-payment-method form |
1397
- | `PaymentMethodsList` | Saved payment methods list with render props |
1398
- | `DeletePaymentMethodDialog` | Remove payment method (app provides dialog chrome) |
1399
- | `PaymentMethodActions` | Per-method set-default/delete actions |
1400
-
1401
- ### Buyer Billing
1402
-
1403
- | Component | Description |
1404
- | ------------------ | ------------------------------------------------------------------------------------------------------- |
1405
- | `BuyerBillingView` | Per-store buyer billing view: subscriptions grouped by store, reusable saved card, embedded card update |
1406
-
1407
- An embedded-only billing surface for buyers: their subscriptions are grouped by
1408
- store (each store scoped via the `listSubscriptionsByUserAndStore` /
1409
- `groupSubscriptionsByStore` per-store queries) with per-store cancel/reactivate,
1410
- alongside the ONE saved payment method that is reusable across every store. The
1411
- card is updated in place via an embedded `AddCardForm` slot — no redirect.
1412
-
1413
- ```tsx
1414
- import {
1415
- BuyerBillingView,
1416
- AddCardForm,
1417
- StripeProvider,
1418
- } from "@fantastic.dev/better-stripe/react";
1419
- import { groupSubscriptionsByStore } from "@fantastic.dev/better-stripe";
1420
-
1421
- function BuyerBilling({ userId, customerAccount }: Props) {
1422
- const subscriptions = useQuery(api.stripe.listSubscriptionsByUser, {
1423
- userId,
1424
- });
1425
- const { defaultMethod } = usePaymentMethods(customerAccount);
1426
- const cancel = useMutation(api.stripe.cancelSubscription);
1427
- const reactivate = useMutation(api.stripe.reactivateSubscription);
1428
-
1429
- return (
1430
- <BuyerBillingView
1431
- // groupSubscriptionsByStore reused, not recomputed
1432
- subscriptions={subscriptions?.map((s) => ({
1433
- ...s,
1434
- id: s.stripeSubscriptionId,
1435
- }))}
1436
- paymentMethod={defaultMethod}
1437
- isLoading={subscriptions === undefined}
1438
- onCancel={(sub) => cancel({ stripeSubscriptionId: sub.id })}
1439
- onReactivate={(sub) => reactivate({ stripeSubscriptionId: sub.id })}
1440
- updateCardSlot={
1441
- <StripeProvider publishableKey={pk}>
1442
- <AddCardForm onSuccess={handleCardSaved} />
1443
- </StripeProvider>
1444
- }
1445
- />
1446
- );
1447
- }
1448
- ```
1449
-
1450
- ### Connect and Marketplace
96
+ Passing `webhooks: internal.stripe` runs your sync triggers in the same transaction
97
+ as component writes. Async hooks run after commit. See [webhooks and triggers](docs/webhooks.md)
98
+ for event destinations, signing secrets, and hook examples.
1451
99
 
1452
- | Component | Description |
1453
- | ------------------------- | --------------------------------------------- |
1454
- | `ConnectStatusBadge` | Connect verification status badge |
1455
- | `AccountOnboardingCard` | Connect onboarding progress display |
1456
- | `AccountOnboardingButton` | Continue onboarding action (status-aware) |
1457
- | `AccountCreateCard` | Create Connect account card |
1458
- | `AccountCreateButton` | Create account action with loading state |
1459
- | `AccountLoginCard` | Login to Connect dashboard card |
1460
- | `AccountLoginButton` | Dashboard login/open action |
1461
- | `AccountCloseCard` | Close/restart account card (status-aware) |
1462
- | `AccountCloseButton` | Close/restart action with status-aware labels |
1463
- | `ConnectRequirements` | Missing requirements checklist |
100
+ Create separate V1 snapshot and V2 thin event destinations pointing to
101
+ `https://<your-deployment>.convex.site/stripe/webhook`. Store their signing secrets
102
+ as `STRIPE_WEBHOOK_SECRET` and `STRIPE_WEBHOOK_SECRET_V2` in your Convex deployment.
103
+ Follow [webhook setup](docs/webhooks.md#webhook-setup) to configure both destinations.
1464
104
 
1465
- ### Payouts and Earnings
105
+ ## Documentation
1466
106
 
1467
- Use React's `formatPayoutAmount(amount, currency, locale?)` when rendering
1468
- observed ordinary Stripe balances and payouts. It preserves supported currency
1469
- units, including JPY and fractional ISK/UGX compatibility values. Unknown
1470
- precision is shown explicitly as raw minor units with `display unavailable`.
1471
- This display helper does not establish payout eligibility or Global Payouts
1472
- currency support. See the [React workflow guide](docs/react-workflows.md).
107
+ The [documentation index](docs/README.md) lists all guides. Start with:
1473
108
 
1474
- | Component | Description |
1475
- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1476
- | `PayoutSchedule` | Recipient balance + next-payout display, fed by a `balance` snapshot and `listPayouts` rows. Payouts are automatic/rolling — no manual-withdrawal action is offered. |
1477
- | `EarningsSummary` | Gross / reversals & adjustments / net + latest payout, fed by `useEarnings(accountId)`. Reversals cover both deferred fee collection and refund/dispute clawbacks — not a pure fees figure, hence the "Reversals & adjustments" label rather than "Fees". |
1478
- | `SplitBreakdown` | Per-sale store / affiliate / other / platform split lines, fed by `useSplitBreakdown`. The platform line reads "unknown" (not $0) when the hook wasn't given the sale amount. |
109
+ - [Configuration](docs/configuration.md), environment variables and API versions.
110
+ - [Client API](docs/client-api.md), server methods and recovery workflows.
111
+ - [Webhooks and triggers](docs/webhooks.md), event setup and transactional callbacks.
112
+ - [React API](docs/react-api.md) and [workflow examples](docs/react-workflows.md).
113
+ - [Marketplace economics](docs/marketplace.md) and [settlement and payouts](docs/settlement.md).
114
+ - [Migration guide](MIGRATION.md) and [release handoff](docs/release-handoff.md).
1479
115
 
1480
- ### Disputes (headless)
116
+ The [example app](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md)
117
+ demonstrates customer, seller, affiliate, and admin flows, including several checkout
118
+ integration styles.
1481
119
 
1482
- The app-owned alternative to [Embedded Disputes](#embedded-disputes-stripe-connect) below — build a custom dispute UI on the read hooks and these components instead of Stripe's hosted ConnectJS components.
120
+ ## Contributing
1483
121
 
1484
- | Component | Description |
1485
- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1486
- | `DisputesList` | Sorted-by-deadline dispute list (soonest evidence due-by first, no-deadline last), fed by `useDisputes` |
1487
- | `DisputeDetail` | Amount, reason, status, evidence-due countdown, and linked transfers for one dispute, fed by `useDisputeWithCountdown` |
1488
- | `EvidenceUpload` | Since 0.14.0: unstyled file-selection, pending, failure and retry control with render props; bind `onUpload(file)` to an authenticated server adapter that attaches to a draft |
1489
- | `EvidenceForm` | Plain-language evidence form (product description, access activity, additional info, customer communication) that maps through `buildDisputeEvidence` before calling an app-wired `onUpdateDispute`; `stage()` saves a draft, `submit()` finalizes |
1490
-
1491
- ### Embedded Disputes (Stripe Connect)
1492
-
1493
- The Stripe-hosted alternative to the headless dispute components: each seller
1494
- views and responds to their own disputes via Stripe's embedded `disputes_list`
1495
- / `payment_disputes` components, driven by the Account Session that
1496
- `createDisputeSession` creates.
1497
-
1498
- | Component | Description |
1499
- | ------------------ | ----------------------------------------------------------------------------------------------- |
1500
- | `ConnectProvider` | Initializes ConnectJS with your publishable key + an account-session fetcher |
1501
- | `EmbeddedDisputes` | Mounts the embedded `disputes_list` (or `payment_disputes` when scoped via `payment`) component |
1502
-
1503
- **Dependencies:** the wrapper uses [`@stripe/react-connect-js`](https://www.npmjs.com/package/@stripe/react-connect-js) and [`@stripe/connect-js`](https://www.npmjs.com/package/@stripe/connect-js), which ship as regular dependencies of this package (same convention as `@stripe/react-stripe-js` / `@stripe/stripe-js`) -- no extra install step. ConnectJS components are client-only iframes; render them in client components.
1504
-
1505
- ```tsx
1506
- // convex/stripe.ts — expose the account session (server side)
1507
- export const createDisputeSession = action({
1508
- args: { stripeAccountId: v.string() },
1509
- handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
1510
- });
1511
-
1512
- // Seller disputes page (client side)
1513
- import {
1514
- ConnectProvider,
1515
- EmbeddedDisputes,
1516
- } from "@fantastic.dev/better-stripe/react";
1517
-
1518
- function SellerDisputes({ stripeAccountId }: { stripeAccountId: string }) {
1519
- const createSession = useAction(api.stripe.createDisputeSession);
1520
- return (
1521
- <ConnectProvider
1522
- publishableKey={import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY}
1523
- fetchClientSecret={async () =>
1524
- (await createSession({ stripeAccountId })).clientSecret
1525
- }
1526
- >
1527
- <EmbeddedDisputes />
1528
- </ConnectProvider>
1529
- );
1530
- }
1531
- ```
1532
-
1533
- ## Testing Utilities
1534
-
1535
- Import from `@fantastic.dev/better-stripe/testing`.
1536
-
1537
- ### assertTestEnvironment
1538
-
1539
- Guards against running test fixtures with live Stripe keys:
1540
-
1541
- ```typescript
1542
- import { assertTestEnvironment } from "@fantastic.dev/better-stripe/testing";
1543
-
1544
- assertTestEnvironment(); // Throws if STRIPE_SECRET_KEY does not start with sk_test_
1545
- ```
1546
-
1547
- ### Fixture Factories
1548
-
1549
- Typed factories for creating Stripe test data:
1550
-
1551
- ```typescript
1552
- import {
1553
- createTestAccount,
1554
- createTestPrice,
1555
- createTestProduct,
1556
- createTestSubscription,
1557
- } from "@fantastic.dev/better-stripe/testing";
1558
-
1559
- const account = await createTestAccount(stripe, { email: "test@example.com" });
1560
- const product = await createTestProduct(stripe, { name: "Pro Plan" });
1561
- const price = await createTestPrice(stripe, {
1562
- productId: product.id,
1563
- unitAmount: 2999,
1564
- interval: "month",
1565
- });
1566
- ```
1567
-
1568
- ### Mock Webhook Events
1569
-
1570
- Factories for creating mock webhook events in tests:
1571
-
1572
- ```typescript
1573
- import {
1574
- mockAccountUpdated,
1575
- mockCheckoutCompleted,
1576
- mockInvoicePaid,
1577
- mockSubscriptionUpdated,
1578
- } from "@fantastic.dev/better-stripe/testing";
1579
-
1580
- const event = mockCheckoutCompleted({
1581
- stripeSessionId: "cs_test_123",
1582
- metadata: { userId: "user_abc" },
1583
- });
1584
- ```
1585
-
1586
- ## Configuration
1587
-
1588
- ### Environment Variables
1589
-
1590
- | Variable | Required | Read by | Description |
1591
- | -------------------------- | ----------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1592
- | `STRIPE_SECRET_KEY` | Yes | Component | Declared in the component's `convex.config.ts` (required) and read by the component (e.g. `getStripeMode`). Also passed explicitly via the `BetterStripe` constructor and `registerRoutes`. The installing app must wire it to the component — see below. |
1593
- | `STRIPE_WEBHOOK_SECRET` | Yes | App | Signing secret for the V1 snapshot event destination. Read by `registerRoutes` in the app, not the component. |
1594
- | `STRIPE_WEBHOOK_SECRET_V2` | No\* | App | Signing secret for the V2 thin event destination (Connect account events). \*Required whenever your V2 destination has its own secret (the usual case); falls back to `STRIPE_WEBHOOK_SECRET` if unset. |
1595
- | `STRIPE_PUBLISHABLE_KEY` | Yes (React) | Frontend | A public, frontend-only key. Supply it from the frontend's own env (`VITE_STRIPE_PUBLISHABLE_KEY` / `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`) and pass it as the `publishableKey` prop to the React components. It is **not** a component env var. |
1596
-
1597
- ### Wiring component env vars
1598
-
1599
- The component declares `STRIPE_SECRET_KEY` as a required environment variable in
1600
- its `convex.config.ts`. Convex isolates a component's functions from the
1601
- deployment's `process.env`, so setting the var with `convex env set` is **not**
1602
- enough on its own — the installing app must provide it to the component via
1603
- `app.use`:
1604
-
1605
- ```ts
1606
- // convex/convex.config.ts
1607
- import { defineApp } from "convex/server";
1608
- import { v } from "convex/values";
1609
- import betterStripe from "@fantastic.dev/better-stripe/convex.config";
1610
-
1611
- const app = defineApp({
1612
- env: { STRIPE_SECRET_KEY: v.string() },
1613
- });
1614
- // Pass by reference so the component always sees the deployment's current value
1615
- // (set via `convex env set STRIPE_SECRET_KEY ...`).
1616
- app.use(betterStripe, {
1617
- env: { STRIPE_SECRET_KEY: app.env.STRIPE_SECRET_KEY },
1618
- });
1619
- export default app;
1620
- ```
1621
-
1622
- The webhook secrets (`STRIPE_WEBHOOK_SECRET`, `STRIPE_WEBHOOK_SECRET_V2`) are read
1623
- by the app's `registerRoutes`, not the component, so they only need to be set in
1624
- the deployment env — no `app.use` wiring required.
1625
-
1626
- ### Stripe API Version
1627
-
1628
- The component pins the Stripe API version internally (`2026-09-30.endive`) using the installed stripe-node 23 SDK's exact API-version type. Upgrading the pinned version requires a package release and changelog entry. Apps do not need to set `STRIPE_API_VERSION`. See [the migration notes](MIGRATION.md) for removing Dojo's fulfillment-retry patch and upgrading webhook payload versions separately.
1629
-
1630
- ### SDK Management
1631
-
1632
- The component owns the Stripe SDK instance internally via a keyed client cache (keyed by API key). Apps pass `STRIPE_SECRET_KEY`; the component handles versioning and client lifecycle. Apps should not create their own Stripe SDK instances for operations that go through the component.
1633
-
1634
- ## Architecture
1635
-
1636
- ### Component-Owned Tables
1637
-
1638
- The component manages 8 domain tables and 1 internal table:
1639
-
1640
- | Table | Description |
1641
- | ------------------ | -------------------------------------------------------- |
1642
- | `accounts` | V2 account records with identity and configuration state |
1643
- | `products` | Stripe products with optional trial day management |
1644
- | `prices` | Stripe prices linked to products |
1645
- | `subscriptions` | Subscription lifecycle with first-class trial tracking |
1646
- | `checkoutSessions` | Checkout session state (embedded and redirect) |
1647
- | `invoices` | Invoice records with subscription metadata |
1648
- | `payments` | Payment intent records |
1649
- | `payouts` | Payout records for Connect/marketplace |
1650
- | `webhookEvents` | Internal ledger for replay protection and observability |
1651
-
1652
- ### App-Layer Tables
1653
-
1654
- The consuming app maintains its own tables for business context. The component never reads or writes app tables directly. App tables are updated via sync triggers that run in the same transaction as component writes.
1655
-
1656
- Example app-layer tables (from a typical integration):
1657
-
1658
- - Linking products to app-specific entities (e.g., communities, teams)
1659
- - Linking subscriptions to app-specific purchase types
1660
- - Payout percentage configurations
1661
-
1662
- ### Trigger Flow
1663
-
1664
- ```
1665
- Stripe Webhook Event
1666
- |
1667
- v
1668
- Webhook handler: Verify signature + check ledger
1669
- |
1670
- v
1671
- syncWebhook (one mutation transaction)
1672
- - Upsert component domain table
1673
- - Run sync trigger --> App updates its own tables
1674
- | Throwing rolls back the upsert;
1675
- | Stripe retries and the failed
1676
- | ledger row is reprocessed
1677
- v
1678
- Mark ledger row processed
1679
- |
1680
- v
1681
- Async hook (scheduled action) --> App calls external APIs
1682
- Failures do not roll back;
1683
- hooks should be idempotent
1684
- ```
1685
-
1686
- ### Package Entry Points
1687
-
1688
- | Entry Point | Contents |
1689
- | -------------------------------------------- | -------------------------------------------------------- |
1690
- | `@fantastic.dev/better-stripe` | `BetterStripe` class, `registerRoutes`, TypeScript types |
1691
- | `@fantastic.dev/better-stripe/react` | React hooks, headless UI components, formatting helpers |
1692
- | `@fantastic.dev/better-stripe/testing` | Test fixtures, mock webhooks, `assertTestEnvironment` |
1693
- | `@fantastic.dev/better-stripe/convex.config` | Convex component registration |
1694
-
1695
- ### Error Handling
1696
-
1697
- Structured errors are thrown as `ConvexError` with a `BetterStripeError` payload:
1698
-
1699
- ```typescript
1700
- interface BetterStripeError {
1701
- code: BetterStripeErrorCode;
1702
- message: string;
1703
- stripeError?: {
1704
- type: string;
1705
- code?: string;
1706
- message: string;
1707
- };
1708
- }
1709
- ```
1710
-
1711
- Error codes: `ACCOUNT_NOT_FOUND`, `ACCOUNT_CREATE_FAILED`, `PRODUCT_NOT_FOUND`, `PRICE_NOT_FOUND`, `SUBSCRIPTION_NOT_FOUND`, `SUBSCRIPTION_UPDATE_FAILED`, `CHECKOUT_CREATE_FAILED`, `CHECKOUT_NOT_FOUND`, `PAYMENT_METHOD_FAILED`, `WEBHOOK_VERIFICATION_FAILED`, `WEBHOOK_DUPLICATE_EVENT`, `STRIPE_API_ERROR`, `TEST_ENV_REQUIRED`, `INVALID_CONFIGURATION`.
1712
-
1713
- > **Note:** All methods that throw their own errors or catch-and-rethrow now use structured `ConvexError(BetterStripeError)` payloads. Methods that let uncaught Stripe SDK errors propagate are a separate policy decision and not yet aligned.
1714
-
1715
- ## Resources
1716
-
1717
- - [Stripe V2 Accounts API](https://docs.stripe.com/connect/accounts-v2/api)
1718
- - [Stripe Embedded Checkout](https://docs.stripe.com/payments/checkout/custom)
1719
- - [Convex Component Authoring](https://docs.convex.dev/components/authoring)
1720
- - [Stripe Webhook Event Reference](https://docs.stripe.com/api/events/types)
1721
- - [Stripe Testing Guide](https://docs.stripe.com/testing)
1722
- - [Example checkout tests](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md#test-the-integration-examples), including successful payments, declines, insufficient funds, and 3D Secure
122
+ See the [development guide](docs/development.md) for local setup and code generation,
123
+ [testing utilities](docs/testing.md) for fixtures, and the [release guide](docs/releasing.md)
124
+ for publishing. Run `pnpm run check:all` before submitting changes.
1723
125
 
1724
126
  ## License
1725
127
 
1726
128
  MIT
1727
-
1728
- ## Verified settlement and payout APIs
1729
-
1730
- `getVerifiedSale`, `allocateSale`, `selectCommissionInvoice`, and `settleSale`
1731
- provide verified fees, fee-first allocations, durable subscription commission
1732
- terms, and recoverable execution through the component's existing transfer ledger.
1733
- `getPayoutSnapshot` supplies per-currency balances, real cursor history, and
1734
- explicitly bounded upcoming payout data. See [settlement and payout contracts](docs/settlement.md)
1735
- for authorization, recovery, migration, and provider limitations.
1736
-
1737
- Account creation (`createAccount`, `getOrCreateAccount`, `ensureCustomerAccount`),
1738
- `createCheckoutSession`, `createProduct`, and `createPrice` accept an optional `idempotencyKey`. Use one stable
1739
- account-creation key per logical account and a distinct key per checkout order.
1740
- For catalog edits, persist a request key for the logical product or immutable
1741
- price version. Retry identical parameters with the same key after a provider or
1742
- component persistence failure. Use a new key when the price amount or other
1743
- creation parameters change. Creating a new Price does not migrate existing
1744
- subscriptions; they retain their prior price until the host explicitly changes
1745
- them. Never reuse a version key for different parameters.
1746
-
1747
- React `Checkout` preserves its request ID through retries; your server must
1748
- forward that identity as the SDK request option. Persist it in the host order
1749
- for recovery across reloads. Omission retains the previous SDK behavior.
1750
-
1751
- Keys must be nonempty, at most 255 characters, and contain no sensitive data.
1752
- Reuse a key only with identical parameters. Stripe v1 Checkout keys can be pruned
1753
- after 24 hours; Accounts v2 deduplicates within 30 days. Maintain durable order and
1754
- account mappings beyond those windows, and reconcile ambiguous provider results
1755
- before retrying an expired key. See [v1 idempotency](https://docs.stripe.com/api/idempotent_requests)
1756
- and [v2 request semantics](https://docs.stripe.com/api-v2-overview).
1757
-
1758
- `getCheckoutSessionFromStripe`, `getSubscriptionFromStripe`, and `getCouponFromStripe` read
1759
- current provider objects rather than cached component records. They are server
1760
- APIs: authorize each resource and return only the fields your browser needs.
1761
- Subscription upserts accept Stripe's `incomplete_expired` terminal status.
1762
-
1763
- ### One-time intents and saved-card setup
1764
-
1765
- `createPaymentIntent(ctx, { userId, customerAccount?, stripePriceId,
1766
- idempotencyKey, receiptEmail?, metadata? })` creates a card-only, platform
1767
- PaymentIntent by default. Set `paymentMethods: "automatic"` to let Stripe select
1768
- compatible methods, as in the example. It retrieves the platform price and expanded product from Stripe,
1769
- rejects inactive products/prices, recurring and nonpositive/nonfixed prices, and
1770
- derives amount and currency from the provider price. It returns only
1771
- `{ paymentIntentId, clientSecret }`. Omit `customerAccount` for a host-authorized
1772
- guest purchase. Existing Checkout Sessions integrations remain available.
1773
-
1774
- `createSetupIntent(ctx, { userId, customerAccount, usage, consent: true,
1775
- idempotencyKey, metadata? })` provisions a card-only SetupIntent for a V2 customer
1776
- account, returning only `{ setupIntentId, clientSecret }`. Explicitly choose
1777
- `on_session` or `off_session` and record consent to that usage before provisioning.
1778
- Confirmation attaches the saved card after required authentication; it does not
1779
- set a subscription default. `SaveCard` from the React entrypoint supplies an
1780
- unstyled Payment Element workflow. See the [React guide](docs/react-workflows.md#save-a-card-through-setupintent-confirmation).
1781
-
1782
- Both APIs require caller idempotency keys. Persist logical request identity and
1783
- immutable inputs on the server, bind keys to the authenticated customer and
1784
- operation, and reuse the same key on retries. Stripe's bounded idempotency window
1785
- is not a durable order store. Authenticate in the host adapter, authorize the
1786
- selected price/product and customer, and supply server-selected metadata. The
1787
- package checks a supplied customer account's persisted `userId` ownership,
1788
- protects its own attribution keys and strips the reserved `bs*` namespace. Never
1789
- accept browser-provided amounts, user IDs or metadata as authorization.
1790
-
1791
- Grant paid access only after the existing verified webhook/settlement flow.
1792
- Creation and browser confirmation are not settlement proof. Customer-account
1793
- operations require Accounts v2 support in the sandbox or merchant account; the
1794
- [customer preview guide](docs/accounts-v2-preview.md) explains eligibility.
1795
-
1796
- #### Live sandbox verification, 2026-10-15
1797
-
1798
- The public intent APIs and `SaveCard` passed real Stripe test-mode verification
1799
- at commit `332d49c`, merged in [PR #166](https://github.com/FantasticDevHQ/better-stripe/pull/166).
1800
- Browser 3DS failure, retry on the same SetupIntent, and successful authentication
1801
- passed. A card saved for `off_session` use then succeeded on a later PaymentIntent;
1802
- all successful test payments were refunded. Provider checks also covered customer
1803
- ownership, redisplay permission, idempotent retries and declines.
1804
-
1805
- The initial `non_connect_platform_accounts_v2_access_blocked` error was resolved
1806
- by enabling Connect in the intended Connect test sandbox. The browser flow used
1807
- `2026-09-30.endive`; separate API checks also passed on `2026-09-30.preview`.
1808
- This does not establish customer-only preview eligibility for another account.
1809
- See the [sandbox setup findings](docs/accounts-v2-preview.md#connect-sandbox-setup-findings-2026-10-15),
1810
- [authentication and reuse results](docs/react-workflows.md#live-authentication-and-reuse-results-2026-10-15),
1811
- and [uploaded screenshots and provider records](https://github.com/FantasticDevHQ/better-stripe/pull/166#issuecomment-6185124292).
1812
-
1813
- ## Component history and currency summaries
1814
-
1815
- See the [read contract guide](docs/read-contracts.md) for reactive product, price and payout
1816
- cursors, exact currency summaries, legacy backfill, payout failure details, and
1817
- published-version adoption requirements.
1818
-
1819
- For buyer purchase-history discovery, use the public invoice and
1820
- [Checkout-session page readers](docs/checkout-session-pages.md). Checkout pages
1821
- also reveal open/asynchronous sessions with no invoice. They preserve raw
1822
- references and require host authorization, continuation checkpoints and
1823
- historical reconciliation; they do not attest complete history or award credit.
1824
-
1825
- Custom recipient payout minimums are waived during the final day before the verified holding deadline. Provider limits and all financial checks still apply. See [settlement and deadline handling](docs/settlement.md) for worker cadence, retries and expiry limitations.
1826
-
1827
- Holding-expiry recovery remains visible and retryable after schedule restoration. The package preserves unresolved provider balances and payout claims, and prevents reset or custom reactivation from erasing them. See [expiry recovery](docs/settlement.md) for operator handling.
1828
-
1829
- Automatic payout status is reusable through `payoutAttemptStatus`, `payoutAttemptValidator`, and the React `PayoutAttemptStatus` workflow. Rejection reasons and retry times remain separate from eligibility previews and bank arrival dates. See [React workflow guidance](docs/react-workflows.md).
1830
-
1831
- Payout qualification renews source verification for the selected currency only after a complete matching provider-history check. Slower receipt scans retain the same freshness and local reservation safeguards; partial or changed history stays held. See [settlement guidance](docs/settlement.md).
1832
-
1833
- Automatic combined payouts use a complete paginated ledger collection above 100 historical sources or claims. The collection is checked and bound to the immutable claim before Stripe is contacted; incomplete scans resume without authorizing money. See [settlement guidance](docs/settlement.md#resumable-local-collections).
1834
-
1835
- Resolve recovery-backed payout liabilities with `stripe.costRecovery.payoutQuote(ctx, authorizedScope)` and pass its amount/version together to preview or automatic release. The example does this for seller refund/dispute costs; stale or missing required versions fail safely. See [versioned liability guidance](docs/settlement.md#versioned-recovery-liabilities).
1836
-
1837
- Historical payout adoption and funded-account activation also use complete paginated collections beyond the small direct snapshot path. They revalidate complete financial membership atomically, preserve paid principal and holding age, and reject stale funding or recovery changes. See [historical import guidance](docs/settlement.md#historical-import-and-funded-activation).
1838
-
1839
- ## Metered usage
1840
-
1841
- Metered billing is under investigation. See the [provider comparison and sandbox acceptance matrix](docs/metered-usage.md) for current status and integration requirements. Public usage APIs are not available yet.