@fantastic.dev/better-stripe 0.50.1 → 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,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,96 @@
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
+ Successful full coverage checks automatically raise the floors in
50
+ `gates/coverage-budgets.json`. Run `pnpm run check:coverage` or
51
+ `pnpm run check:all`, then commit any budget changes. Each metric retains the
52
+ existing 0.5 percentage point margin below its measured baseline, and floors
53
+ never decrease. Failed checks leave the budgets untouched. CI checks the same
54
+ ratchet and fails if an improvement has not been committed. `pnpm test:coverage`
55
+ only generates the report; filtered or skipped runs cannot update floors through
56
+ the automatic ratchet.
57
+
58
+ Builds and typechecks use TypeScript 7 (`@typescript/native` aliases
59
+ `typescript`). ESLint and Convex code generation still need the TypeScript 6
60
+ API, so `typescript` aliases Microsoft's `@typescript/typescript6` compatibility
61
+ package. Keep both aliases when updating dependencies, as described in
62
+ [Microsoft's migration guide](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0).
63
+
64
+ Stripe 23 targets API version `2026-09-30.endive`. Account links now collect
65
+ requirements without a `configurations` parameter; callers can still pass the
66
+ legacy option, but it is not sent to Stripe. See the
67
+ [Stripe API changelog](https://docs.stripe.com/changelog) before upgrading an
68
+ existing integration to this API version.
69
+
70
+ ### Regenerating codegen
71
+
72
+ 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.
73
+
74
+ The example resolves the workspace package through `dist/`. After changing
75
+ component source, regenerate library bindings with `pnpm codegen:lib`, run
76
+ `pnpm build`, then deploy the rebuilt component from the example directory with
77
+ `pnpm exec convex dev --once`. Run `pnpm codegen:example` afterward. Code generation
78
+ alone does not prove that a newly added function is mounted; invoke a representative
79
+ query or action against the development deployment before running financial tests.
80
+
81
+ 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:
82
+
83
+ ```bash
84
+ pnpm codegen # regen the library component + example app
85
+ pnpm codegen:lib # regen src/component/_generated only
86
+ pnpm codegen:example # regen example/convex/_generated only
87
+ ```
88
+
89
+ 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.
90
+
91
+ **CI gate.** Two layers verify the committed files are not stale:
92
+
93
+ 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:
94
+ - 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.
95
+ - 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.
96
+ 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.
@@ -0,0 +1,123 @@
1
+ # Metered usage feasibility
2
+
3
+ Status: investigation in progress, reviewed 2026-10-18. BetterStripe does not yet
4
+ expose metered billing APIs. The provider, first billable unit and pricing model
5
+ must be selected before implementing provider-specific catalog, delivery or UI.
6
+ This document records the compatibility questions and repeatable access preflight.
7
+ It does not claim a successful billing sandbox run.
8
+
9
+ ## Existing integration constraints
10
+
11
+ BetterStripe subscriptions use Accounts v2 `customer_account` identities through
12
+ the platform Stripe client. See `src/client/billing/subscriptions.ts` and
13
+ [financial ownership](financial-ownership.md). Adding a separate v1 Customer is a
14
+ new identity/payment-method mapping contract, not an interchangeable identifier.
15
+ Existing fixed-price subscriptions, checkout and settlement must keep working.
16
+
17
+ Hosts authorize actors, payers and sellers and decide which activity is billable.
18
+ BetterStripe will own durable acceptance, deduplication, delivery and reconciliation.
19
+ A provider receipt cannot authorize a tenant or prove that usage was invoiced.
20
+ Seller and affiliate settlement must continue to use verified paid-invoice
21
+ proceeds and original payment provenance.
22
+
23
+ ## Provider comparison
24
+
25
+ | Concern | Stripe Billing Meters | Metronome with Stripe |
26
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
27
+ | Provider guidance | Stripe directs new usage integrations to Metronome, including existing flat-rate subscriptions adding usage | Recommended evaluation path for new usage integrations |
28
+ | Credentials | Existing Stripe key, subject to permissions and API access | Separate Metronome sandbox/account token and explicit Stripe integration enrollment |
29
+ | Payer identity | Guide maps meter payloads to Stripe Customer IDs; installed Stripe 23.0.0 meter types expose `by_id` only | Documented invoice delivery configuration uses `stripe_customer_id` with a `cus_` ID |
30
+ | Accounts v2 | `acct_` payer ingestion and invoice identity remain unverified | `customer_account` invoice delivery remains unverified; ingest aliases alone do not establish payment identity |
31
+ | Connect | Stripe documents connected-account requests and different rate limits; this does not prove a platform-owned Accounts v2 payer works in that realm | Multi-entity connections are documented; equivalence to Connect destination charges or separate transfers remains unverified |
32
+ | Catalog | Meter attached to recurring metered price | Billable metric, product, rate card and customer contract |
33
+ | Invoices | Stripe owns subscription invoicing | Metronome rates usage and pushes separate invoices to Stripe, including when recurring subscriptions coexist |
34
+ | Cost/access | Confirm account eligibility and current Billing pricing before selection | Confirm enrollment, commercial terms and extra credential acceptance before selection |
35
+
36
+ No provider is selected. Evaluate Metronome first because it is Stripe's current
37
+ recommendation. Adopt it only after proving the Accounts v2 and settlement
38
+ contracts and explicitly accepting the additional service credentials. Keep Billing
39
+ Meters as a comparison candidate, not an automatic fallback if access fails.
40
+ Neither candidate currently has proven end-to-end support in this repository.
41
+
42
+ ## Pricing-model decision
43
+
44
+ The product owner must choose pay-as-you-go, included monthly units with overages,
45
+ or prepaid credits, and name the first billable unit. Pay-as-you-go is the proposed
46
+ smallest starting scope. This proposal is not approval. Other models remain
47
+ unselected. In particular, do not create a second wallet or infer prepaid access
48
+ rules from the existing balance-funding integration.
49
+
50
+ Record the unit, decimal precision, aggregation formula, billing interval, currency,
51
+ price/version and payer/seller scope with the decision. Host limits and entitlement
52
+ rules are separate from an eventually consistent provider usage total.
53
+
54
+ ## Access preflight
55
+
56
+ From the repository root, inject a sandbox key as `STRIPE_SECRET_KEY` and run:
57
+
58
+ ```sh
59
+ node scripts/metering-feasibility.mjs
60
+ ```
61
+
62
+ Use `op run` from one persistent authorized terminal when the key is in 1Password.
63
+ Do not print or save the key. The script rejects non-test secret keys before making
64
+ any request. It makes one platform-realm GET to `/v1/billing/meters?limit=1`, pins
65
+ the repository's Stripe version and prints only status and verification flags.
66
+ It creates no meters, customers, events, subscriptions, invoices or charges.
67
+
68
+ A successful response establishes endpoint access only. A 401 or 403 is an access
69
+ failure, not evidence that a billing identity or model is unsupported. The script
70
+ has no connected-account selector and does not test that realm. It is a development
71
+ tool in the repository, not a public package API.
72
+
73
+ ## Sandbox acceptance matrix
74
+
75
+ Run the following after credentials and product decisions are available. Capture
76
+ sanitized request shapes, API versions, timestamps, status codes and assertions.
77
+ Keep secrets and raw customer/provider payloads out of evidence and workflow state.
78
+
79
+ | Scenario | Required proof | Current result |
80
+ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
81
+ | Platform Accounts v2 payer | Meter/contract creation, ingestion, aggregate and invoice all refer to the authorized payer | Unverified |
82
+ | Connected seller | Prove catalog/event realm and payer ownership, destination/transfer economics and paid-invoice provenance | Unverified |
83
+ | Non-Connect account | Prove identity and invoice flow without silently provisioning an alternative payer | Unverified |
84
+ | Duplicate delivery | Same source event and provider identifier produce one aggregate contribution | Unverified |
85
+ | Shared meter | Two subscriptions for one customer show the actual aggregation boundary; no inferred per-subscription event targeting | Unverified |
86
+ | Correction | Original event, reason and receipt retained; provider cancellation window and finalized-invoice behavior demonstrated | Unverified |
87
+ | Invoice closeout | Original event time, delayed aggregate, finalized invoice line and payment/processing costs reconcile | Unverified |
88
+ | Test clocks | Determine which provider clock drives event timestamps and invoice periods, without assuming virtual time advances ingestion | Unverified |
89
+ | Packed consumer | Verify eventual public contracts from the built tarball with linked guides present | Deferred until public APIs exist |
90
+
91
+ For Billing Meters, event uniqueness is enforced for at least a rolling 24-hour
92
+ window. Acceptance permits timestamps within 35 calendar days in the past or five
93
+ minutes in the future. Cancellation is limited to events sent within 24 hours.
94
+ Aggregation is asynchronous. Accepted late events can appear in summaries without
95
+ changing a finalized invoice. Preserve local deduplication and an explicit unknown
96
+ delivery state beyond the safe retry window. Events have no subscription selector.
97
+
98
+ Metronome's quickstart uses a customer UUID or ingest alias and transaction ID,
99
+ string-valued numerical properties and a 34-day backdating window. Confirm exact
100
+ retention, correction and retry guarantees for the chosen API and account before
101
+ encoding them as constants. Its invoice integration documentation and Stripe's
102
+ integration overview use different metadata names for invoice mapping. Inspect the
103
+ actual sandbox invoice rather than trusting a single assumed metadata key.
104
+
105
+ ## Evidence recorded so far
106
+
107
+ The repository uses Stripe 23.0.0 and pins `2026-09-30.endive`. Its installed meter
108
+ creation types permit `customer_mapping.type: 'by_id'`; this is a type inspection,
109
+ not proof that Accounts v2 ingestion is supported or unsupported. The access probe
110
+ has automated tests covering rejection of live/missing keys, a single read-only
111
+ request and sanitization of provider errors. Actual provider access, usage delivery,
112
+ aggregation, invoices, payment provenance and Metronome access remain unverified.
113
+
114
+ ## Primary sources
115
+
116
+ - [Stripe usage-based billing](https://docs.stripe.com/billing/usage-based)
117
+ - [Stripe's guidance on recording usage](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage)
118
+ - [Record usage with the API](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage-api)
119
+ - [Create a meter event](https://docs.stripe.com/api/billing/meter-event/create)
120
+ - [Configure meters and corrections](https://docs.stripe.com/billing/subscriptions/usage-based/meters/configure)
121
+ - [How Metronome works with Stripe](https://docs.stripe.com/billing/how-metronome-works-with-stripe)
122
+ - [Metronome API quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
123
+ - [Metronome invoice integration](https://docs.metronome.com/integrations/invoice-integrations/stripe)
@@ -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