@fantastic.dev/better-stripe 0.67.1 → 0.68.1

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/MIGRATION.md +1 -1
  3. package/README.md +12 -12
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  6. package/dist/client/index.d.ts +1 -0
  7. package/dist/client/index.d.ts.map +1 -1
  8. package/dist/client/index.js.map +1 -1
  9. package/dist/client/products/catalogClient.d.ts +7 -0
  10. package/dist/client/products/catalogClient.d.ts.map +1 -1
  11. package/dist/client/products/catalogClient.js +7 -0
  12. package/dist/client/products/catalogClient.js.map +1 -1
  13. package/dist/client/products/identity.d.ts +26 -0
  14. package/dist/client/products/identity.d.ts.map +1 -0
  15. package/dist/client/products/identity.js +8 -0
  16. package/dist/client/products/identity.js.map +1 -0
  17. package/dist/client/usage/observationClient.d.ts +2 -2
  18. package/dist/client/usage/observationClient.d.ts.map +1 -1
  19. package/dist/component/_generated/component.d.ts +43 -0
  20. package/dist/component/_generated/component.d.ts.map +1 -1
  21. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  22. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  23. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  24. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  25. package/dist/component/products/queries.d.ts +49 -0
  26. package/dist/component/products/queries.d.ts.map +1 -1
  27. package/dist/component/products/queries.js +32 -0
  28. package/dist/component/products/queries.js.map +1 -1
  29. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  30. package/docs/README.md +18 -32
  31. package/docs/architecture.md +40 -21
  32. package/docs/client-api.md +25 -3
  33. package/docs/configuration.md +36 -8
  34. package/docs/development.md +25 -5
  35. package/docs/marketplace.md +34 -10
  36. package/docs/overview.md +14 -3
  37. package/docs/react-api.md +18 -9
  38. package/docs/read-contracts.md +34 -0
  39. package/docs/testing.md +29 -4
  40. package/docs/usage-observations.md +5 -2
  41. package/docs/webhooks.md +45 -7
  42. package/package.json +15 -60
  43. package/src/client/index.ts +4 -0
  44. package/src/client/products/catalogClient.ts +15 -0
  45. package/src/client/products/identity.test.ts +91 -0
  46. package/src/client/products/identity.ts +36 -0
  47. package/src/component/_generated/component.ts +47 -0
  48. package/src/component/products/identity.test.ts +217 -0
  49. package/src/component/products/queries.ts +42 -0
@@ -2,12 +2,12 @@
2
2
 
3
3
  ### Environment Variables
4
4
 
5
- | Variable | Required | Read by | Description |
6
- | -------------------------- | ----------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
7
- | `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. |
8
- | `STRIPE_WEBHOOK_SECRET` | Yes | App | Signing secret for the V1 snapshot event destination. Read by `registerRoutes` in the app, not the component. |
9
- | `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. |
10
- | `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. |
5
+ | Variable | Required | Read by | Description |
6
+ | -------------------------- | ----------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
7
+ | `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. |
8
+ | `STRIPE_WEBHOOK_SECRET` | Yes | App | Signing secret for the V1 snapshot event destination. Read by `registerRoutes` in the app, not the component. |
9
+ | `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. |
10
+ | `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. The component also accepts it optionally through `app.use` for `stripe.getPublishableKey`; frontend props still need the public key explicitly. |
11
11
 
12
12
  ### Wiring component env vars
13
13
 
@@ -40,11 +40,39 @@ the deployment env — no `app.use` wiring required.
40
40
 
41
41
  ### Stripe API Version
42
42
 
43
- 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.
43
+ The default API version is `2026-09-30.endive`. The supported customer-only
44
+ Accounts v2 opt-in is `STRIPE_CUSTOMER_PREVIEW_API_VERSION`, currently
45
+ `2026-09-30.preview`. Other values are rejected. This is a constructor option,
46
+ not a `STRIPE_API_VERSION` environment variable. Account eligibility and request
47
+ version are separate requirements; read [Accounts v2 setup](accounts-v2-preview.md).
48
+
49
+ ```ts
50
+ import {
51
+ BetterStripe,
52
+ STRIPE_CUSTOMER_PREVIEW_API_VERSION,
53
+ } from "@fantastic.dev/better-stripe";
54
+ import { components } from "./_generated/api";
55
+
56
+ export const stripe = new BetterStripe(components.betterStripe, {
57
+ STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
58
+ // Omit for the default Connect/GA integration.
59
+ stripeApiVersion: STRIPE_CUSTOMER_PREVIEW_API_VERSION,
60
+ });
61
+ ```
62
+
63
+ Use `stripe.registerRoutes(http, config)` to inherit this client's key/version,
64
+ or pass the same `stripeApiVersion` explicitly to standalone `registerRoutes`.
65
+ Pin snapshot event destinations to the matching version. Changing package
66
+ defaults follows the release process; upgrading a client does not migrate existing
67
+ provider destinations. See [migration notes](../MIGRATION.md).
44
68
 
