@fantastic.dev/better-stripe 0.50.2 → 0.51.0

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 +26 -0
  2. package/README.md +39 -1748
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  4. package/dist/client/connect/payoutAdoptionTestHelpers.js +12 -1
  5. package/dist/client/connect/payoutAdoptionTestHelpers.js.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutExecutionTestHelpers.js +12 -1
  8. package/dist/client/connect/payoutExecutionTestHelpers.js.map +1 -1
  9. package/dist/client/usage/boundaries.d.ts +132 -0
  10. package/dist/client/usage/boundaries.d.ts.map +1 -0
  11. package/dist/client/usage/boundaries.js +43 -0
  12. package/dist/client/usage/boundaries.js.map +1 -0
  13. package/dist/client/usage/contracts.d.ts +59 -0
  14. package/dist/client/usage/contracts.d.ts.map +1 -0
  15. package/dist/client/usage/contracts.js +63 -0
  16. package/dist/client/usage/contracts.js.map +1 -0
  17. package/dist/client/usage/index.d.ts +7 -0
  18. package/dist/client/usage/index.d.ts.map +1 -0
  19. package/dist/client/usage/index.js +4 -0
  20. package/dist/client/usage/index.js.map +1 -0
  21. package/dist/client/usage/records.d.ts +50 -0
  22. package/dist/client/usage/records.d.ts.map +1 -0
  23. package/dist/client/usage/records.js +54 -0
  24. package/dist/client/usage/records.js.map +1 -0
  25. package/docs/README.md +58 -0
  26. package/docs/architecture.md +80 -0
  27. package/docs/client-api.md +586 -0
  28. package/docs/configuration.md +51 -0
  29. package/docs/development.md +114 -0
  30. package/docs/marketplace.md +165 -0
  31. package/docs/metered-usage.md +289 -37
  32. package/docs/metering-setup.md +183 -0
  33. package/docs/overview.md +140 -0
  34. package/docs/react-api.md +284 -0
  35. package/docs/releasing.md +19 -0
  36. package/docs/testing.md +52 -0
  37. package/docs/webhooks.md +259 -0
  38. package/package.json +17 -2
  39. package/src/client/connect/payoutAdoptionTestHelpers.ts +17 -1
  40. package/src/client/connect/payoutExecutionTestHelpers.ts +17 -1
  41. package/src/client/transferContinuation.test.ts +2 -6
  42. package/src/client/usage/boundaries.test.ts +136 -0
  43. package/src/client/usage/boundaries.ts +182 -0
  44. package/src/client/usage/contracts.test.ts +145 -0
  45. package/src/client/usage/contracts.ts +79 -0
  46. package/src/client/usage/index.ts +34 -0
  47. package/src/client/usage/records.ts +76 -0
  48. package/src/test.ts +17 -1
  49. package/src/vite-env.d.ts +5 -1
