@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.
@@ -0,0 +1,586 @@
1
+ # Server API
2
+
3
+ ## Client API reference
4
+
5
+ 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.
6
+
7
+ 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_...`).
8
+
9
+ ### Account
10
+
11
+ `closeAccount` and its `restartAccountOnboarding` alias retain a durable closure
12
+ record before contacting Stripe. Successful closure removes the active account
13
+ mapping but preserves the original user/organization ownership, close timestamp
14
+ and financial rows. A pending attempt pins its owner through retry; delayed
15
+ account upserts cannot revive a closed recipient. Retrying after provider success
16
+ and local persistence failure retrieves provider state and completes locally
17
+ without closing an already closed account again. A required provider lookup that
18
+ fails now stops closure rather than submitting an empty configuration guess.
19
+
20
+ `getClosedAccountByStripeId(ctx, { stripeAccountId })` retrieves closed provenance;
21
+ `listClosedAccountsByUserId(ctx, { userId, paginationOpts })` discovers personal
22
+ closed accounts using indexed pages of 1–100 records. Organization accounts are
23
+ excluded from personal discovery. These are trusted host APIs: authenticate the
24
+ actor and check both original user and organization scope before passing the
25
+ historical Stripe account ID to existing payout, transfer or commission readers.
26
+ A supplied userId or a replacement account never proves historical ownership.
27
+ An untracked legacy closure has no invented owner and is not discoverable as a
28
+ personal account. Records deleted before this contract cannot be reconstructed.
29
+
30
+ Closure provenance does not evaluate outstanding funds, reservations, recovery
31
+ liabilities or permission to create a replacement. Applications must enforce
32
+ those policies before exposing `AccountCloseCard`; its render props provide
33
+ presentation and confirmation, not financial authorization. Do not use closure
34
+ as an automatic delete-and-recreate onboarding reset. Existing active-account
35
+ getters keep their signatures and exclude completed closures; historical readers
36
+ retain original financial references. The Vite reference's
37
+ [closed-account authorization example](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md#closed-account-history)
38
+ shows where the host's authenticated-actor check belongs.
39
+
40
+ | Method | Description |
41
+ | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
42
+ | `createAccount(ctx, { userId, email?, name?, country?, orgId?, metadata? })` | Create a V2 account in Stripe and the component database |
43
+ | `getAccount(ctx, { accountId })` | Get account by component document ID |
44
+ | `getAccountByStripeId(ctx, { stripeAccountId })` | Get account by Stripe account ID |
45
+ | `getOrCreateAccount(ctx, { userId, email?, name?, country?, orgId?, metadata? })` | Get existing or create new account |
46
+ | `getAccountByUserId(ctx, { userId })` | Get account by app-layer user ID |
47
+ | `getAccountByOrgId(ctx, { orgId })` | Get account by organization/team ID |
48
+ | `getAccountOnboardingStatus(ctx, { accountId })` | Get Connect onboarding status (by component document ID) |
49
+ | `updateAccount(ctx, { stripeAccountId, email?, name?, metadata? })` | Update account fields |
50
+ | `createAccountLink(ctx, { stripeAccountId, refreshUrl, returnUrl, type })` | Create Connect onboarding or update link |
51
+ | `createAccountSession(ctx, { stripeAccountId, components })` | Create embedded account management session |
52
+ | `createLoginLink(ctx, { stripeAccountId })` | Create Express dashboard login link |
53
+ | `addRecipientConfiguration(ctx, { stripeAccountId })` | Add recipient configuration to an existing account |
54
+ | `getV2Account(ctx, { stripeAccountId, include? })` | Retrieve a V2 account directly from Stripe |
55
+ | `updateV2Account(ctx, { stripeAccountId, updateParams })` | Update a V2 account in Stripe |
56
+ | `listStripeAccounts(ctx, { limit? })` | List V2 accounts directly from Stripe |
57
+ | `closeAccount(ctx, { stripeAccountId })` | Close a V2 account; returns `{ closed: boolean }` |
58
+ | `restartAccountOnboarding(ctx, { stripeAccountId })` | Close the account so onboarding can restart fresh |
59
+ | `setAccountStatementDescriptor(ctx, { stripeAccountId, statementDescriptor })` | Set (or `null` to clear) the account's per-store statement-descriptor suffix |
60
+ | `createDisputeSession(ctx, { stripeAccountId })` | Create an embedded Account Session scoped to the seller's disputes |
61
+
62
+ ### Product and Price
63
+
64
+ `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.
65
+
66
+ 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.
67
+
68
+ | Method | Description |
69
+ | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
70
+ | `createProduct(ctx, { name, description?, active?, accountId?, metadata? })` | Create product in Stripe and component DB |
71
+ | `getProduct(ctx, { productId })` | Get product by component document ID |
72
+ | `getProductByStripeId(ctx, { stripeProductId })` | Get product by Stripe product ID |
73
+ | `listProducts(ctx, { accountId?, active?, limit? })` | List products with optional filters |
74
+ | `updateProduct(ctx, { stripeProductId, ...updates })` | Update product fields |
75
+ | `deactivateProduct(ctx, { stripeProductId })` | Deactivate product in Stripe and component DB |
76
+ | `createPrice(ctx, { stripeProductId, unitAmount, type, currency?, interval?, intervalCount?, nickname?, metadata? })` | Create price in Stripe and component DB |
77
+ | `getPrice(ctx, { priceId })` | Get price by component document ID |
78
+ | `getPriceByStripeId(ctx, { stripePriceId })` | Get price by Stripe price ID |
79
+ | `listPrices(ctx, { productId?, active?, limit? })` | List prices with optional filters |
80
+ | `updatePrice(ctx, { stripePriceId, ...updates })` | Update price fields |
81
+ | `deactivatePrice(ctx, { stripePriceId })` | Deactivate price in Stripe and component DB |
82
+
83
+ ### Checkout and Subscription
84
+
85
+ | Method | Description |
86
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
87
+ | `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 |
88
+ | `getCheckoutSession(ctx, { sessionId })` | Get checkout session by component document ID |
89
+ | `getCheckoutSessionByStripeId(ctx, { stripeSessionId })` | Get checkout session by Stripe session ID |
90
+ | `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 |
91
+ | `getSubscription(ctx, { subscriptionId })` | Get subscription by component document ID |
92
+ | `getSubscriptionByStripeId(ctx, { stripeSubscriptionId })` | Get subscription by Stripe subscription ID |
93
+ | `listSubscriptions(ctx, { stripeAccountId?, status?, limit? })` | List subscriptions, optionally scoped to a Connect account (use `listSubscriptionsByUser` for per-user filtering) |
94
+ | `listSubscriptionsByUser(ctx, { userId, status? })` | List all subscriptions for a user |
95
+ | `listSubscriptionsByOrg(ctx, { orgId, status? })` | List all subscriptions for an organization |
96
+ | `getActiveSubscription(ctx, { userId, orgId? })` | Get the active subscription for a user or org |
97
+ | `getTrialStatus(ctx, { subscriptionId })` | Get trial state for a subscription |
98
+ | `cancelSubscription(ctx, { stripeSubscriptionId, cancelAtPeriodEnd? })` | Cancel subscription immediately or at period end |
99
+ | `reactivateSubscription(ctx, { stripeSubscriptionId })` | Reactivate a canceled subscription |
100
+ | `updateSubscriptionQuantity(ctx, { stripeSubscriptionId, quantity })` | Update subscription seat quantity |
101
+
102
+ ### Durable recovery claims
103
+
104
+ `stripe.costRecovery` is a server-only recovery client backed by the Convex
105
+ component. Bookkeeping methods do not use Stripe credentials or move money.
106
+ Invoice methods use the configured Stripe client and must run in an action.
107
+ Your host authenticates the
108
+ caller, approves which costs are owed, authorizes the account and recovery scope,
109
+ and verifies provider outcomes before confirming collection. A recovery scope is
110
+ an application-defined liability boundary, such as one store. Amounts are signed
111
+ integer minor units and currencies never mix.
112
+
113
+ ```ts
114
+ const recovery = stripe.costRecovery;
115
+ const scope = {
116
+ accountId: sellerAccountId,
117
+ scopeKey: storeId,
118
+ currency: "usd",
119
+ };
120
+ await recovery.recordClaim(ctx, {
121
+ ...scope,
122
+ claimKey: `cost:${chargeId}`,
123
+ sourceChargeId: chargeId,
124
+ sourceGross: originalGross,
125
+ sourceProcessingFee: originalProviderFee,
126
+ amountDue: approvedCumulativeCost,
127
+ revision: durableObservationRevision,
128
+ });
129
+ const result = await recovery.reserve(ctx, {
130
+ ...scope,
131
+ groupKey: `settlement:${fundingChargeId}`,
132
+ operationKey: `settlement:${fundingChargeId}:batch:1`,
133
+ sourceKind: "settlement",
134
+ sourceId: fundingChargeId,
135
+ sourceGross: fundingGross,
136
+ sourceProcessingFee: fundingProviderFee,
137
+ maxDebit: availableSellerEarnings,
138
+ maxCredit: approvedCreditBudget,
139
+ });
140
+ ```
141
+
142
+ Claims retain their original charge, account, scope, currency, gross and provider
143
+ fee. Replays of the same revision must have the same amount; lower revisions are
144
+ ignored. The host must assign durable, monotonically increasing observation
145
+ revisions from authoritative reconciliation, not an unordered event arrival
146
+ counter. Use `getClaim(ctx, { claimKey })` to capture the prior revision before
147
+ reading provider state, then propose the next revision. On a conflicting revision,
148
+ retry the full provider reconciliation, rather than incrementing the revision of
149
+ an already-stale snapshot. Later provider observations update cumulative `amountDue`, including
150
+ signed credits, without erasing collected or reserved history. Claim keys beginning
151
+ with `rollback:` are reserved by the package.
152
+
153
+ Reservations use maintained totals across all claims, so a credit beyond the
154
+ first history page still reduces the recoverable amount. Each call allocates at
155
+ most 100 claims. Repeat with distinct, durable batch operation keys in the same
156
+ group until `seal(ctx, { groupKey })` succeeds. The group's debit/credit budgets
157
+ apply across all batches. A group identifies exactly one external money boundary;
158
+ only one group per account/scope/currency may remain pending. Retry the same batch
159
+ key to recover the same allocation after a timeout or host write failure.
160
+
161
+ Seal before any provider side effect. New claim observations can require another
162
+ batch before sealing; observations after sealing remain owed or credited for a
163
+ later group. After verifying the provider's final result, call
164
+ `finish(ctx, { groupKey, outcome: "collect" | "release" })`. Completion processes
165
+ at most ten reservations per call, each with at most 100 claims. Repeat while
166
+ `isDone` is false using separate action/job invocations when needed to respect
167
+ Convex transaction limits. Completion is idempotent; a collected group cannot be
168
+ released or reused with another outcome. Do not release an unknown provider
169
+ outcome just because a request timed out. An unpaid invoice must stay reserved
170
+ until its verified payment or cancellation policy resolves it.
171
+
172
+ For a collected settlement group whose funding sale is later returned, call
173
+ `rollback(ctx, { groupKey, returnedPrincipal, revision })` with the authorized
174
+ cumulative principal. This records a separate, source-linked rollback claim,
175
+ preserves the original costs and collection history, and rounds positive and
176
+ negative amounts symmetrically. Reinstated principal can reduce the rollback
177
+ again with a newer revision. This bookkeeping operation does not refund or
178
+ reverse a transfer. For invoice groups, use the verified funding adapter below;
179
+ do not invent invoice payment allocations.
180
+
181
+ Use `balance(ctx, scope)` for exact maintained totals and
182
+ `listClaims(ctx, { ...scope, limit, cursor })` for paginated history. `getClaim`, `getGroup` and
183
+ `getReservation` resume durable workflows. Integrate these server callbacks with
184
+ the existing unstyled React `CostRecovery` display. These bookkeeping APIs leave
185
+ consent, provider fee policy and entitlement changes in the host.
186
+
187
+ The example uses these package calls for sale reservations, verified collection,
188
+ monthly invoice adjustments and source observations. Its host stores source and
189
+ display metadata; financial totals come from the component. `CostRecovery` accepts
190
+ an optional `reservedAmount` to distinguish reservations from collected money,
191
+ while preserving the legacy `invoicedAmount` input. See the example README for
192
+ cutover constraints and the sandbox renewal acceptance procedure.
193
+
194
+ ### Atomic recovery preparation
195
+
196
+ Call `stripe.costRecovery.prepareGroup(ctx, { ...groupOptions, limit: 100 })`
197
+ after authorizing the account, scope, currency, source and debit/credit policy.
198
+ Each call reserves at most one batch and seals the completed target in the same
199
+ component mutation. It returns `{ status: "prepared", group, isDone }`. Continue
200
+ with unchanged group options while `isDone` is false; do not run provider effects
201
+ until it is true. Sealed or finished replay returns the saved group without
202
+ another reservation. Batch identities use a persisted sequence, independent of
203
+ pending or completed reservation counts. The optional limit must be 1 through
204
+ 100 and can change between bounded calls.
205
+
206
+ A competing boundary returns `{ status: "conflict", reason: "scope_busy",
207
+ retryable: false }`. Changed group identity or a legacy operation-key collision
208
+ returns `identity_changed`; invalid scope or policy returns `rejected`. These
209
+ outcomes do not reserve anything. Read current state and let host policy decide
210
+ what to do; conflicts are not automatic retries. Existing `reserve`, `seal` and
211
+ `finish` methods remain available. Host reporting and provider execution remain
212
+ separate from preparation.
213
+
214
+ ### Importing opening recovery balances
215
+
216
+ When moving an existing ledger into the component, your server can call
217
+ `stripe.costRecovery.importClaim(ctx, { ...observation, operationKey, collectedAmount })`.
218
+ The observation includes the authorized account/scope/currency, original charge,
219
+ gross and processing fee, approved cumulative amount due and a durable revision.
220
+ `collectedAmount` is the signed amount already verified as collected before the
221
+ cutover. The component retains that opening snapshot and computes outstanding as
222
+ amount due minus the imported collection. It does not create a Stripe payment.
223
+
224
+ Quiesce the old ledger's writers and verify its invoice and payout outcomes first.
225
+ An unpaid invoice is a reservation, not a collection; an unknown provider outcome
226
+ must stay held until reconciled. Do not import those amounts as collected or
227
+ silently release them. Authorize source identity and original provider economics
228
+ in the host before invoking this server-only bookkeeping operation.
229
+
230
+ Use one stable import operation key per claim. A replay returns the current claim
231
+ even after later observations or collections, without resetting its opening
232
+ amount. Changing the opening snapshot or source binding, reusing an operation key
233
+ for another claim, importing over a normal live claim, or introducing a new
234
+ opening balance while the scope has a pending external recovery group is rejected.
235
+ Signed credit collections and currencies stay separate. New observations continue
236
+ through `recordClaim` with newer durable revisions.
237
+
238
+ ### Invoice recovery adjustments
239
+
240
+ After authorizing the seller, invoice and liability scope, reserve with
241
+ `sourceKind: "invoice"` and `sourceId: invoiceId`. Allocate bounded batches and
242
+ seal the group before calling Stripe. Then attach exactly one signed adjustment
243
+ for the entire group:
244
+
245
+ ```ts
246
+ const receipt = await recovery.attachInvoice(ctx, { ...scope, groupKey });
247
+ // Invoke from your invoice lifecycle reconciliation, and repeat bounded completion
248
+ // until isDone after payment or release.
249
+ const result = await recovery.reconcileInvoice(ctx, {
250
+ ...scope,
251
+ groupKey,
252
+ releaseUncollectible: false,
253
+ });
254
+ ```
255
+
256
+ The invoice must belong to the authorized customer account, use the same currency,
257
+ and be draft before a new item is created. The package stores its stable group
258
+ identity before the provider call, uses that identity as the idempotency key and
259
+ item metadata, and persists the resulting item ID. Every retry scans all items
260
+ on that exact invoice, recovering a successful creation even if the subsequent
261
+ database write failed or the provider idempotency key expired. A bound item that
262
+ has been deleted, changed or duplicated requires reconciliation; the package
263
+ never silently recreates it. Negative adjustments are credits. Items are not
264
+ discountable.
265
+
266
+ Your host must durably serialize provider operations for each group, including
267
+ attachment and any calls that finish or release it. Never release a reservation
268
+ after a timeout or unknown provider outcome. Draft and open invoices retain their
269
+ reservations, blocking recovery from a second payout. A verified paid invoice
270
+ commits collection; a verified void releases the obligation for a future boundary.
271
+ If an invoice is voided before its adjustment was attached, reconciliation releases
272
+ an unbound sealed group only after scanning every item on that exact invoice.
273
+ The receipt then has `invoiceItemId: null`. A missing previously bound item, or
274
+ an absent adjustment on a paid or unpaid invoice, remains an error and keeps
275
+ reservations held.
276
+ Uncollectible invoices stay reserved unless your explicit host policy passes
277
+ `releaseUncollectible: true`. Do not use that policy while another process might
278
+ retry payment on the original invoice. Subscription cancellation alone does not
279
+ prove its invoices were voided. These methods never attempt card fallback or
280
+ change a payout schedule.
281
+
282
+ For a collected invoice fully funded by one PaymentIntent, call
283
+ `rollbackInvoice(ctx, { ...scope, groupKey, revision })`. It checks the paid
284
+ invoice, completely paginates its payments, verifies the funding charge and its
285
+ refund/dispute transactions, retains the original funding economics, and records
286
+ a separate proportional rollback claim. Use a durable revision captured before
287
+ provider reconciliation, and retry the full read on revision conflicts. Original
288
+ cost claims remain intact. Multiple payments, partial allocations, mixed customer
289
+ credits and non-PaymentIntent funding return
290
+ `{ status: "not_ready", reason: "invoice_funding_allocation_required" }` without
291
+ changing claims. Provider processing costs can also return their documented
292
+ not-ready reasons. Those cases need a host-approved allocation policy rather than
293
+ guessed amounts. Invoice integration in the example is a separate migration.
294
+
295
+ Provider methods preserve the configured API version and propagate Stripe errors.
296
+ See Stripe's [invoice item creation](https://docs.stripe.com/api/invoiceitems/create)
297
+ and [invoice item pagination](https://docs.stripe.com/api/invoiceitems/list).
298
+
299
+ ### Refund and dispute processing costs
300
+
301
+ `getProcessingCostContext(ctx, { paymentIntentId, stripeAccountId? })` reads
302
+ provider costs for an authorized payment, including refunded and disputed
303
+ charges. Authorize both the payment and optional connected-account namespace in
304
+ your host. The client preserves its configured API version and provider errors;
305
+ it does not settle a sale, move money, create debt or decide which costs a seller
306
+ owes. The example's cost adapter uses this method while keeping its billing policy
307
+ in the application.
308
+
309
+ A `ready` result contains every refund and dispute, source-linked balance
310
+ transactions, signed fee adjustments and provider amounts in integer minor units.
311
+ Dates are milliseconds. `processingFee` is the original charge balance
312
+ transaction's total provider-reported fee, which can include application fees on
313
+ direct charges. Each transaction exposes `feeDetails` so your approved policy can
314
+ distinguish processor, application and other fees. A null breakdown means provider
315
+ details were unavailable; the reported total remains authoritative. Negative fee
316
+ adjustments remain credits. Failed refunds include their failure reversal instead
317
+ of counting their principal as returned.
318
+
319
+ `principalReturned` caps the combined economic refund/dispute principal at the
320
+ original gross amount. Raw signed provider transactions remain intact, including
321
+ any overlapping debits, and are not a seller debt calculation. A won dispute with
322
+ an unreinstated principal withdrawal is `not_ready`. Pending refunds, missing cost
323
+ transactions or different settlement currencies also return an explicit
324
+ `not_ready` reason instead of estimated or mixed-currency totals. Provider
325
+ pagination errors throw rather than returning partial data. Retry delayed
326
+ provider data; resolve currency conversion through an explicit host policy.
327
+
328
+ See Stripe's [balance transaction fields](https://docs.stripe.com/api/balance_transactions/object)
329
+ and [refund failure reversals](https://docs.stripe.com/api/refunds/object).
330
+
331
+ ### Optional balance-funded subscriptions
332
+
333
+ Balance funding requires an eligible connected account and Stripe's Accounts v2
334
+ balance-payment preview. It is separate from non-Connect customer-only Accounts
335
+ v2 eligibility. Keep your normal client on GA; construct a separate client with
336
+ `stripeApiVersion: STRIPE_CUSTOMER_PREVIEW_API_VERSION` for this optional feature.
337
+ `getBalanceFundingCapability()` reports whether that client is explicitly
338
+ configured. It does not claim the account has provider approval; Stripe validates
339
+ eligibility when preparing the payment method.
340
+
341
+ After authenticating the seller, authorizing the subscription, and recording
342
+ explicit recurring-debit consent in your own database:
343
+
344
+ ```ts
345
+ const preparation = await balanceStripe.prepareBalanceFunding(ctx, {
346
+ customerAccount: authorizedSellerAccountId,
347
+ stripeSubscriptionId: authorizedSubscriptionId,
348
+ consent: true,
349
+ idempotencyKey: durablePreparationRequestId,
350
+ });
351
+ // Persist this immutable server-side record BEFORE enabling balance payments.
352
+ await savePreparationAndConsent(preparation);
353
+ await balanceStripe.setBalanceFunding(ctx, {
354
+ preparation,
355
+ enabled: true,
356
+ consent: true,
357
+ idempotencyKey: durableEnableRequestId,
358
+ });
359
+ // Opt-out restores the previous default method and payment-method types.
360
+ await balanceStripe.setBalanceFunding(ctx, {
361
+ preparation: await loadPersistedPreparation(),
362
+ enabled: false,
363
+ idempotencyKey: durableDisableRequestId,
364
+ });
365
+ ```
366
+
367
+ `prepareBalanceFunding` creates/attaches a `stripe_balance` method and captures
368
+ the prior subscription settings without changing them. `setBalanceFunding`
369
+ checks subscription ownership and payment-method ownership, then changes the
370
+ settings or recognizes that the requested state already exists. Null prior
371
+ settings restore inheritance from the customer's settings. External source
372
+ changes cause an error instead of being overwritten. Provider errors are
373
+ preserved. Never accept restoration records or account IDs from an unauthenticated
374
+ browser as authority.
375
+
376
+ The example now uses component-owned
377
+ [`balanceFundingWorkflow`](balance-funding-workflow.md) for preparation,
378
+ apply, receipts and reconciliation. Its host adapter keeps consent and request
379
+ references; it no longer writes a second financial operation ledger. Existing
380
+ example installations should follow the
381
+ [cutover runbook](example-balance-funding-cutover.md) before retiring legacy
382
+ records. The stateless methods above remain supported.
383
+
384
+ When using those stateless methods, serialize changes per subscription in the host. Persist the operation identity
385
+ before the provider call, reuse it after a timeout or host write failure, and use
386
+ a new identity for each later enable/disable cycle. An unfinished operation must prevent an opposite change from racing it; retry
387
+ the pending change first. Preserve the preparation through retries. Keys must be
388
+ nonempty, contain no line breaks, and be at most 247 characters because the package
389
+ adds phase suffixes. Stripe's idempotency retention window still applies.
390
+
391
+ Only eligible processing earnings can fund these subscriptions; top-ups cannot.
392
+ Insufficient available balance in the invoice currency fails payment and does not
393
+ automatically charge a saved card. Handle `invoice.payment_failed` in your host
394
+ and offer an explicit alternate-method recovery flow. These operations neither
395
+ pay an overdue invoice nor change payout schedules. See Stripe's
396
+ [balance-payment eligibility, approval and recovery guidance](https://docs.stripe.com/payments/pay-with-balance).
397
+
398
+ ### Upcoming invoice preview
399
+
400
+ Authorize the customer account and subscription in your host action, then call
401
+ `stripe.getUpcomingInvoicePreview(ctx, { customerAccount, stripeSubscriptionId })`.
402
+ The method verifies that the subscription belongs to that account and uses your
403
+ configured Stripe API version. It retrieves every invoice line, returns integer
404
+ minor-unit amounts and millisecond timestamps, and preserves Stripe errors,
405
+ including unavailable previews. Failed pagination throws instead of returning a
406
+ partial estimate. `nextBillingAt` uses Stripe's next payment attempt, trial end,
407
+ or earliest subscription-item renewal date, in that order.
408
+
409
+ Pass the result through an authenticated callback to the React `InvoiceEstimate`
410
+ component. It displays the provider `total` without summing line amounts. Totals
411
+ can include discounts, tax or credits; `amountDue` can differ from `total` because
412
+ of customer balances. Previews are estimates, not payable invoices. Application
413
+ recovery costs and credits remain host-owned policy. See Stripe's
414
+ [invoice preview documentation](https://docs.stripe.com/api/invoices/create_preview).
415
+
416
+ ### Invoice, Payment Method, and Payout
417
+
418
+ | Method | Description |
419
+ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
420
+ | `getInvoice(ctx, { stripeInvoiceId })` | Get invoice by Stripe invoice ID |
421
+ | `getInvoiceByStripeId(ctx, { stripeInvoiceId })` | Alias for getInvoice |
422
+ | `listInvoices(ctx, { stripeAccountId?, userId?, subscriptionId?, status?, limit? })` | List invoices with optional filters |
423
+ | `listInvoicesByUser(ctx, { userId })` | List all invoices for a user |
424
+ | `getInvoiceFromStripe(ctx, { stripeInvoiceId })` | Fetch latest invoice data directly from Stripe |
425
+ | `getUpcomingInvoicePreview(ctx, { customerAccount, stripeSubscriptionId })` | Preview the next invoice with complete lines, provider totals and millisecond dates |
426
+ | `listPaymentMethods(ctx, { stripeCustomerId, type? })` | List saved payment methods |
427
+ | `attachPaymentMethod(ctx, { paymentMethodId, stripeCustomerId })` | Attach a payment method to a customer account |
428
+ | `detachPaymentMethod(ctx, { paymentMethodId })` | Detach a payment method |
429
+ | `setDefaultPaymentMethod(ctx, { stripeAccountId, paymentMethodId })` | Not supported for V2 accounts — throws with guidance to use `createBillingPortalSession()` |
430
+ | `createBillingPortalSession(ctx, { stripeAccountId, returnUrl })` | Create a Stripe billing portal session URL |
431
+ | `createPayout(ctx, { stripeAccountId, amount, currency?, metadata? })` | Create a payout for a Connect account |
432
+ | `getPayout(ctx, { payoutId })` | Get payout by component document ID |
433
+ | `listPayouts(ctx, { stripeAccountId?, status?, limit? })` | List payouts with optional filters |
434
+
435
+ ### Refund and Dispute
436
+
437
+ | Method | Description |
438
+ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
439
+ | `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` |
440
+ | `getRefundByStripeId(ctx, { stripeRefundId })` | Get a refund by Stripe refund ID |
441
+ | `listRefunds(ctx, { stripeAccountId?, stripePaymentIntentId?, status?, limit? })` | List refunds with optional filters |
442
+ | `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 |
443
+ | `getDisputeByStripeId(ctx, { stripeDisputeId })` | Get a dispute by Stripe dispute ID |
444
+ | `getDisputeWithCountdown(ctx, { stripeDisputeId })` | Get a dispute plus its evidence-due countdown (`daysRemaining`, `isOverdue`) |
445
+ | `listDisputes(ctx, { stripeAccountId?, stripePaymentIntentId?, status?, limit? })` | List disputes with optional filters |
446
+ | `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 |
447
+ | `updateDispute(ctx, { stripeDisputeId, evidence?, metadata?, submit?, stripeAccountId? })` | Submit/stage dispute evidence (`submit: true` finalizes the response) |
448
+ | `closeDispute(ctx, { stripeDisputeId, stripeAccountId? })` | Accept a dispute (concede the chargeback) — irreversible |
449
+ | `reverseTransfers(ctx, { sourceChargeId, percent?, amount? })` | Reverse split/destination transfers for a charge (the primitive behind automatic dispute clawback; also callable manually) |
450
+
451
+ `uploadDisputeEvidence` shipped in [0.14.0](https://github.com/FantasticDevHQ/better-stripe/releases/tag/v0.14.0).
452
+ Call it from an authenticated server adapter with a session-derived actor. A seller
453
+ can upload only for a dispute whose sale belongs to their merchant account.
454
+
455
+ ```ts
456
+ const { stripeFileId } = await stripe.uploadDisputeEvidence(ctx, {
457
+ stripeDisputeId,
458
+ actor: { type: "seller", accountId: authorizedSellerAccountId },
459
+ field: "customer_communication",
460
+ file: {
461
+ data: evidenceBytes, // Uint8Array loaded from authorized private storage
462
+ name: "communication.pdf",
463
+ type: "application/pdf",
464
+ },
465
+ });
466
+ ```
467
+
468
+ The API accepts nonempty PDF, JPEG or PNG bytes up to 5,000,000 bytes, with a
469
+ matching MIME type and file signature. Stripe validates the complete document.
470
+ Authorization runs before upload and again before attachment. Only the returned
471
+ provider file ID is bound to the chosen evidence field, with explicit
472
+ `submit: false`. The result contains `stripeFileId` and `stripeDisputeId` after
473
+ attachment succeeds. Use a separate authorized `updateDispute` call with
474
+ `submit: true` when the user explicitly finalizes evidence.
475
+
476
+ The optional `stripeAccountId` identifies the provider account owning the charge;
477
+ it is distinct from the seller actor. Resolve it server-side. Do not accept
478
+ browser-provided actors or file IDs as authorization. See the
479
+ [upload workflow guide](react-workflows.md#dispute-evidence-uploads-and-onboarding-navigation)
480
+ for errors, retries and storage/transport limits.
481
+
482
+ Refunds denormalize cumulative state onto the linked `payments` row (`refundedAmount`, `refundStatus: "partially_refunded" | "fully_refunded"`) so "is this payment whole?" is a single read.
483
+
484
+ ### Operational
485
+
486
+ | Method | Description |
487
+ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
488
+ | `syncAllAccounts(ctx)` | Sync all V2 accounts from Stripe to component DB |
489
+ | `syncAllProducts(ctx)` | Sync all products and prices from Stripe |
490
+ | `syncAllSubscriptions(ctx)` | Sync all subscriptions from Stripe |
491
+ | `setupEventDestination(ctx, { url, eventPayload?, name?, description?, enabledEvents? })` | Create or update a V2 event destination (snapshot or thin) |
492
+ | `listEventDestinations(ctx, { limit? })` | List all V2 event destinations |
493
+ | `listWebhookEndpoints(ctx, { limit? })` | List V1 webhook endpoints |
494
+ | `createWebhookEndpoint(ctx, { url, description?, enabledEvents? })` | Create a V1 webhook endpoint |
495
+ | `webhookHandlers()` | Returns the `{ syncWebhook, asyncWebhook }` pair to export from a Convex module |
496
+
497
+ ### Standalone Function
498
+
499
+ | Function | Description |
500
+ | ------------------------------------------ | ---------------------------------------------------------- |
501
+ | `registerRoutes(http, component, options)` | Register the webhook HTTP endpoint on a Convex HTTP router |
502
+
503
+ ## Verified settlement and payout APIs
504
+
505
+ `getVerifiedSale`, `allocateSale`, `selectCommissionInvoice`, and `settleSale`
506
+ provide verified fees, fee-first allocations, durable subscription commission
507
+ terms, and recoverable execution through the component's existing transfer ledger.
508
+ `getPayoutSnapshot` supplies per-currency balances, real cursor history, and
509
+ explicitly bounded upcoming payout data. See [settlement and payout contracts](settlement.md)
510
+ for authorization, recovery, migration, and provider limitations.
511
+
512
+ Account creation (`createAccount`, `getOrCreateAccount`, `ensureCustomerAccount`),
513
+ `createCheckoutSession`, `createProduct`, and `createPrice` accept an optional `idempotencyKey`. Use one stable
514
+ account-creation key per logical account and a distinct key per checkout order.
515
+ For catalog edits, persist a request key for the logical product or immutable
516
+ price version. Retry identical parameters with the same key after a provider or
517
+ component persistence failure. Use a new key when the price amount or other
518
+ creation parameters change. Creating a new Price does not migrate existing
519
+ subscriptions; they retain their prior price until the host explicitly changes
520
+ them. Never reuse a version key for different parameters.
521
+
522
+ React `Checkout` preserves its request ID through retries; your server must
523
+ forward that identity as the SDK request option. Persist it in the host order
524
+ for recovery across reloads. Omission retains the previous SDK behavior.
525
+
526
+ Keys must be nonempty, at most 255 characters, and contain no sensitive data.
527
+ Reuse a key only with identical parameters. Stripe v1 Checkout keys can be pruned
528
+ after 24 hours; Accounts v2 deduplicates within 30 days. Maintain durable order and
529
+ account mappings beyond those windows, and reconcile ambiguous provider results
530
+ before retrying an expired key. See [v1 idempotency](https://docs.stripe.com/api/idempotent_requests)
531
+ and [v2 request semantics](https://docs.stripe.com/api-v2-overview).
532
+
533
+ `getCheckoutSessionFromStripe`, `getSubscriptionFromStripe`, and `getCouponFromStripe` read
534
+ current provider objects rather than cached component records. They are server
535
+ APIs: authorize each resource and return only the fields your browser needs.
536
+ Subscription upserts accept Stripe's `incomplete_expired` terminal status.
537
+
538
+ ### One-time intents and saved-card setup
539
+
540
+ `createPaymentIntent(ctx, { userId, customerAccount?, stripePriceId,
541
+ idempotencyKey, receiptEmail?, metadata? })` creates a card-only, platform
542
+ PaymentIntent by default. Set `paymentMethods: "automatic"` to let Stripe select
543
+ compatible methods, as in the example. It retrieves the platform price and expanded product from Stripe,
544
+ rejects inactive products/prices, recurring and nonpositive/nonfixed prices, and
545
+ derives amount and currency from the provider price. It returns only
546
+ `{ paymentIntentId, clientSecret }`. Omit `customerAccount` for a host-authorized
547
+ guest purchase. Existing Checkout Sessions integrations remain available.
548
+
549
+ `createSetupIntent(ctx, { userId, customerAccount, usage, consent: true,
550
+ idempotencyKey, metadata? })` provisions a card-only SetupIntent for a V2 customer
551
+ account, returning only `{ setupIntentId, clientSecret }`. Explicitly choose
552
+ `on_session` or `off_session` and record consent to that usage before provisioning.
553
+ Confirmation attaches the saved card after required authentication; it does not
554
+ set a subscription default. `SaveCard` from the React entrypoint supplies an
555
+ unstyled Payment Element workflow. See the [React guide](react-workflows.md#save-a-card-through-setupintent-confirmation).
556
+
557
+ Both APIs require caller idempotency keys. Persist logical request identity and
558
+ immutable inputs on the server, bind keys to the authenticated customer and
559
+ operation, and reuse the same key on retries. Stripe's bounded idempotency window
560
+ is not a durable order store. Authenticate in the host adapter, authorize the
561
+ selected price/product and customer, and supply server-selected metadata. The
562
+ package checks a supplied customer account's persisted `userId` ownership,
563
+ protects its own attribution keys and strips the reserved `bs*` namespace. Never
564
+ accept browser-provided amounts, user IDs or metadata as authorization.
565
+
566
+ Grant paid access only after the existing verified webhook/settlement flow.
567
+ Creation and browser confirmation are not settlement proof. Customer-account
568
+ operations require Accounts v2 support in the sandbox or merchant account; the
569
+ [customer preview guide](accounts-v2-preview.md) explains eligibility.
570
+
571
+ #### Live sandbox verification, 2026-10-15
572
+
573
+ The public intent APIs and `SaveCard` passed real Stripe test-mode verification
574
+ at commit `332d49c`, merged in [PR #166](https://github.com/FantasticDevHQ/better-stripe/pull/166).
575
+ Browser 3DS failure, retry on the same SetupIntent, and successful authentication
576
+ passed. A card saved for `off_session` use then succeeded on a later PaymentIntent;
577
+ all successful test payments were refunded. Provider checks also covered customer
578
+ ownership, redisplay permission, idempotent retries and declines.
579
+
580
+ The initial `non_connect_platform_accounts_v2_access_blocked` error was resolved
581
+ by enabling Connect in the intended Connect test sandbox. The browser flow used
582
+ `2026-09-30.endive`; separate API checks also passed on `2026-09-30.preview`.
583
+ This does not establish customer-only preview eligibility for another account.
584
+ See the [sandbox setup findings](accounts-v2-preview.md#connect-sandbox-setup-findings-2026-10-15),
585
+ [authentication and reuse results](react-workflows.md#live-authentication-and-reuse-results-2026-10-15),
586
+ and [uploaded screenshots and provider records](https://github.com/FantasticDevHQ/better-stripe/pull/166#issuecomment-6185124292).