45
69
  ### SDK Management
46
70
 
47
- 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.
71
+ The package manages Stripe clients for its public operations. The shared client
72
+ cache is keyed by API key and supported API version. Durable provider adapters
73
+ can create isolated clients with their own retry policy. Pass credentials through
74
+ the documented constructor or internal provider-action boundary; do not journal
75
+ secrets or duplicate the package's Stripe operations in host code.
48
76
 
49
77
  ## TypeScript setup
50
78
 
@@ -2,9 +2,14 @@
2
2
 
3
3
  ### Development toolchain
4
4
 
5
- Install with `pnpm install` from the repository root, then run `pnpm build`
6
- and `pnpm dev` to start the example at http://localhost:5173. The example needs
7
- Node.js 22.12+ and a configured Convex development deployment; see
5
+ Use Node.js 24, as CI does, and the pinned pnpm version in `package.json`.
6
+ The package supports Node.js 20+, but the Vite example requires Node.js 22.12+.
7
+ From the repository root, run `pnpm install --frozen-lockfile` and
8
+ `pnpm run build:clean`. After configuring the example's existing Convex development
9
+ deployment, `pnpm dev` starts its backend watcher and Vite frontend. Use the
10
+ localhost URL Vite prints, normally http://localhost:5173. For a frontend-only
11
+ server against an already deployed backend, run `pnpm run dev:frontend` from
12
+ `example/`. See
8
13
  [the example setup guide](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md).
9
14
 
10
15
  The BetterStripe example separates visitor, customer, affiliate, seller, and