@@ -0,0 +1,140 @@
1
+ # Package overview
2
+
3
+ ## Features
4
+
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
8
+ - **Subscriptions** -- Lifecycle management including cancel, reactivate, quantity updates, and trial tracking
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
+ - **Split engine** -- Single-recipient destination charges or multi-recipient separate-charges-and-transfers (store + affiliate(s)), computed and executed by the webhook engine
11
+ - **Invoices** -- Invoice syncing and querying with metadata propagation from subscriptions
12
+ - **Payments** -- Payment intent tracking and status management
13
+ - **Payouts** -- Automatic rolling payouts for Connect/marketplace flows, with a recipient balance + cadence React surface
14
+ - **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)
15
+ - **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
16
+ - **Per-store statement descriptors** -- Buyer-recognizable charge descriptors resolved per seller with a configurable platform fallback
17
+ - **Webhook handling** -- Single-endpoint processing with ledger-based deduplication and replay protection
18
+ - **Trigger system** -- BetterAuth-style sync triggers (same transaction) and async hooks (scheduled action) for app-layer extensibility
19
+ - **React hooks** -- Read hooks and flow hooks for all billing and marketplace-economics domains (fees, splits, earnings, payouts, disputes)
20
+ - **Headless UI components** -- Checkout, subscription, payment method, Connect, payout, split, and dispute components with render-prop customization
21
+ - **Test utilities** -- Typed fixture factories, mock webhook events, and `assertTestEnvironment` guard
22
+
23
+ See [Roadmap / Known Gaps](#roadmap--known-gaps) for what's still in flight.
24
+
25
+ ## Roadmap / Known Gaps
26
+
27
+ 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:
28
+
29
+ - **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.
30
+ - **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.
31
+ - **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.
32
+ - **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](affiliate-clawbacks.md).
33
+ - **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.
34
+
35
+ ### Relation to `@convex-dev/stripe`
36
+
37
+ 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.
38
+
39
+ ## Accounts v2 customer preview
40
+
41
+ Choose the setup that matches your Stripe account:
42
+
43
+ | Integration | Enable “Reusable payment methods for Global Payouts” for Accounts v2 access? | BetterStripe API version |
44
+ | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------ |
45
+ | Connect platform, including ordinary connected-account payouts and marketplace splits | No. Accounts v2 is GA for Connect. | Omit `stripeApiVersion` to keep the GA default. |
46
+ | 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`. |
47
+
48
+ For the non-Connect setup, the account owner enables that exact toggle under
49
+ [Account previews and features](https://dashboard.stripe.com/settings/previews)
50
+ → **Product previews**. If it is missing or disabled, check with the account
51
+ owner and request access through [Stripe's customer-account guide](https://docs.stripe.com/accounts-v2/use-accounts-as-customers).
52
+ The Dashboard does not always explain why a toggle is disabled. Do not enable
53
+ Connect just to bypass the customer-preview requirement.
54
+
55
+ The exported preview constant currently selects `2026-09-30.preview`, which
56
+ passed our live non-Connect checkout and billing tests. A newer version selected
57
+ in Stripe's API documentation does not enable account features or change this
58
+ package's supported-version list. Both account enablement and a supported
59
+ preview request version are necessary. Use `stripe.registerRoutes` to inherit
60
+ the client's version for webhook processing, and pin snapshot destinations to
61
+ the same version.
62
+
63
+ The table covers **Accounts v2 access**. Actually reusing saved payment methods
64
+ for **Global Payouts** is a separate preview feature with its own eligibility,
65
+ even for Connect users. See [Stripe's credential-reuse guide](https://docs.stripe.com/global-payouts/credential-reuse).
66
+ Enabling this toggle also synchronizes existing Customers into customer-configured
67
+ Accounts and changes customer creation in Stripe-hosted integrations. Review
68
+ those migration effects before enabling it on an existing account.
69
+ See the [customer preview setup and webhook migration guide](accounts-v2-preview.md).
70
+
71
+ Recipient-held custom payout policies now have versioned preparation, verified
72
+ manual schedule changes, live drift checks, opt-out restoration, and a bounded
73
+ deadline-expiry API. See [policy setup and limits](settlement.md#recipient-held-payout-policy-controls).
74
+ A [recipient funding reader](settlement.md#verified-recipient-funding-receipts)
75
+ verifies original and reversal receipts, maturity, and exact settlement amounts;
76
+ received credit is kept distinct from still-unpaid entitlement.
77
+ A [payout receipt and reconciliation API](settlement.md#verified-payout-receipts-and-reconciliation)
78
+ verifies actual bank-payout debits and returns, adopts an attempted claim's
79
+ provider outcome, and books its net payout fees once.
80
+ The [combined release API](settlement.md#combined-recipient-release) verifies
81
+ complete source and payout history, reserves mature unpaid funds, and creates an
82
+ idempotent bank payout. Install a host job to invoke it and expire due policies.
83
+ The [automatic worker](settlement.md#automatic-recipient-worker) provides
84
+ durable attempt IDs, retry leases, recovery discovery and the next attempt time.
85
+ The example installs its five-minute cron in `example/convex/crons.ts`.
86
+ A [payout eligibility preview](settlement.md#payout-eligibility-preview)
87
+ uses the release qualification checks to report combined mature funds, pending
88
+ credits, shared deductions and source categories without creating a bank payout.
89
+ The unstyled React [`PayoutProgress`](react-workflows.md#combined-automatic-payout-progress)
90
+ displays that assessment with one combined minimum and supports custom cards
91
+ and translated copy through render props.
92
+ [`PayoutSettings`](react-workflows.md#payout-settings)
93
+ adds consent, exact minimum entry, pending-state recovery and account-wide opt-out
94
+ through authorized host callbacks. Seller and affiliate payout pages use both.
95
+ [Historical imports and explicit funded activation](settlement.md#historical-import-and-funded-activation)
96
+ verify old payouts, source ownership and holding age before enabling a custom
97
+ schedule. Larger histories and unallocated money still require reconciliation;
98
+ schedule controls alone do not enforce a minimum.
99
+ [Resumable local collections and reset safeguards](settlement.md#resumable-local-collections)
100
+ provide bounded ledger inspection while provider-history continuation and scalable
101
+ claim execution are completed.
102
+
103
+ ## Component history and currency summaries
104
+
105
+ See the [read contract guide](read-contracts.md) for reactive product, price and payout
106
+ cursors, exact currency summaries, legacy backfill, payout failure details, and
107
+ published-version adoption requirements.
108
+
109
+ For buyer purchase-history discovery, use the public invoice and
110
+ [Checkout-session page readers](checkout-session-pages.md). Checkout pages
111
+ also reveal open/asynchronous sessions with no invoice. They preserve raw
112
+ references and require host authorization, continuation checkpoints and
113
+ historical reconciliation; they do not attest complete history or award credit.
114
+
115
+ 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](settlement.md) for worker cadence, retries and expiry limitations.
116
+
117
+ 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](settlement.md) for operator handling.
118
+
119
+ 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](react-workflows.md).
120
+
121
+ 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](settlement.md).
122
+
123
+ 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](settlement.md#resumable-local-collections).
124
+
125
+ 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](settlement.md#versioned-recovery-liabilities).
126
+
127
+ 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](settlement.md#historical-import-and-funded-activation).
128
+
129
+ ## Metered usage
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.
132
+
133
+ ## Resources
134
+
135
+ - [Stripe V2 Accounts API](https://docs.stripe.com/connect/accounts-v2/api)
136
+ - [Stripe Embedded Checkout](https://docs.stripe.com/payments/checkout/custom)
137
+ - [Convex Component Authoring](https://docs.convex.dev/components/authoring)
138
+ - [Stripe Webhook Event Reference](https://docs.stripe.com/api/events/types)
139
+ - [Stripe Testing Guide](https://docs.stripe.com/testing)
140
+ - [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
@@ -0,0 +1,284 @@
1
+ # React API reference
2
+
3
+ ## React Hooks
4
+
5
+ Import from `@fantastic.dev/better-stripe/react`. All hooks use Convex's `useQuery` and `useMutation` internally.
6
+
7
+ 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
+
9
+ ### Read Hooks
10
+
11
+ | Hook Factory | Hook Arguments | Returns |
12
+ | ------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
13
+ | `createUseAccount` | `(userId?)` | `{ account, isLoading }` |
14
+ | `createUseProducts` | `({ accountId?, active? }?)` | `{ products, isLoading }` |
15
+ | `createUsePrices` | `(productId?)` | `{ prices, isLoading }` |
16
+ | `createUseSubscription` | `(subscriptionId?)` | `{ subscription, isActive, isTrialing, isCanceling, daysUntilRenewal, daysUntilTrialEnd, isLoading }` |
17
+ | `createUseSubscriptions` | `({ userId?, status? }?)` | `{ subscriptions, activeSubscription, isLoading }` |
18
+ | `createUseCheckout` | `(sessionId?)` | `{ session, status, isComplete, isLoading }` |
19
+ | `createUsePaymentMethods` | `(accountId?)` | `{ methods, defaultMethod, isLoading }` |
20
+ | `createUseInvoices` | `({ userId?, subscriptionId?, status? }?)` | `{ invoices, isLoading }` |
21
+ | `createUseAccountOnboarding` | `(accountId?)` | `{ account, status, isReady, missingRequirements, isLoading }` |
22
+ | `createUseEarnings` | `(accountId?)` | `{ gross, reversed, net, payouts, paidOut, transfers, isLoading }` — recipient balance/earnings |
23
+ | `createUseSplitBreakdown` | `({ sourceChargeId?, saleAmount? })` | `{ breakdown: { legs, store, affiliate, other, recipientsTotal, platform? } \| null, isLoading }` — per-sale split |
24
+ | `createUseDisputes` | `({ accountId?, status? }?)` | `{ disputes, isLoading }` |
25
+ | `createUseDisputeWithCountdown` | `(stripeDisputeId?)` | `{ dispute, countdown: { dueBy?, daysRemaining?, isOverdue } \| null, isLoading }` |
26
+
27
+ ### Checkout Session Hooks
28
+
29
+ For Stripe Checkout Session custom UI flows (CheckoutProvider-based):
30
+
31
+ | Hook / Component | Description |
32
+ | ------------------------- | ----------------------------------------------------------------------------------------------------------- |
33
+ | `CheckoutSessionProvider` | Provider wrapping Stripe's `CheckoutProvider`. Accepts `publishableKey`, `clientSecret`, `appearance`. |
34
+ | `useCheckoutSession()` | Returns `{ type, sessionId, canConfirm, confirm(opts?) }` — discriminated union for checkout state/actions. |
35
+
36
+ ```tsx
37
+ import {
38
+ CheckoutSessionProvider,
39
+ PaymentElement,
40
+ useCheckoutSession,
41
+ } from "@fantastic.dev/better-stripe/react";
42
+
43
+ <CheckoutSessionProvider publishableKey={pk} clientSecret={token}>
44
+ <MyForm />
45
+ </CheckoutSessionProvider>;
46
+
47
+ function MyForm() {
48
+ const checkout = useCheckoutSession();
49
+ if (checkout.type !== "success") return <Spinner />;
50
+ return (
51
+ <>
52
+ <PaymentElement />
53
+ <button
54
+ disabled={!checkout.canConfirm}
55
+ onClick={() => checkout.confirm()}
56
+ >
57
+ Pay
58
+ </button>
59
+ </>
60
+ );
61
+ }
62
+ ```
63
+
64
+ ### Payment Confirmation Hooks
65
+
66
+ | Hook | Description |
67
+ | --------------------- | ----------------------------------------------------------------------------------------------------- |
68
+ | `useConfirmPayment()` | Provides `confirmPayment(clientSecret)`, `confirmCardSetup(clientSecret)`, `confirmSetup(returnUrl?)` |
69
+
70
+ All return `{ success: true } | { success: false, error: string }`.
71
+
72
+ ### Payment Method Action Hooks
73
+
74
+ | Hook | Description |
75
+ | ----------------------------- | ------------------------------------------------------------------------------------- |
76
+ | `usePaymentMethodActions(cb)` | Provides `createAndAttach()`, `detach(id)`, `setDefault(id)` with loading/error state |
77
+
78
+ Accepts app-provided callbacks for backend operations (attach, detach, setDefault, reload).
79
+
80
+ ### Theming
81
+
82
+ | API | Description |
83
+ | -------------------------------- | ------------------------------------------------------------------------- |
84
+ | `createStripeAppearance(config)` | Factory: color tokens → Stripe `Appearance` object |
85
+ | `createStripeElementStyles(cfg)` | Factory: color tokens → inline `style` for CardNumber/Expiry/CVC elements |
86
+ | `defaultStripeAppearance` | Light preset |
87
+ | `darkStripeAppearance` | Dark preset |
88
+
89
+ ### Re-exported Stripe Elements
90
+
91
+ These are re-exported so apps never need to import from `@stripe/react-stripe-js` directly:
92
+
93
+ `PaymentElement`, `CardElement`, `CardNumberElement`, `CardExpiryElement`, `CardCvcElement`
94
+
95
+ ## React Components
96
+
97
+ Import from `@fantastic.dev/better-stripe/react`. The package includes the
98
+ example's reusable checkout, payouts, refunds, disputes, accounts, onboarding,
99
+ products, subscriptions, billing, referrals, and admin/setup workflows.
100
+
101
+ Use native unstyled markup, render props, or companion hooks with your own
102
+ design system. Bind authenticated server callbacks and query data in your app.
103
+ Supported workflows can select Stripe Connect embedded presentation; checkout
104
+ supports five integrations. No example router, persona provider, or CSS is required.
105
+
106
+ See [the React workflow guide](react-workflows.md) for usage, the full
107
+ component/hook matrix, styling, data contracts, and Stripe integration limits.
108
+ Existing low-level components remain available below. Props vary by component;
109
+ Stripe iframe styling uses `appearance`, while custom markup uses render props
110
+ or the low-level component's `className`/label props.
111
+
112
+ ### Hosted onboarding navigation
113
+
114
+ Since 0.14.0, `Onboarding` and `useOnboarding` suppress hosted navigation from
115
+ create/continue responses after unmount or authenticated scope replacement.
116
+ Current-scope responses still navigate through `onNavigate` or the default
117
+ `window.location.assign`. Shared pending locks, duplicate-submit prevention and
118
+ error state remain intact. Set `scopeKey` to identify the authenticated
119
+ account/resource; it controls lifecycle isolation and does not authorize access.
120
+ See the [workflow guide](react-workflows.md#dispute-evidence-uploads-and-onboarding-navigation).
121
+
122
+ ### Provider
123
+
124
+ | Component | Description |
125
+ | ------------------------- | ------------------------------------------------------------------------------------------------ |
126
+ | `StripeProvider` | Stripe Elements context provider. Accepts `publishableKey` prop. |
127
+ | `CheckoutSessionProvider` | Checkout Session context provider for custom UI flows. Accepts `publishableKey`, `clientSecret`. |
128
+
129
+ ### Checkout and Subscription
130
+
131
+ | Component | Description |
132
+ | ----------------------- | --------------------------------------------------------- |
133
+ | `EmbeddedCheckout` | Headless embedded checkout with render-prop loading state |
134
+ | `CheckoutStatus` | Checkout session status display |
135
+ | `PricePicker` | Plan/price selection with render-prop customization |
136
+ | `PriceCard` | Individual price card (controlled or uncontrolled) |
137
+ | `IntervalSelector` | Billing interval toggle (month/year) |
138
+ | `SubscriptionCard` | Current subscription display |
139
+ | `SubscriptionLineItems` | Line item breakdown |
140
+ | `PriceBadge` | Price/plan badge |
141
+ | `TrialAlert` | Trial status and renewal alert |
142
+ | `BillingPortalLink` | Link/button to Stripe billing portal |
143
+ | `SubscriptionActions` | Cancel/reactivate action buttons (status-aware) |
144
+
145
+ ### Payment Methods
146
+
147
+ | Component | Description |
148
+ | --------------------------- | -------------------------------------------------- |
149
+ | `AddCardForm` | Headless add-payment-method form |
150
+ | `PaymentMethodsList` | Saved payment methods list with render props |
151
+ | `DeletePaymentMethodDialog` | Remove payment method (app provides dialog chrome) |
152
+ | `PaymentMethodActions` | Per-method set-default/delete actions |
153
+
154
+ ### Buyer Billing
155
+
156
+ | Component | Description |
157
+ | ------------------ | ------------------------------------------------------------------------------------------------------- |
158
+ | `BuyerBillingView` | Per-store buyer billing view: subscriptions grouped by store, reusable saved card, embedded card update |
159
+
160
+ An embedded-only billing surface for buyers: their subscriptions are grouped by
161
+ store (each store scoped via the `listSubscriptionsByUserAndStore` /
162
+ `groupSubscriptionsByStore` per-store queries) with per-store cancel/reactivate,
163
+ alongside the ONE saved payment method that is reusable across every store. The
164
+ card is updated in place via an embedded `AddCardForm` slot — no redirect.
165
+
166
+ ```tsx
167
+ import {
168
+ BuyerBillingView,
169
+ AddCardForm,
170
+ StripeProvider,
171
+ } from "@fantastic.dev/better-stripe/react";
172
+ import { groupSubscriptionsByStore } from "@fantastic.dev/better-stripe";
173
+
174
+ function BuyerBilling({ userId, customerAccount }: Props) {
175
+ const subscriptions = useQuery(api.stripe.listSubscriptionsByUser, {
176
+ userId,
177
+ });
178
+ const { defaultMethod } = usePaymentMethods(customerAccount);
179
+ const cancel = useMutation(api.stripe.cancelSubscription);
180
+ const reactivate = useMutation(api.stripe.reactivateSubscription);
181
+
182
+ return (
183
+ <BuyerBillingView
184
+ // groupSubscriptionsByStore reused, not recomputed
185
+ subscriptions={subscriptions?.map((s) => ({
186
+ ...s,
187
+ id: s.stripeSubscriptionId,
188
+ }))}
189
+ paymentMethod={defaultMethod}
190
+ isLoading={subscriptions === undefined}
191
+ onCancel={(sub) => cancel({ stripeSubscriptionId: sub.id })}
192
+ onReactivate={(sub) => reactivate({ stripeSubscriptionId: sub.id })}
193
+ updateCardSlot={
194
+ <StripeProvider publishableKey={pk}>
195
+ <AddCardForm onSuccess={handleCardSaved} />
196
+ </StripeProvider>
197
+ }
198
+ />
199
+ );
200
+ }
201
+ ```
202
+
203
+ ### Connect and Marketplace
204
+
205
+ | Component | Description |
206
+ | ------------------------- | --------------------------------------------- |
207
+ | `ConnectStatusBadge` | Connect verification status badge |
208
+ | `AccountOnboardingCard` | Connect onboarding progress display |
209
+ | `AccountOnboardingButton` | Continue onboarding action (status-aware) |
210
+ | `AccountCreateCard` | Create Connect account card |
211
+ | `AccountCreateButton` | Create account action with loading state |
212
+ | `AccountLoginCard` | Login to Connect dashboard card |
213
+ | `AccountLoginButton` | Dashboard login/open action |
214
+ | `AccountCloseCard` | Close/restart account card (status-aware) |
215
+ | `AccountCloseButton` | Close/restart action with status-aware labels |
216
+ | `ConnectRequirements` | Missing requirements checklist |
217
+
218
+ ### Payouts and Earnings
219
+
220
+ Use React's `formatPayoutAmount(amount, currency, locale?)` when rendering
221
+ observed ordinary Stripe balances and payouts. It preserves supported currency
222
+ units, including JPY and fractional ISK/UGX compatibility values. Unknown
223
+ precision is shown explicitly as raw minor units with `display unavailable`.
224
+ This display helper does not establish payout eligibility or Global Payouts
225
+ currency support. See the [React workflow guide](react-workflows.md).
226
+
227
+ | Component | Description |
228
+ | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
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. |
230
+ | `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
+ | `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
+
233
+ ### Disputes (headless)
234
+
235
+ 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.
236
+
237
+ | Component | Description |
238
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
239
+ | `DisputesList` | Sorted-by-deadline dispute list (soonest evidence due-by first, no-deadline last), fed by `useDisputes` |
240
+ | `DisputeDetail` | Amount, reason, status, evidence-due countdown, and linked transfers for one dispute, fed by `useDisputeWithCountdown` |
241
+ | `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 |
242
+ | `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 |
243
+
244
+ ### Embedded Disputes (Stripe Connect)
245
+
246
+ The Stripe-hosted alternative to the headless dispute components: each seller
247
+ views and responds to their own disputes via Stripe's embedded `disputes_list`
248
+ / `payment_disputes` components, driven by the Account Session that
249
+ `createDisputeSession` creates.
250
+
251
+ | Component | Description |
252
+ | ------------------ | ----------------------------------------------------------------------------------------------- |
253
+ | `ConnectProvider` | Initializes ConnectJS with your publishable key + an account-session fetcher |
254
+ | `EmbeddedDisputes` | Mounts the embedded `disputes_list` (or `payment_disputes` when scoped via `payment`) component |
255
+
256
+ **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
+
258
+ ```tsx
259
+ // convex/stripe.ts — expose the account session (server side)
260
+ export const createDisputeSession = action({
261
+ args: { stripeAccountId: v.string() },
262
+ handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
263
+ });
264
+
265
+ // Seller disputes page (client side)
266
+ import {
267
+ ConnectProvider,
268
+ EmbeddedDisputes,
269
+ } from "@fantastic.dev/better-stripe/react";
270
+
271
+ function SellerDisputes({ stripeAccountId }: { stripeAccountId: string }) {
272
+ const createSession = useAction(api.stripe.createDisputeSession);
273
+ return (
274
+ <ConnectProvider
275
+ publishableKey={import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY}
276
+ fetchClientSecret={async () =>
277
+ (await createSession({ stripeAccountId })).clientSecret
278
+ }
279
+ >
280
+ <EmbeddedDisputes />
281
+ </ConnectProvider>
282
+ );
283
+ }
284
+ ```
package/docs/releasing.md CHANGED
@@ -50,3 +50,22 @@ the extensionless import exposed by the public SDK in 0.47.0. Use explicit `.js`
50
50
  extensions for reachable relative imports; do not hide failures behind a custom
51
51
  resolver. A corrected local build is candidate evidence; verify the normal
52
52
  published artifact before application adoption.
53
+
54
+ ## Release workflow
55
+
56
+ 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.**
57
+
58
+ 1. **Give every PR a Conventional Commit title** (it becomes the squash-merge commit):
59
+ - `fix: …` makes a patch release.
60
+ - `feat: …` makes a minor release.
61
+ - `feat!: …` (or a `BREAKING CHANGE:` footer) makes a minor release while the package is pre-1.0.
62
+ - `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.
63
+
64
+ Write the title for consumers of the package: it becomes the changelog entry. A title that isn't a Conventional Commit is left out.
65
+
66
+ 2. **On merge to `main`**, the `Release` workflow opens or updates a release PR that bumps `package.json`, `CHANGELOG.md`, the README version line 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.
67
+ 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.
68
+
69
+ 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.
70
+
71
+ The private `example` workspace isn't published.
@@ -0,0 +1,52 @@
1
+ # Testing utilities
2
+
3
+ Import from `@fantastic.dev/better-stripe/testing`.
4
+
5
+ ### assertTestEnvironment
6
+
7
+ Guards against running test fixtures with live Stripe keys:
8
+
9
+ ```typescript
10
+ import { assertTestEnvironment } from "@fantastic.dev/better-stripe/testing";
11
+
12
+ assertTestEnvironment(); // Throws if STRIPE_SECRET_KEY does not start with sk_test_
13
+ ```
14
+
15
+ ### Fixture Factories
16
+
17
+ Typed factories for creating Stripe test data:
18
+
19
+ ```typescript
20
+ import {
21
+ createTestAccount,
22
+ createTestPrice,
23
+ createTestProduct,
24
+ createTestSubscription,
25
+ } from "@fantastic.dev/better-stripe/testing";
26
+
27
+ const account = await createTestAccount(stripe, { email: "test@example.com" });
28
+ const product = await createTestProduct(stripe, { name: "Pro Plan" });
29
+ const price = await createTestPrice(stripe, {
30
+ productId: product.id,
31
+ unitAmount: 2999,
32
+ interval: "month",
33
+ });
34
+ ```
35
+
36
+ ### Mock Webhook Events
37
+
38
+ Factories for creating mock webhook events in tests:
39
+
40
+ ```typescript
41
+ import {
42
+ mockAccountUpdated,
43
+ mockCheckoutCompleted,
44
+ mockInvoicePaid,
45
+ mockSubscriptionUpdated,
46
+ } from "@fantastic.dev/better-stripe/testing";
47
+
48
+ const event = mockCheckoutCompleted({
49
+ stripeSessionId: "cs_test_123",
50
+ metadata: { userId: "user_abc" },
51
+ });
52
+ ```