@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.
- package/CHANGELOG.md +26 -0
- package/README.md +39 -1748
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.js +12 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.js.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.js +12 -1
- package/dist/client/connect/payoutExecutionTestHelpers.js.map +1 -1
- package/dist/client/usage/boundaries.d.ts +132 -0
- package/dist/client/usage/boundaries.d.ts.map +1 -0
- package/dist/client/usage/boundaries.js +43 -0
- package/dist/client/usage/boundaries.js.map +1 -0
- package/dist/client/usage/contracts.d.ts +59 -0
- package/dist/client/usage/contracts.d.ts.map +1 -0
- package/dist/client/usage/contracts.js +63 -0
- package/dist/client/usage/contracts.js.map +1 -0
- package/dist/client/usage/index.d.ts +7 -0
- package/dist/client/usage/index.d.ts.map +1 -0
- package/dist/client/usage/index.js +4 -0
- package/dist/client/usage/index.js.map +1 -0
- package/dist/client/usage/records.d.ts +50 -0
- package/dist/client/usage/records.d.ts.map +1 -0
- package/dist/client/usage/records.js +54 -0
- package/dist/client/usage/records.js.map +1 -0
- package/docs/README.md +58 -0
- package/docs/architecture.md +80 -0
- package/docs/client-api.md +586 -0
- package/docs/configuration.md +51 -0
- package/docs/development.md +114 -0
- package/docs/marketplace.md +165 -0
- package/docs/metered-usage.md +289 -37
- package/docs/metering-setup.md +183 -0
- package/docs/overview.md +140 -0
- package/docs/react-api.md +284 -0
- package/docs/releasing.md +19 -0
- package/docs/testing.md +52 -0
- package/docs/webhooks.md +259 -0
- package/package.json +17 -2
- package/src/client/connect/payoutAdoptionTestHelpers.ts +17 -1
- package/src/client/connect/payoutExecutionTestHelpers.ts +17 -1
- package/src/client/transferContinuation.test.ts +2 -6
- package/src/client/usage/boundaries.test.ts +136 -0
- package/src/client/usage/boundaries.ts +182 -0
- package/src/client/usage/contracts.test.ts +145 -0
- package/src/client/usage/contracts.ts +79 -0
- package/src/client/usage/index.ts +34 -0
- package/src/client/usage/records.ts +76 -0
- package/src/test.ts +17 -1
- package/src/vite-env.d.ts +5 -1
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Configuration
|
|
2
|
+
|
|
3
|
+
### Environment Variables
|
|
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. |
|
|
11
|
+
|
|
12
|
+
### Wiring component env vars
|
|
13
|
+
|
|
14
|
+
The component declares `STRIPE_SECRET_KEY` as a required environment variable in
|
|
15
|
+
its `convex.config.ts`. Convex isolates a component's functions from the
|
|
16
|
+
deployment's `process.env`, so setting the var with `convex env set` is **not**
|
|
17
|
+
enough on its own — the installing app must provide it to the component via
|
|
18
|
+
`app.use`:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// convex/convex.config.ts
|
|
22
|
+
import { defineApp } from "convex/server";
|
|
23
|
+
import { v } from "convex/values";
|
|
24
|
+
import betterStripe from "@fantastic.dev/better-stripe/convex.config";
|
|
25
|
+
|
|
26
|
+
const app = defineApp({
|
|
27
|
+
env: { STRIPE_SECRET_KEY: v.string() },
|
|
28
|
+
});
|
|
29
|
+
// Pass by reference so the component always sees the deployment's current value
|
|
30
|
+
// (set via `convex env set STRIPE_SECRET_KEY ...`).
|
|
31
|
+
app.use(betterStripe, {
|
|
32
|
+
env: { STRIPE_SECRET_KEY: app.env.STRIPE_SECRET_KEY },
|
|
33
|
+
});
|
|
34
|
+
export default app;
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The webhook secrets (`STRIPE_WEBHOOK_SECRET`, `STRIPE_WEBHOOK_SECRET_V2`) are read
|
|
38
|
+
by the app's `registerRoutes`, not the component, so they only need to be set in
|
|
39
|
+
the deployment env — no `app.use` wiring required.
|
|
40
|
+
|
|
41
|
+
### Stripe API Version
|
|
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.
|
|
44
|
+
|
|
45
|
+
### SDK Management
|
|
46
|
+
|
|
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.
|
|
48
|
+
|
|
49
|
+
## TypeScript setup
|
|
50
|
+
|
|
51
|
+
> **TypeScript 6+:** `compilerOptions.types` now defaults to `[]`, so installed `@types/*` packages are no longer included automatically. If Convex's typecheck reports `Cannot find name 'process'` for your `process.env` reads, add `"types": ["node"]` to `convex/tsconfig.json` and make sure `@types/node` is a devDependency.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Development guide
|
|
2
|
+
|
|
3
|
+
### Development toolchain
|
|
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
|
|
8
|
+
[the example setup guide](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md).
|
|
9
|
+
|
|
10
|
+
The BetterStripe example separates visitor, customer, affiliate, seller, and
|
|
11
|
+
platform-admin workflows. Fresh fictional Maya and Sasha stores explicitly
|
|
12
|
+
configure 20% Forever referral commissions to fund the affiliate payout example;
|
|
13
|
+
ordinary stores still default to zero, and seed reruns preserve later edits.
|
|
14
|
+
Its resumable Stripe sandbox fixtures populate sales,
|
|
15
|
+
referrals, refunds, disputes, subscriptions, and payouts. Seller plans include
|
|
16
|
+
monthly billing, actual Stripe fee reconciliation, and refund/dispute cost
|
|
17
|
+
recovery. The example also demonstrates optional balance-funded subscriptions
|
|
18
|
+
using Stripe's Accounts v2 preview. See the setup guide for consent requirements,
|
|
19
|
+
renewal tests, and payment-recovery limitations.
|
|
20
|
+
|
|
21
|
+
The example compares via API views, BetterStripe React components, Stripe Connect
|
|
22
|
+
embeds, and hosted billing where supported. Its checkout chooser demonstrates
|
|
23
|
+
Hosted Checkout, Embedded Checkout, custom Checkout Sessions with Payment Element,
|
|
24
|
+
Payment Intents with Payment Element, and the preview Embedded Checkout Form,
|
|
25
|
+
with pros and cons for each. `createCheckoutSession` accepts `uiMode` values
|
|
26
|
+
`"redirect"`, `"embedded"`, `"custom"`, and `"form"`; the latter two map to Stripe's
|
|
27
|
+
`elements` and preview `form` modes. See [the integration examples](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md#compare-integration-styles).
|
|
28
|
+
|
|
29
|
+
Admins can configure store-plan monthly prices and sale fees. Monthly price changes
|
|
30
|
+
create new Stripe Prices; existing store subscriptions keep their current price.
|
|
31
|
+
Affiliate payouts accept percentages or fixed amounts in the sale currency, with
|
|
32
|
+
optional price, product, store, plan, and platform defaults. Unconfigured payouts
|
|
33
|
+
are zero. Subscription commission terms are **Forever** or **One-time**, with
|
|
34
|
+
Forever as the default. The example saves the selected term in Stripe subscription
|
|
35
|
+
metadata and its Convex ledger, then applies it when paid invoices settle.
|
|
36
|
+
See [affiliate configuration and testing](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md#seller-product-and-subscription-affiliate-payouts).
|
|
37
|
+
|
|
38
|
+
The public React exports include `AffiliatePayoutEditor`, `PlanPricingEditor`,
|
|
39
|
+
`Pagination`, and `useCursorPagination`. The example supplies styling through
|
|
40
|
+
render props; its backend owns authorization, rule inheritance, and transfers.
|
|
41
|
+
See [the workflow reference](react-workflows.md#percentage-or-fixed-affiliate-payouts)
|
|
42
|
+
and [the UI reuse audit](react-workflows-audit.md).
|
|
43
|
+
|
|
44
|
+
Run `pnpm run check:all` before submitting changes. It runs the build, lint,
|
|
45
|
+
formatting, typechecks, codegen drift check, tests, and repository quality gates
|
|
46
|
+
used by CI. Policy lives in `repo-gates.config.json`; measured baselines live in
|
|
47
|
+
`gates/`. Fix failures without weakening the gates or raising existing budgets.
|
|
48
|
+
|
|
49
|
+
Coverage checks enforce the committed floors in `gates/coverage-budgets.json`.
|
|
50
|
+
`pnpm run check:coverage` and `pnpm run check:all` never edit that file or fail
|
|
51
|
+
because coverage improved. Ordinary feature PRs should leave the budget file alone.
|
|
52
|
+
|
|
53
|
+
The [weekly coverage workflow](https://github.com/FantasticDevHQ/better-stripe/actions/workflows/coverage-ratchet.yml)
|
|
54
|
+
runs Mondays at 09:17 Asia/Bangkok, 02:17 UTC. It runs every repository gate on
|
|
55
|
+
`main`, then captures earned floor increases of at least **0.05 percentage points**
|
|
56
|
+
per metric. It keeps the existing 0.5-point margin below measured coverage and
|
|
57
|
+
never lowers a floor. Eligible metrics capture their full earned increase; this
|
|
58
|
+
is a minimum useful change, not a forced weekly increase. Smaller gains accumulate
|
|
59
|
+
until a later run. Failed checks and old reports cannot authorize any update.
|
|
60
|
+
|
|
61
|
+
The workflow maintains one ready-for-review PR on `codex/coverage-ratchet`, changing
|
|
62
|
+
only the coverage budget file. Its description records measured coverage, old and
|
|
63
|
+
proposed floors, and a link to the full gate run. It reuses the existing release
|
|
64
|
+
GitHub App configuration so the generated PR runs normal CI. Auto-merge matches
|
|
65
|
+
the exact generated head and waits for all required checks under the existing
|
|
66
|
+
branch protections, without bypass actors. The helper checks the app author,
|
|
67
|
+
branch, repository, changed files, policy metadata, and measured proposal before
|
|
68
|
+
enabling auto-merge. Do not add unrelated commits to this managed branch.
|
|
69
|
+
|
|
70
|
+
Use **Run workflow** on `main` for an additional full measurement between weekly
|
|
71
|
+
runs. Once merged, this workflow becomes available to the scheduler and manual
|
|
72
|
+
dispatch. Locally, `node scripts/check-coverage.mjs --ratchet` runs the same complete
|
|
73
|
+
gates before proposing a budget update. It accepts no test filters, partial mode,
|
|
74
|
+
or skipped execution. `pnpm test:coverage` generates a report only.
|
|
75
|
+
|
|
76
|
+
Builds and typechecks use TypeScript 7 (`@typescript/native` aliases
|
|
77
|
+
`typescript`). ESLint and Convex code generation still need the TypeScript 6
|
|
78
|
+
API, so `typescript` aliases Microsoft's `@typescript/typescript6` compatibility
|
|
79
|
+
package. Keep both aliases when updating dependencies, as described in
|
|
80
|
+
[Microsoft's migration guide](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0).
|
|
81
|
+
|
|
82
|
+
Stripe 23 targets API version `2026-09-30.endive`. Account links now collect
|
|
83
|
+
requirements without a `configurations` parameter; callers can still pass the
|
|
84
|
+
legacy option, but it is not sent to Stripe. See the
|
|
85
|
+
[Stripe API changelog](https://docs.stripe.com/changelog) before upgrading an
|
|
86
|
+
existing integration to this API version.
|
|
87
|
+
|
|
88
|
+
### Regenerating codegen
|
|
89
|
+
|
|
90
|
+
The component ships committed Convex codegen output at `src/component/_generated/{api,component,dataModel,server}.ts` — consumers reach the bindings via the `./_generated/component` subpath export. The example app also commits its own codegen at `example/convex/_generated/`. Running `pnpm dev` (which wraps `convex dev`) regenerates these automatically when the schema or function definitions change, but only against the live dev deployment and only while the dev server is watching.
|
|
91
|
+
|
|
92
|
+
The example resolves the workspace package through `dist/`. After changing
|
|
93
|
+
component source, regenerate library bindings with `pnpm codegen:lib`, run
|
|
94
|
+
`pnpm build`, then deploy the rebuilt component from the example directory with
|
|
95
|
+
`pnpm exec convex dev --once`. Run `pnpm codegen:example` afterward. Code generation
|
|
96
|
+
alone does not prove that a newly added function is mounted; invoke a representative
|
|
97
|
+
query or action against the development deployment before running financial tests.
|
|
98
|
+
|
|
99
|
+
If you add, remove, or rename a query/mutation/action on a branch without the dev server watching — or after a rebase — regenerate explicitly before committing:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
pnpm codegen # regen the library component + example app
|
|
103
|
+
pnpm codegen:lib # regen src/component/_generated only
|
|
104
|
+
pnpm codegen:example # regen example/convex/_generated only
|
|
105
|
+
```
|
|
106
|
+
|
|
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.
|
|
108
|
+
|
|
109
|
+
**CI gate.** Two layers verify the committed files are not stale:
|
|
110
|
+
|
|
111
|
+
1. **Structural drift check** (`pnpm codegen:check`, always runs in CI): two independent scans, each checking both directions (every source export appears in the generated file, and every generated entry still has a matching source), neither needing a deployment:
|
|
112
|
+
- Library component — scans `src/component/**/*.{queries,mutations,actions}.ts` and verifies every exported function appears in `src/component/_generated/component.ts`. The reverse direction also flags a stale entry left behind by a _deleted_ query/mutation/action. The export-detection regex intentionally matches only direct `query(...)`/`mutation(...)`/`action(...)` exports — not wrapper or re-export forms like `customQuery(...)` (convex-helpers) or `export { fn as name }`, which this component has none of today; widen the regex (and the reverse scan) rather than assuming that stays true.
|
|
113
|
+
- Example app — scans `example/convex/**/*.ts` and verifies every source module is imported and registered in `example/convex/_generated/api.ts`. Catches the common case of adding a new `example/convex/<module>.ts` (or nested file like `example/convex/lib/<module>.ts`) without regenerating. The reverse direction likewise flags a stale import left behind by a _deleted_ module.
|
|
114
|
+
2. **Authoritative regen-and-diff** (runs in CI when `CONVEX_DEPLOYMENT` is configured): runs `pnpm codegen` against the configured dev deployment and fails if `git diff` shows changes. Catches every drift case, including validator-shape changes the structural check can't see. To enable on a fork, set the `CONVEX_DEPLOYMENT` repo secret to a dev deployment name and authorize the CI runner — see Convex's [GitHub Actions guide](https://docs.convex.dev/production/integration/deployments#github-actions).
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# Marketplace economics
|
|
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).
|
|
4
|
+
|
|
5
|
+
### Fee Model
|
|
6
|
+
|
|
7
|
+
`PlatformFeeConfig` is the platform's take on a sale:
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
type FeeTier = { upTo: number | null; percent: number; fixed?: number };
|
|
11
|
+
type PlatformFeeConfig = {
|
|
12
|
+
percent: number; // base percentage (0–100)
|
|
13
|
+
fixed?: number; // optional fixed surcharge, minor units
|
|
14
|
+
tiers?: FeeTier[]; // optional; overrides the base by charge amount
|
|
15
|
+
};
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Configure a default at construction (`new BetterStripe(component, { platformFee: {...} })`), and/or pass a per-call `fee` override (type `FeeOverride`, same shape as `PlatformFeeConfig`) to `createCheckoutSession`/`createSubscription` — the override wins. `stripe.resolveFee(override?)` resolves the effective config the same way the client does internally, and `stripe.platformFee` reads the configured default back.
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { computeFee } from "@fantastic.dev/better-stripe";
|
|
22
|
+
|
|
23
|
+
const { feeAmount, percentApplied, fixedApplied, tier } = computeFee(2999, {
|
|
24
|
+
percent: 10,
|
|
25
|
+
fixed: 30,
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`computeFee(amount, config)` picks the first tier whose `upTo` covers the amount (a final `upTo: null` is the catch-all), rounds half-up, and caps the fee at the charge amount. It's exported so an app can preview "platform keeps $X" client-side before checkout.
|
|
30
|
+
|
|
31
|
+
**How the fee is charged** depends on shape and charge type:
|
|
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).
|
|
36
|
+
|
|
37
|
+
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
|
+
|
|
39
|
+
### Split Engine
|
|
40
|
+
|
|
41
|
+
For a sale split across multiple recipients (store + affiliate(s)), pass `split` instead of `destinationAccountId` to `createCheckoutSession`/`createSubscription`:
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
type SplitRecipient = {
|
|
45
|
+
destinationAccountId: string;
|
|
46
|
+
role: "store" | "affiliate" | "other";
|
|
47
|
+
amount?: number; // exactly one of amount/percent
|
|
48
|
+
percent?: number; // percent of the gross charge amount
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
await stripe.createCheckoutSession(ctx, {
|
|
52
|
+
userId,
|
|
53
|
+
stripePriceId,
|
|
54
|
+
mode: "payment",
|
|
55
|
+
returnUrl,
|
|
56
|
+
split: [
|
|
57
|
+
{ destinationAccountId: storeAccountId, role: "store", percent: 80 },
|
|
58
|
+
{
|
|
59
|
+
destinationAccountId: affiliateAccountId,
|
|
60
|
+
role: "affiliate",
|
|
61
|
+
percent: 10,
|
|
62
|
+
},
|
|
63
|
+
],
|
|
64
|
+
fee: { percent: 10 }, // per-call override; omit to use the configured default
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- **A single-recipient `split`** is treated as a plain destination charge (equivalent to `destinationAccountId`) — `application_fee_percent`/`application_fee_amount` applies as above.
|
|
69
|
+
- **A multi-recipient `split`** routes via **separate charges & transfers**: the platform charges the full amount, then the webhook engine (`createSplitTransfers`, on `payment_intent.succeeded`/`invoice.paid`) creates one Stripe `Transfer` per recipient with `source_transaction` linkage. No `application_fee` is used on this path — the platform's cut is the remainder after transfers.
|
|
70
|
+
- **Subscriptions** re-run the split on every billing cycle (each invoice re-reads the subscription's `split`/`feeConfig` markers), so per-cycle recipient amounts stay in sync with the config at charge time.
|
|
71
|
+
|
|
72
|
+
The core math is exported for previewing splits client-side:
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
import { computeSplit } from "@fantastic.dev/better-stripe";
|
|
76
|
+
|
|
77
|
+
const result = computeSplit(10000, { percent: 10 }, [
|
|
78
|
+
{ destinationAccountId: "acct_store", role: "store", percent: 80 },
|
|
79
|
+
{ destinationAccountId: "acct_affiliate", role: "affiliate", percent: 10 },
|
|
80
|
+
]);
|
|
81
|
+
// result.transfers: [{ destinationAccountId, role, amount }, ...]
|
|
82
|
+
// result.platformFee: the resolver's cut; result.platformRetained: amount − sum(transfers)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`computeSplit` throws if the transfers plus the platform fee would exceed the charge amount — the platform is always left with at least its configured cut. Any rounding remainder stays with the platform.
|
|
86
|
+
|
|
87
|
+
### Payouts
|
|
88
|
+
|
|
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).
|
|
90
|
+
|
|
91
|
+
### Disputes
|
|
92
|
+
|
|
93
|
+
The platform is merchant of record, so a chargeback lands on the platform's Stripe account even for a seller's sale. The dispute pipeline (all webhook-driven, on `charge.dispute.*`):
|
|
94
|
+
|
|
95
|
+
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
|
+
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").
|
|
98
|
+
|
|
99
|
+
Sellers respond to their own disputes without platform staff involvement, via an embedded Stripe Connect session:
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
// server: expose the account session
|
|
103
|
+
export const createDisputeSession = action({
|
|
104
|
+
args: { stripeAccountId: v.string() },
|
|
105
|
+
handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
|
|
106
|
+
});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`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
|
+
|
|
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.
|
|
112
|
+
|
|
113
|
+
For commissions tracked by the recovery ledger, generic manual reversal is
|
|
114
|
+
rejected. Use `createRefund` for a real refund or `stripe.affiliateRecovery.retry`
|
|
115
|
+
for a recovery operation, so existing offsets and uncertain receipts remain
|
|
116
|
+
coordinated.
|
|
117
|
+
|
|
118
|
+
### Affiliate commission accounting
|
|
119
|
+
|
|
120
|
+
The component stores each original affiliate transfer's commission and currency,
|
|
121
|
+
links available payment/invoice references, and separates finalized obligations,
|
|
122
|
+
provisional dispute exposure, reserved slices, and confirmed reversals. New
|
|
123
|
+
commission reversal operations reconcile exact Stripe receipts after interrupted
|
|
124
|
+
ledger writes. Percentage and fixed commissions use the original allocated
|
|
125
|
+
amount, with deterministic rounding in integer currency units.
|
|
126
|
+
|
|
127
|
+
Trusted host APIs under `components.betterStripe.settlement` provide
|
|
128
|
+
`queries.listAffiliateObligations` and
|
|
129
|
+
`mutations.migrateAffiliateObligations`. Authorize account ownership before
|
|
130
|
+
exposing snapshots and restrict migration to operators. Existing rows with
|
|
131
|
+
unattributed reversal balances require reconciliation. See the
|
|
132
|
+
[API and migration guide](affiliate-clawbacks.md#migration-and-operator-reconciliation).
|
|
133
|
+
|
|
134
|
+
Insufficient-balance debt is offset atomically against eligible future commissions
|
|
135
|
+
in the same currency before transfer creation. Dispute wins restore only actual
|
|
136
|
+
reversals/offsets and retain independent refunds. `stripe.affiliateRecovery`
|
|
137
|
+
provides snapshots, history, operator retry and legacy review; the reusable
|
|
138
|
+
`AffiliateRecovery`/`AffiliateRecoveryHistory` views consume those records.
|
|
139
|
+
|
|
140
|
+
Affiliate payouts require a stable idempotency key and pass an atomic debt and
|
|
141
|
+
reservation gate. An optional `minimumAmount` applies a host-authorized currency
|
|
142
|
+
minimum; it is not a discovered provider floor. Transfer reversal does not recall
|
|
143
|
+
a completed bank payout, Stripe-managed automatic bank payouts remain outside
|
|
144
|
+
this gate, and Global Payouts is unsupported. See the guide for account capability
|
|
145
|
+
checks, maintenance jobs and live sandbox verification requirements.
|
|
146
|
+
|
|
147
|
+
### Refunds and Statement Descriptors
|
|
148
|
+
|
|
149
|
+
`createRefund(ctx, { stripePaymentIntentId?, stripeChargeId?, amount?, reason?, refundApplicationFee?, reverseTransfer?, ... })` issues a Stripe refund with marketplace semantics, both defaulting **on**:
|
|
150
|
+
|
|
151
|
+
- `refundApplicationFee` — return the platform's application fee pro-rata with the refund (destination charges only; Stripe pro-rates partial refunds automatically).
|
|
152
|
+
- `reverseTransfer` — pull the refunded amount back from the destination account (destination charges only; also pro-rated for partials).
|
|
153
|
+
|
|
154
|
+
Stripe hard-errors if either flag is sent for a charge that doesn't carry an application fee / destination transfer, so `createRefund` resolves the charge first and only sends each flag when the charge can honor it. **Split (separate-charges) sales carry neither** — those go through the same charge, so their clawback is webhook-driven: on `refund.created`/`.updated`, `reverseTransfersForRefund` reverses each recipient's ledger leg pro-rata to the cumulative amount of live refunds whose status is `succeeded`. Pending, action-required, failed, and canceled refunds are excluded; `charge.amount_refunded` alone can include pending refunds. Affiliate legs converge on the larger successful-refund or dispute exposure, capped at the original commission, so the same principal is not recovered twice. A separate `application_fee.refunded` handler keeps the linked payment's `feeCollectedAmount`/`feeRefundedAmount` in sync. The `refunds` table and the linked `payments` row update as the corresponding webhooks arrive; `createRefund` itself returns only the new refund id.
|
|
155
|
+
|
|
156
|
+
Per-store statement descriptors make destination charges recognizable on a buyer's card statement (`PLATFORMPREFIX* SUFFIX`):
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
await stripe.setAccountStatementDescriptor(ctx, {
|
|
160
|
+
stripeAccountId,
|
|
161
|
+
statementDescriptor: "ACME STORE", // or null to clear
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Validated against Stripe's rules (`validateStatementDescriptorSuffix`: 1–22 chars, at least one Latin letter, no `< > \ ' " *`, no non-Latin — rejects rather than truncates) before writing. Resolution order per charge: the store's stored suffix → the platform's configured `statementDescriptorSuffix` default (constructor option) → none. One-time payments set the suffix directly on the PaymentIntent at checkout. Store-owned products carry the descriptor for subscriptions' first charges; the webhook processor sets it on later invoices. Refresh existing products with `updateProduct` after changing a store's descriptor.
|