@@ -37,7 +42,8 @@ See [affiliate configuration and testing](https://github.com/FantasticDevHQ/bett
37
42
 
38
43
  The public React exports include `AffiliatePayoutEditor`, `PlanPricingEditor`,
39
44
  `Pagination`, and `useCursorPagination`. The example supplies styling through
40
- render props; its backend owns authorization, rule inheritance, and transfers.
45
+ render props; its backend owns authorization and rule inheritance. The package owns durable
46
+ transfer execution, retained financial records and provider reconciliation.
41
47
  See [the workflow reference](react-workflows.md#percentage-or-fixed-affiliate-payouts)
42
48
  and [the UI reuse audit](react-workflows-audit.md).
43
49
 
@@ -46,6 +52,14 @@ formatting, typechecks, codegen drift check, tests, and repository quality gates
46
52
  used by CI. Policy lives in `repo-gates.config.json`; measured baselines live in
47
53
  `gates/`. Fix failures without weakening the gates or raising existing budgets.
48
54
 
55
+ Use `pnpm run check:package` to clean/rebuild the package and run the artifact
56
+ checks in one command. It verifies public documentation imports and local links,
57
+ recursively linked guides in the actual tarball, and extracted usage consumers
58
+ for public types, runtime accounting and React rendering. It uses deterministic
59
+ fixtures without provider credentials or deployment changes. Native component
60
+ analysis remains a separate authorized development probe in
61
+ [the usage handoff evidence](https://github.com/FantasticDevHQ/better-stripe/tree/main/docs/evidence/usage-handoff).
62
+
49
63
  Coverage checks enforce the committed floors in `gates/coverage-budgets.json`.
50
64
  `pnpm run check:coverage` and `pnpm run check:all` never edit that file or fail
51
65
  because coverage improved. Ordinary feature PRs should leave the budget file alone.
@@ -104,7 +118,13 @@ pnpm codegen:lib # regen src/component/_generated only
104
118
  pnpm codegen:example # regen example/convex/_generated only
105
119
  ```
106
120
 
107
- 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.
121
+ All three require a configured dev deployment, normally selected by a prior
122
+ `pnpm exec convex dev` from `example/`. They generate local bindings and, for
123
+ components, upload and analyze definitions against the selected development
124
+ deployment. Codegen does not replace its serving application or run a data
125
+ migration; deploying updated handlers still requires `convex dev` or
126
+ `convex dev --once` from `example/`. Keep secrets and deployment-key overrides
127
+ out of the wrong terminal. See [safe development selection](metering-setup.md#run-the-repository-example).
108
128
 
109
129
  **CI gate.** Two layers verify the committed files are not stale:
110
130
 
@@ -1,6 +1,6 @@
1
1
  # Marketplace economics
2
2
 
3
- 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).
3
+ 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. Amounts use the currency's minor units, cents for USD. Do not assume two decimal places for every currency.
4
4
 
5
5
  ### Fee Model
6
6
 
@@ -30,9 +30,19 @@ const { feeAmount, percentApplied, fixedApplied, tier } = computeFee(2999, {
30
30
 
31
31
  **How the fee is charged** depends on shape and charge type:
32
32
 
33
- - **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.
34
- - **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`.
35
- - For synchronously finalized first invoices, `invoice.paid` collects the missed fixed/tiered fee through a partial destination-transfer reversal. See [first-invoice fee handling](overview.md#roadmap--known-gaps).
33
+ - Percent-only subscription fees use `application_fee_percent`.
34
+ - A one-time destination charge with a known amount computes
35
+ `application_fee_amount` before confirmation, including percent-only rates.
36
+ - Fixed/tiered subscription fees are computed on draft `invoice.created` and set
37
+ as `application_fee_amount`. A synchronously finalized first invoice misses
38
+ that draft window; `invoice.paid` collects its fee through a retained partial
39
+ destination-transfer reversal.
40
+ - A deferred one-time fee cannot be attached to a succeeded PaymentIntent as
41
+ `application_fee_amount`. The webhook processor collects it through a partial
42
+ reversal of the original destination transfer with retained recovery evidence.
43
+
44
+ See [first-invoice fee handling](overview.md#roadmap--known-gaps) for replay
45
+ and duplicate-collection guards.
36
46
 
37
47
  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).
38
48
 
@@ -86,7 +96,13 @@ const result = computeSplit(10000, { percent: 10 }, [
86
96
 
87
97
  ### Payouts
88
98
 
89
- 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-api.md#react-hooks) and [React Components](react-api.md#react-components).
99
+ Stripe-managed automatic payouts are the default. `listPayouts` reads history
100
+ and `createPayout` submits an authorized payout. The package also supports
101
+ explicit recipient-held custom policies, verified manual schedule changes and
102
+ automatic workers. Those require consent, source/recovery verification and
103
+ the [payout policy controls](settlement.md#recipient-held-payout-policy-controls).
104
+ The presentational `PayoutSchedule` component shows a supplied balance and next
105
+ payout; that component offers no withdrawal command. See [React workflows](react-workflows.md#payout-settings).
90
106
 
91
107
  ### Disputes
92
108
 
@@ -94,21 +110,29 @@ The platform is merchant of record, so a chargeback lands on the platform's Stri
94
110
 
95
111
  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.
96
112
  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](affiliate-clawbacks.md#verification-evidence).
97
- 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").
113
+ 3. **Auto-cancel** — on dispute open, the disputed subscription (resolved PaymentIntent → invoice → subscription) is canceled by default (`registerRoutes`'s `autoCancelOnDispute`, default `true`; pairs with `cancelDisputedSubscriptionImmediately`, default `false` → cancel-at-period-end, matching the Skool model of "cancel now, remove access at cycle end").
98
114
 
99
115
  Sellers respond to their own disputes without platform staff involvement, via an embedded Stripe Connect session:
100
116
 
101
117
  ```typescript
102
- // server: expose the account session
118
+ // Host helper authenticates ctx.auth and authorizes the original seller account.
103
119
  export const createDisputeSession = action({
104
- args: { stripeAccountId: v.string() },
105
- handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
120
+ args: {},
121
+ handler: async (ctx) => {
122
+ const stripeAccountId = await requireAuthorizedSellerAccount(ctx);
123
+ return stripe.createDisputeSession(ctx, { stripeAccountId });
124
+ },
106
125
  });
107
126
  ```
108
127
 
109
128
  `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](react-api.md#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-api.md#react-components)).
110
129
 
111
- `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.
130
+ `stripe.reverseTransfers(ctx, { sourceChargeId, percent?, amount?, operationId? })`
131
+ exposes the existing reversal primitive. Supply a stable, server-derived
132
+ `operationId` to retain original slices and idempotency keys across retries.
133
+ Without it the call is a one-shot reversal with no idempotency protection; an
134
+ uncertain outcome must not be blindly retried. Authorize the original charge,
135
+ amount and recovery policy before invoking it.
112
136
 
113
137
  For commissions tracked by the recovery ledger, generic manual reversal is
114
138
  rejected. Use `createRefund` for a real refund or `stripe.affiliateRecovery.retry`
package/docs/overview.md CHANGED
@@ -3,8 +3,8 @@
3
3
  ## Features
4
4
 
5
5
  - **V2 Accounts API** -- Account creation, onboarding, Connect/marketplace, merchant and recipient configurations
6
- - **Products and Prices** -- Full CRUD with trial day management as a first-class feature
7
- - **Checkout** -- Both embedded (custom UI mode) and redirect checkout session creation
6
+ - **Products and Prices** -- Creation, reads, updates and deactivation, with product trial-day defaults
7
+ - **Checkout** -- Checkout Sessions with redirect, embedded, custom Elements and preview form modes; React also supports the separate PaymentIntent flow
8
8
  - **Subscriptions** -- Lifecycle management including cancel, reactivate, quantity updates, and trial tracking
9
9
  - **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
10
10
  - **Split engine** -- Single-recipient destination charges or multi-recipient separate-charges-and-transfers (store + affiliate(s)), computed and executed by the webhook engine
@@ -128,7 +128,18 @@ Historical payout adoption and funded-account activation also use complete pagin
128
128
 
129
129
  ## Metered usage
130
130
 
131
- Metered billing is under investigation. See the [provider comparison and sandbox acceptance matrix](metered-usage.md) for current status and integration requirements. Public usage APIs are not available yet.
131
+ Native Stripe metered billing supports pay as you go, included monthly units with
132
+ overages, and payment-backed prepaid credits through `stripe.usage`. The package
133
+ owns scoped atomic recording, reservations, durable delivery, reconciliation,
134
+ allowance/credit accounting, corrections and original-payment settlement.
135
+ Hosts authorize billable work and choose units, prices and policies.
136
+
137
+ Start with [sandbox setup](metering-setup.md) and [public model recipes](metered-usage.md).
138
+ The [example walkthrough](usage-example.md) demonstrates all three models using
139
+ the package's [reusable React workflows](usage-react.md) and
140
+ [configuration UI](usage-configuration.md). See [verification and limits](usage-verification.md)
141
+ for actual native evidence and [opt-in rollout](usage-rollout.md) for adoption,
142
+ drain, model transitions and rollback. Metronome is not required.
132
143
 
133
144
  ## Resources
134
145
 
package/docs/react-api.md CHANGED
@@ -2,7 +2,10 @@
2
2
 
3
3
  ## React Hooks
4
4
 
5
- Import from `@fantastic.dev/better-stripe/react`. All hooks use Convex's `useQuery` and `useMutation` internally.
5
+ Import from `@fantastic.dev/better-stripe/react`. Read factories accept the host's Convex query binding. Command workflows use
6
+ host callbacks, Convex mutations/actions or Stripe.js according to the flow.
7
+ Authenticate and authorize those host endpoints; a React component is not an
8
+ authorization boundary.
6
9
 
7
10
  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.
8
11
 
@@ -226,7 +229,7 @@ currency support. See the [React workflow guide](react-workflows.md).
226
229
 
227
230
  | Component | Description |
228
231
  | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
229
- | `PayoutSchedule` | Recipient balance + next-payout display, fed by a `balance` snapshot and `listPayouts` rows. Payouts are automatic/rolling — no manual-withdrawal action is offered. |
232
+ | `PayoutSchedule` | Recipient balance + next-payout display, fed by a `balance` snapshot and `listPayouts` rows. This display component offers no manual-withdrawal action; the package's separate payout policy and command APIs remain available. |
230
233
  | `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". |
231
234
  | `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. |
232
235
 
@@ -243,6 +246,10 @@ The app-owned alternative to [Embedded Disputes](#embedded-disputes-stripe-conne
243
246
 
244
247
  ### Embedded Disputes (Stripe Connect)
245
248
 
249
+ `createDisputeSession` is a trusted server API. Authenticate the caller and
250
+ resolve/authorize their original seller account before creating an AccountSession.
251
+ Never expose a public action that forwards an arbitrary browser account ID.
252
+
246
253
  The Stripe-hosted alternative to the headless dispute components: each seller
247
254
  views and responds to their own disputes via Stripe's embedded `disputes_list`
248
255
  / `payment_disputes` components, driven by the Account Session that
@@ -256,10 +263,14 @@ views and responds to their own disputes via Stripe's embedded `disputes_list`
256
263
  **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.
257
264
 
258
265
  ```tsx
259
- // convex/stripe.ts — expose the account session (server side)
266
+ // convex/stripe.ts, server side.
267
+ // Implement this helper using ctx.auth and the original seller-account mapping.
260
268
  export const createDisputeSession = action({
261
- args: { stripeAccountId: v.string() },
262
- handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
269
+ args: {},
270
+ handler: async (ctx) => {
271
+ const stripeAccountId = await requireAuthorizedSellerAccount(ctx);
272
+ return stripe.createDisputeSession(ctx, { stripeAccountId });
273
+ },
263
274
  });
264
275
 
265
276
  // Seller disputes page (client side)
@@ -268,14 +279,12 @@ import {
268
279
  EmbeddedDisputes,
269
280
  } from "@fantastic.dev/better-stripe/react";
270
281
 
271
- function SellerDisputes({ stripeAccountId }: { stripeAccountId: string }) {
282
+ function SellerDisputes() {
272
283
  const createSession = useAction(api.stripe.createDisputeSession);
273
284
  return (
274
285
  <ConnectProvider
275
286
  publishableKey={import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY}
276
- fetchClientSecret={async () =>
277
- (await createSession({ stripeAccountId })).clientSecret
278
- }
287
+ fetchClientSecret={async () => (await createSession({})).clientSecret}
279
288
  >
280
289
  <EmbeddedDisputes />
281
290
  </ConnectProvider>
@@ -400,3 +400,37 @@ Omitting the flag or passing `false` retains the legacy first-row behavior and
400
400
  are unchanged. The query performs no provider calls, writes or financial work.
401
401
  Native-generated component references carry the optional boolean; hosts must
402
402
  adopt a normally published, independently verified artifact before using it.
403
+
404
+ ## Bounded product and price identity
405
+
406
+ Use `stripe.getProductIdentity(ctx, { stripeProductId })` and
407
+ `stripe.getPriceIdentity(ctx, { stripePriceId })` when the host needs to reject
408
+ an ambiguous provider-ID mapping. Each reads the existing exact provider-ID
409
+ index with `take(2)` and returns one of:
410
+
411
+ - `{ status: "missing" }` when no cached row matches.
412
+ - `{ status: "unique", product }` or `{ status: "unique", price }` with the
413
+ complete cached row and its actual component `_id`.
414
+ - `{ status: "ambiguous" }` when at least two rows match.
415
+
416
+ These readers never filter active status, account, parent product or metadata
417
+ before counting matches. An inactive or foreign-associated duplicate remains
418
+ ambiguous. They make no provider request and do not repair the cache. An unrelated
419
+ provider ID does not affect the queried identity. Existing
420
+ `getProductByStripeId` and `getPriceByStripeId` retain their first-row behavior
421
+ and return types.
422
+
423
+ The public `ProductIdentityResult` and `PriceIdentityResult` types narrow on
424
+ `status`. A host that requires an exact identity must reject both missing and
425
+ ambiguous results. Unique cache data does not grant permission. Authenticate the
426
+ current actor and validate original source, account ownership, recipient and
427
+ product/price relationships before exposing a reader or authorizing money writes.
428
+ For example, compare the unique price's `productId` with the unique product's
429
+ component `_id`, in addition to the expected provider IDs and currency.
430
+
431
+ The Vite reference's authorized server adapters can use these methods when they
432
+ need strict identity proof. This addition does not migrate its existing catalog
433
+ CRUD or replace its authorization. Dojo's plan-policy consumer must still prove
434
+ the original creator, current paid coverage and registered catalog version,
435
+ using the creator's platform-plan currency. This API does not implement Dojo
436
+ settlement or recurring affiliate terms.
package/docs/testing.md CHANGED
@@ -4,26 +4,36 @@ Import from `@fantastic.dev/better-stripe/testing`.
4
4
 
5
5
  ### assertTestEnvironment
6
6
 
7
- Guards against running test fixtures with live Stripe keys:
7
+ Validate the exact secret used to construct a raw stripe-node client before
8
+ running native fixtures. The helper accepts an explicit key or falls back to
9
+ `process.env.STRIPE_SECRET_KEY`:
8
10
 
9
11
  ```typescript
10
12
  import { assertTestEnvironment } from "@fantastic.dev/better-stripe/testing";
11
13
 
12
- assertTestEnvironment(); // Throws if STRIPE_SECRET_KEY does not start with sk_test_
14
+ assertTestEnvironment(process.env.STRIPE_SECRET_KEY); // Throws for missing/non-test keys.
13
15
  ```
14
16
 
15
17
  ### Fixture Factories
16
18
 
17
- Typed factories for creating Stripe test data:
19
+ Typed factories create Stripe sandbox resources through a raw `Stripe` SDK,
20
+ not a `BetterStripe` instance:
18
21
 
19
22
  ```typescript
23
+ import Stripe from "stripe";
20
24
  import {
25
+ assertTestEnvironment,
21
26
  createTestAccount,
22
27
  createTestPrice,
23
28
  createTestProduct,
24
29
  createTestSubscription,
25
30
  } from "@fantastic.dev/better-stripe/testing";
26
31
 
32
+ const key = process.env.STRIPE_SECRET_KEY;
33
+ if (!key) throw new Error("Sandbox key required");
34
+ assertTestEnvironment(key);
35
+ const stripe = new Stripe(key);
36
+
27
37
  const account = await createTestAccount(stripe, { email: "test@example.com" });
28
38
  const product = await createTestProduct(stripe, { name: "Pro Plan" });
29
39
  const price = await createTestPrice(stripe, {
@@ -33,6 +43,16 @@ const price = await createTestPrice(stripe, {
33
43
  });
34
44
  ```
35
45
 
46
+ Keep the validated key and SDK instance together. The factories' internal guard
47
+ can fall back to the process environment when the SDK does not expose its key;
48
+ it does not independently attest an arbitrary SDK client. Do not pass a different
49
+ client while validating only the environment's test key.
50
+
51
+ These helpers create native Stripe test resources, not component mirror rows.
52
+ `createTestSubscription` takes a classic Stripe Customer ID in `customerId`;
53
+ do not pass an Accounts v2 `acct_...` ID there. Use the configured public
54
+ BetterStripe subscription APIs for Accounts v2 application flows.
55
+
36
56
  ### Mock Webhook Events
37
57
 
38
58
  Factories for creating mock webhook events in tests:
@@ -46,7 +66,12 @@ import {
46
66
  } from "@fantastic.dev/better-stripe/testing";
47
67
 
48
68
  const event = mockCheckoutCompleted({
49
- stripeSessionId: "cs_test_123",
69
+ id: "cs_test_123",
50
70
  metadata: { userId: "user_abc" },
51
71
  });
52
72
  ```
73
+
74
+ `mockAccountUpdated` produces a classic `account.updated` snapshot fixture.
75
+ It is not an Accounts v2 thin-event fixture. Thin-event tests must supply the
76
+ appropriate event reference and mock the original provider lookup separately.
77
+ The factories construct test payloads; they do not sign HTTP webhook requests.
@@ -39,8 +39,11 @@ unavailable estimates. A plan or price change on the same item does not reset
39
39
  the local allowance. Estimates exclude taxes, discounts, fixed
40
40
  fees, rounding and other invoice lines. They are not finalized amounts or limits
41
41
  that authorize work. Strict allowance reservations are implemented separately.
42
- Prepaid balance/estimate fields remain explicitly unavailable until the prepaid
43
- accounting APIs are configured. They never infer available credits from usage.
42
+ The generic usage summary always leaves prepaid estimate/credit fields
43
+ unavailable with `credit_balance_requires_scoped_reader`. Read the original
44
+ binding's `stripe.usage.getCreditBalance` and purchase reconciliation separately;
45
+ see [payment-backed credits](usage-credits.md). A usage summary never infers
46
+ available credits from consumed units, even after a credit account is configured.
44
47
 
45
48
  `read(ctx, {scope, page: {period, limit, cursor}})` returns immutable event history
46
49
  with current delivery state. For an event's delivery audit:
package/docs/webhooks.md CHANGED
@@ -7,9 +7,9 @@
7
7
  Register the webhook endpoint on your Convex HTTP router:
8
8
 
9
9
  ```typescript
10
- import { registerRoutes } from "@fantastic.dev/better-stripe";
10
+ import { stripe } from "./stripe"; // Your configured BetterStripe instance.
11
11
 
12
- registerRoutes(http, components.betterStripe, {
12
+ stripe.registerRoutes(http, {
13
13
  webhookPath: "/stripe/webhook", // Default path
14
14
  stripeSecretKey: process.env.STRIPE_SECRET_KEY,
15
15
  webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
@@ -47,7 +47,15 @@ const v2 = await stripe.setupEventDestination(ctx, {
47
47
  });
48
48
  ```
49
49
 
50
- The method is idempotent — it finds an existing destination matching the URL and payload type, updates its events, or creates a new one.
50
+ The method finds an existing destination matching URL and payload type and
51
+ updates its events, or creates a new one. It rejects incompatible existing
52
+ snapshot versions and customer-preview event scopes instead of silently
53
+ migrating them. Preserve the original destination and signing secret until its
54
+ explicit replacement is configured. See [preview webhook migration](accounts-v2-preview.md).
55
+
56
+ The instance method `stripe.registerRoutes` inherits the configured SDK key and
57
+ API version. Standalone `registerRoutes(http, components.betterStripe, config)`
58
+ remains available; supply the same `stripeApiVersion` explicitly for a preview client.
51
59
 
52
60
  #### Admin UI setup
53
61
 
@@ -57,12 +65,19 @@ The example app includes an `/admin/setup` page that handles webhook creation, e
57
65
 
58
66
  ```typescript
59
67
  import {
60
- BETTER_STRIPE_WEBHOOK_EVENTS, // V1 snapshot events (20 events)
61
- BETTER_STRIPE_V2_WEBHOOK_EVENTS, // V2 thin events (12 events)
62
- ALL_BETTER_STRIPE_EVENTS, // Combined (32 events)
68
+ BETTER_STRIPE_WEBHOOK_EVENTS, // Default V1 snapshot event names
69
+ BETTER_STRIPE_V2_WEBHOOK_EVENTS, // Default Connect V2 thin event names
70
+ ALL_BETTER_STRIPE_EVENTS, // Combined defaults, not every optional event handler
63
71
  } from "@fantastic.dev/better-stripe";
64
72
  ```
65
73
 
74
+ Customer-only preview clients select `BETTER_STRIPE_CUSTOMER_ACCOUNT_EVENTS`
75
+ for their default thin destination instead of the Connect list. Metered billing
76
+ also handles `v1.billing.meter.error_report_triggered` and
77
+ `v1.billing.meter.no_meter_found` as signed thin events. Those names are not in
78
+ `ALL_BETTER_STRIPE_EVENTS`; configure them explicitly as described in
79
+ [asynchronous metering errors](usage-delivery.md#receive-asynchronous-native-validation-errors).
80
+
66
81
  ### Event Processing
67
82
 
68
83
  Records synced from Stripe objects without `userId` metadata are stored unattributed (`userId: ""`) and are not returned by user-scoped queries.
@@ -70,11 +85,34 @@ Records synced from Stripe objects without `userId` metadata are stored unattrib
70
85
  The webhook handler processes events through these steps:
71
86
 
72
87
  1. Verify Stripe signature
73
- 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.
88
+ 2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `processed`, `ignored`, or still within its processing lease, return 200 immediately. A stale processing lease can be retried. If the previous delivery `failed` (its writes rolled back), the ledger row is reset and the event is reprocessed on Stripe's retry.
74
89
  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.
75
90
  4. On failure, mark the ledger row `failed` and return 500 so Stripe retries; otherwise mark it `processed`
76
91
  5. Schedule the matching `after*` async hook via `ctx.scheduler` (separate action)
77
92
 
93
+ ### Required V1 hook delivery
94
+
95
+ By default, `onEvent` and `events[type]` callbacks are best-effort.
96
+ For selected verified V1 events, `retryOnHookError(event)` can require them to
97
+ succeed before acknowledgment:
98
+
99
+ ```ts
100
+ retryOnHookError: (event) => event.type === "checkout.session.completed",
101
+ ```
102
+
103
+ For that selection, component processing commits first; the callbacks run before
104
+ the event is marked processed. Callback failures return 500 and permit redelivery.
105
+ A concurrent in-flight delivery returns 503, and a failed reservation/completion
106
+ also returns 500. An abandoned processing lease becomes retryable after ten
107
+ minutes. Sync triggers and callbacks must remain idempotent by `event.id` or a
108
+ durable business key because they can run again after partial success.
109
+
110
+ Unselected callbacks, V2 hooks and scheduled `asyncWebhook` hooks keep best-effort
111
+ acknowledgment behavior. Required fulfillment belongs in the selected V1
112
+ `onEvent`/`events` path, not a scheduled hook. Refund synchronization independently
113
+ requires ledger success even without an application retry selector. See
114
+ [the migration contract](../MIGRATION.md#remove-dojos-consumer-patch).
115
+
78
116
  ### Ledger-Based Deduplication
79
117
 
80
118
  The component maintains a `webhookEvents` table that tracks every event by its Stripe event ID. This provides:
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.67.1",
4
- "description": "A Convex component for Stripe V2 Accounts API integration.",
3
+ "version": "0.68.1",
4
+ "description": "Convex component for Stripe Accounts v2, subscriptions, metered billing and Connect marketplaces, with React workflows.",
5
5
  "keywords": [
6
6
  "stripe",
7
7
  "convex",
8
- "component"
8
+ "component",
9
+ "billing",
10
+ "subscriptions",
11
+ "metered-billing",
12
+ "usage-based-billing",
13
+ "stripe-connect",
14
+ "react"
9
15
  ],
10
16
  "homepage": "https://github.com/FantasticDevHQ/better-stripe#readme",
11
17
  "bugs": {
@@ -61,63 +67,11 @@
61
67
  "files": [
62
68
  "dist",
63
69
  "src",
64
- "docs/react-workflows.md",
65
- "docs/settlement.md",
66
- "docs/affiliate-clawbacks.md",
67
- "docs/accounts-v2-preview.md",
68
- "docs/react-workflows-audit.md",
69
- "CHANGELOG.md",
70
- "MIGRATION.md",
71
- "docs/read-contracts.md",
72
- "docs/billing-history.md",
73
- "docs/subscription-payment-methods.md",
74
- "docs/invoice-payment-pages.md",
75
- "docs/checkout-session-pages.md",
76
- "docs/refund-context.md",
77
- "docs/refund-command-evidence.md",
78
- "docs/personal-account-mapping.md",
79
- "docs/financial-ownership.md",
80
- "docs/financial-observations.md",
81
- "docs/architecture/component-extraction.md",
82
- "docs/architecture/durable-execution.md",
83
- "docs/architecture/recovery-workflow.md",
84
- "docs/balance-funding-state.md",
85
- "docs/balance-funding-workflow.md",
86
- "docs/processing-cost-reconciliation.md",
87
- "docs/example-balance-funding-cutover.md",
88
- "docs/example-recovery-cutover.md",
89
- "docs/releasing.md",
90
- "docs/release-handoff.md",
91
- "docs/setup-intent-recovery.md",
92
- "docs/metered-usage.md",
93
- "docs/metering-setup.md",
94
- "docs/README.md",
95
- "docs/overview.md",
96
- "docs/client-api.md",
97
- "docs/webhooks.md",
98
- "docs/marketplace.md",
99
- "docs/react-api.md",
100
- "docs/testing.md",
101
- "docs/configuration.md",
102
- "docs/architecture.md",
103
- "docs/development.md",
104
- "docs/usage-ledger.md",
105
- "docs/usage-catalog.md",
106
- "docs/usage-delivery.md",
107
- "docs/usage-observations.md",
108
- "docs/usage-subscriptions.md",
109
- "docs/usage-credits.md",
110
- "docs/usage-limits.md",
111
- "docs/usage-corrections.md",
112
- "docs/usage-settlement.md",
113
- "docs/usage-security.md",
114
- "docs/usage-react.md",
70
+ "docs/*.md",
71
+ "docs/architecture/*.md",
115
72
  "docs/evidence/native-metering",
116
- "docs/usage-configuration.md",
117
- "docs/usage-example.md",
118
- "docs/payout-revision-migration.md",
119
- "docs/usage-verification.md",
120
- "docs/usage-rollout.md"
73
+ "CHANGELOG.md",
74
+ "MIGRATION.md"
121
75
  ],
122
76
  "scripts": {
123
77
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -153,7 +107,8 @@
153
107
  "check:ci-parity": "repo-gates check-ci-parity",
154
108
  "check:coverage": "node scripts/check-coverage.mjs",
155
109
  "format:check": "pnpm run format",
156
- "check:agents": "repo-gates check-agents"
110
+ "check:agents": "repo-gates check-agents",
111
+ "check:package": "pnpm run build:clean && vitest run scripts/documentation-contracts.test.mjs scripts/packed-docs.test.mjs scripts/public-docs.test.mjs scripts/usage-contracts-packed.test.mjs scripts/usage-composition-packed.test.mjs scripts/usage-models-packed.test.mjs"
157
112
  },
158
113
  "dependencies": {
159
114
  "@convex-dev/workflow": "0.4.10",
@@ -1,3 +1,7 @@
1
+ export type {
2
+ ProductIdentityResult,
3
+ PriceIdentityResult,
4
+ } from "./products/identity.js";
1
5
  export type { SettlementPolicyContext } from "../shared/settlementPolicyContext.js";
2
6
  export { UsageSubscriptionError } from "./usage/subscriptionErrors.js";
3
7
  export { UsageCatalogError } from "./usage/catalogTypes.js";