@fantastic.dev/better-stripe 0.68.0 → 0.68.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/MIGRATION.md +1 -1
- package/README.md +12 -12
- package/docs/README.md +18 -32
- package/docs/architecture.md +40 -21
- package/docs/client-api.md +15 -3
- package/docs/configuration.md +36 -8
- package/docs/development.md +25 -5
- package/docs/marketplace.md +34 -10
- package/docs/overview.md +14 -3
- package/docs/react-api.md +18 -9
- package/docs/testing.md +29 -4
- package/docs/usage-observations.md +5 -2
- package/docs/webhooks.md +45 -7
- package/package.json +15 -60
package/CHANGELOG.md
CHANGED
|
@@ -26,6 +26,16 @@
|
|
|
26
26
|
- Remove internal tracker references from public documentation and add a
|
|
27
27
|
regression check that prevents their reintroduction.
|
|
28
28
|
|
|
29
|
+
## [0.68.1](https://github.com/FantasticDevHQ/better-stripe/compare/v0.68.0...v0.68.1) (2026-10-19)
|
|
30
|
+
|
|
31
|
+
### Documentation
|
|
32
|
+
|
|
33
|
+
- align public guides and simplify package maintenance ([#361](https://github.com/FantasticDevHQ/better-stripe/issues/361)) ([f0a07f9](https://github.com/FantasticDevHQ/better-stripe/commit/f0a07f92e1de8b044c1780a9a7551b531b9ff9e3))
|
|
34
|
+
|
|
35
|
+
### Maintenance
|
|
36
|
+
|
|
37
|
+
- **coverage:** ratchet earned coverage floors ([#362](https://github.com/FantasticDevHQ/better-stripe/issues/362)) ([df7db01](https://github.com/FantasticDevHQ/better-stripe/commit/df7db0112a551702540733b65f9541fcfc280ee9))
|
|
38
|
+
|
|
29
39
|
## [0.68.0](https://github.com/FantasticDevHQ/better-stripe/compare/v0.67.1...v0.68.0) (2026-10-19)
|
|
30
40
|
|
|
31
41
|
### Features
|
package/MIGRATION.md
CHANGED
|
@@ -169,7 +169,7 @@ changes. Further consumer guidance: [Stripe API changelog](https://docs.stripe.c
|
|
|
169
169
|
The docs.stripe.com changelog page returned HTTP 403 in this execution
|
|
170
170
|
environment.
|
|
171
171
|
|
|
172
|
-
##
|
|
172
|
+
## Settlement API extraction
|
|
173
173
|
|
|
174
174
|
Deploy the regenerated component bindings with the package upgrade. Existing
|
|
175
175
|
transfers remain in the same ledger; new immutable allocation and commission
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ billing, and Connect marketplaces. It provides checkout, subscriptions, webhook
|
|
|
5
5
|
syncing, marketplace fees and splits, payouts, refunds, and disputes, with React
|
|
6
6
|
hooks and headless UI components.
|
|
7
7
|
|
|
8
|
-
**Version**: `0.68.
|
|
8
|
+
**Version**: `0.68.1` <!-- x-release-please-version --> (pre-1.0). API may change between minor versions until 1.0.
|
|
9
9
|
|
|
10
10
|
Connect platforms use the default GA API version. Non-Connect merchants using
|
|
11
11
|
customer-only Accounts v2 need preview access and an explicit preview version.
|
|
@@ -135,17 +135,7 @@ The [example app](https://github.com/FantasticDevHQ/better-stripe/blob/main/exam
|
|
|
135
135
|
demonstrates customer, seller, affiliate, and admin flows, including several checkout
|
|
136
136
|
integration styles.
|
|
137
137
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
See the [development guide](docs/development.md) for local setup and code generation,
|
|
141
|
-
[testing utilities](docs/testing.md) for fixtures, and the [release guide](docs/releasing.md)
|
|
142
|
-
for publishing. Run `pnpm run check:all` before submitting changes.
|
|
143
|
-
|
|
144
|
-
## License
|
|
145
|
-
|
|
146
|
-
MIT
|
|
147
|
-
|
|
148
|
-
## Metered usage
|
|
138
|
+
### Metered usage
|
|
149
139
|
|
|
150
140
|
Use native Stripe billing for pay as you go, included monthly units with overages,
|
|
151
141
|
and paid prepaid credits. Developers choose units, precision, rates and policy;
|
|
@@ -163,3 +153,13 @@ for forms, exact usage, allowances, prepaid balances and paginated history.
|
|
|
163
153
|
[The verification matrix](docs/usage-verification.md) records native paid-source
|
|
164
154
|
proof, packed consumers and account/clock limits. Existing apps should follow
|
|
165
155
|
[opt-in adoption, model transitions and rollback](docs/usage-rollout.md).
|
|
156
|
+
|
|
157
|
+
## Contributing
|
|
158
|
+
|
|
159
|
+
See the [development guide](docs/development.md) for local setup and code generation,
|
|
160
|
+
[testing utilities](docs/testing.md) for fixtures, and the [release guide](docs/releasing.md)
|
|
161
|
+
for publishing. Run `pnpm run check:all` before submitting changes.
|
|
162
|
+
|
|
163
|
+
## License
|
|
164
|
+
|
|
165
|
+
MIT
|
package/docs/README.md
CHANGED
|
@@ -24,8 +24,7 @@ guide for your integration.
|
|
|
24
24
|
- [SetupIntent recovery](setup-intent-recovery.md).
|
|
25
25
|
- [Balance funding state](balance-funding-state.md) and [workflow](balance-funding-workflow.md).
|
|
26
26
|
- [Example balance funding cutover](example-balance-funding-cutover.md).
|
|
27
|
-
- [
|
|
28
|
-
- [Opt-in usage rollout](usage-rollout.md), adoption, drain, backfill limits, model transitions, rollback and release handoff.
|
|
27
|
+
- [Metered billing guides](#metered-usage), all three models, package APIs, runnable examples and rollout.
|
|
29
28
|
|
|
30
29
|
## Marketplace, settlement, and recovery
|
|
31
30
|
|
|
@@ -56,33 +55,20 @@ covers sandbox configuration, checkout comparisons, and test flows.
|
|
|
56
55
|
|
|
57
56
|
## Metered usage
|
|
58
57
|
|
|
59
|
-
|
|
60
|
-
[
|
|
61
|
-
|
|
62
|
-
[
|
|
63
|
-
|
|
64
|
-
[
|
|
65
|
-
|
|
66
|
-
[
|
|
67
|
-
|
|
68
|
-
[
|
|
69
|
-
|
|
70
|
-
[
|
|
71
|
-
|
|
72
|
-
- [
|
|
73
|
-
|
|
74
|
-
- [
|
|
75
|
-
|
|
76
|
-
- [Usage corrections](./usage-corrections.md) covers native cancellation, quantity restoration and verified invoice adjustments.
|
|
77
|
-
|
|
78
|
-
- [Native usage settlement](./usage-settlement.md) covers original paid invoices, issuer-service credit purchases and affiliate recovery.
|
|
79
|
-
|
|
80
|
-
- [Metered billing authorization](./usage-security.md) covers server ownership, work deduplication, native proof limits and retained recovery liabilities.
|
|
81
|
-
|
|
82
|
-
- [Reusable metered billing UI](usage-react.md) covers all three models, render props, authenticated adapters and bounded history.
|
|
83
|
-
|
|
84
|
-
- [Native usage configuration UI](usage-configuration.md) covers reusable forms, managed meter selection, price rows and authorized adapters.
|
|
85
|
-
|
|
86
|
-
- [Native metered billing example](usage-example.md), three runnable models, paid evidence and scoped cleanup.
|
|
87
|
-
|
|
88
|
-
- [Metered usage verification](usage-verification.md), three-model acceptance, packed consumers, native proof and failure limits.
|
|
58
|
+
- [Native Stripe setup](metering-setup.md), prerequisites, safe credentials and the developer/AI-agent runbook.
|
|
59
|
+
- [Three-model recipes](metered-usage.md), developer-defined units, rates, allowances and paid prepaid credits.
|
|
60
|
+
- [Atomic ledger and history](usage-ledger.md), acceptance, event identity and retention.
|
|
61
|
+
- [Native usage catalog](usage-catalog.md), provisioning, immutable versions and typed price observations.
|
|
62
|
+
- [Durable delivery](usage-delivery.md), internal provider actions, bounded retries, holds and asynchronous errors.
|
|
63
|
+
- [Observations and reconciliation](usage-observations.md), exact summaries, paginated history, freshness and invoices.
|
|
64
|
+
- [Managed subscriptions](usage-subscriptions.md), enrollment, Checkout, renewal, closeout and native test clocks.
|
|
65
|
+
- [Payment-backed prepaid credits](usage-credits.md), verified purchase grants, consumption and recovery.
|
|
66
|
+
- [Included usage and limits](usage-limits.md), atomic caps, reservations, period resets and overage estimates.
|
|
67
|
+
- [Corrections](usage-corrections.md), native cancellation, quantity restoration and verified invoice adjustments.
|
|
68
|
+
- [Settlement](usage-settlement.md), original paid invoices, issuer-service credit purchases and affiliate recovery.
|
|
69
|
+
- [Authorization](usage-security.md), server ownership, work deduplication and retained liabilities.
|
|
70
|
+
- [React workflows](usage-react.md), all three models, render props, authenticated adapters and bounded history.
|
|
71
|
+
- [Configuration UI](usage-configuration.md), reusable forms, managed meter selection and price rows.
|
|
72
|
+
- [Runnable example](usage-example.md), three sandbox flows, paid evidence and scoped cleanup.
|
|
73
|
+
- [Verification](usage-verification.md), packed consumers, native billing proof and documented limits.
|
|
74
|
+
- [Opt-in rollout](usage-rollout.md), adoption, drain, backfill limits, model transitions and rollback.
|
package/docs/architecture.md
CHANGED
|
@@ -2,19 +2,31 @@
|
|
|
2
2
|
|
|
3
3
|
### Component-Owned Tables
|
|
4
4
|
|
|
5
|
-
The component
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
|
11
|
-
|
|
|
12
|
-
|
|
|
13
|
-
|
|
|
14
|
-
|
|
|
15
|
-
|
|
|
16
|
-
|
|
|
17
|
-
|
|
|
5
|
+
The component schema is composed from domain modules. It includes provider
|
|
6
|
+
mirrors and retained financial, workflow and usage state. The authoritative table
|
|
7
|
+
inventory is [the component schema](../src/component/schema.ts); table names are
|
|
8
|
+
internal storage contracts, not an invitation for a host to write them directly.
|
|
9
|
+
|
|
10
|
+
| Domain | Component-owned state |
|
|
11
|
+
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
|
|
12
|
+
| Accounts and catalog | Accounts, closed-account provenance, products and prices |
|
|
13
|
+
| Billing and Connect | Subscriptions, checkout sessions, invoices, payments, payouts, refunds, disputes, transfers and reversal operations |
|
|
14
|
+
| Webhooks | Event deduplication and processing state |
|
|
15
|
+
| Settlement and affiliate recovery | Immutable allocations/commission decisions, original policy context, obligations, receipts, offsets and balances |
|
|
16
|
+
| Recipient payouts | Policies, schedule operations, releases, claims, source allocations, snapshots, worker jobs and financial/risk revisions |
|
|
17
|
+
| Financial observations and ownership | Scoped ownership generations, complete source/transfer observations, reversal history and retained references |
|
|
18
|
+
| Recovery and funding | Cost claims/reservations, processing-cost reconciliation, balance-funding operations and durable recovery requests |
|
|
19
|
+
| Operation evidence | Bounded evidence headers and payloads |
|
|
20
|
+
| Usage catalog and subscriptions | Immutable meter/price bindings, enrollment controls, intents, locks and history |
|
|
21
|
+
| Usage ledger and delivery | Scoped events, counters, reservations, transactional outbox, delivery locks/errors/history and provider observations |
|
|
22
|
+
| Usage allowance and credits | Allowance policies/history and payment-backed credit accounts, purchases, grants and history |
|
|
23
|
+
| Usage corrections | Correction operations, claims and auditable history |
|
|
24
|
+
| Payout revision migration | Revision journal, bounded migration jobs and results |
|
|
25
|
+
|
|
26
|
+
The component installs its nested Workflow runtime through
|
|
27
|
+
`@fantastic.dev/better-stripe/convex.config`. Hosts supply internal provider
|
|
28
|
+
actions and authorization where required. See [durable execution](architecture/durable-execution.md)
|
|
29
|
+
and [the extraction boundary](architecture/component-extraction.md).
|
|
18
30
|
|
|
19
31
|
### App-Layer Tables
|
|
20
32
|
|
|
@@ -52,12 +64,14 @@ Async hook (scheduled action) --> App calls external APIs
|
|
|
52
64
|
|
|
53
65
|
### Package Entry Points
|
|
54
66
|
|
|
55
|
-
| Entry Point
|
|
56
|
-
|
|
|
57
|
-
| `@fantastic.dev/better-stripe`
|
|
58
|
-
| `@fantastic.dev/better-stripe/react`
|
|
59
|
-
| `@fantastic.dev/better-stripe/testing`
|
|
60
|
-
| `@fantastic.dev/better-stripe/convex.config`
|
|
67
|
+
| Entry Point | Contents |
|
|
68
|
+
| --------------------------------------------------- | -------------------------------------------------------------------- |
|
|
69
|
+
| `@fantastic.dev/better-stripe` | `BetterStripe` class, `registerRoutes`, TypeScript types |
|
|
70
|
+
| `@fantastic.dev/better-stripe/react` | React hooks, headless UI components, formatting helpers |
|
|
71
|
+
| `@fantastic.dev/better-stripe/testing` | Test fixtures, mock webhooks, `assertTestEnvironment` |
|
|
72
|
+
| `@fantastic.dev/better-stripe/convex.config` | Convex component registration and nested Workflow runtime |
|
|
73
|
+
| `@fantastic.dev/better-stripe/usage` | Shared usage schemas, exact quantity helpers and model configuration |
|
|
74
|
+
| `@fantastic.dev/better-stripe/_generated/component` | Generated component reference types |
|
|
61
75
|
|
|
62
76
|
### Error Handling
|
|
63
77
|
|
|
@@ -75,6 +89,11 @@ interface BetterStripeError {
|
|
|
75
89
|
}
|
|
76
90
|
```
|
|
77
91
|
|
|
78
|
-
|
|
92
|
+
The [structured error definitions](../src/client/errors.ts) include account,
|
|
93
|
+
catalog, checkout, subscription, refund, dispute and configuration failures.
|
|
94
|
+
The usage APIs also expose domain-specific errors and explicit held/unknown
|
|
95
|
+
outcomes. See [usage contracts](metered-usage.md) and each workflow's recovery
|
|
96
|
+
contract. A successful transport call does not establish payment or settlement.
|
|
79
97
|
|
|
80
|
-
|
|
98
|
+
Methods that allow uncaught Stripe SDK errors to propagate remain a separate
|
|
99
|
+
error path. Do not assume every failure has the structured payload above.
|
package/docs/client-api.md
CHANGED
|
@@ -96,7 +96,7 @@ Scope the idempotency key to one catalog operation and reuse it only with identi
|
|
|
96
96
|
| `getActiveSubscription(ctx, { userId, orgId? })` | Get the active subscription for a user or org |
|
|
97
97
|
| `getTrialStatus(ctx, { subscriptionId })` | Get trial state for a subscription |
|
|
98
98
|
| `cancelSubscription(ctx, { stripeSubscriptionId, cancelAtPeriodEnd? })` | Cancel subscription immediately or at period end |
|
|
99
|
-
| `reactivateSubscription(ctx, { stripeSubscriptionId })` |
|
|
99
|
+
| `reactivateSubscription(ctx, { stripeSubscriptionId })` | Clear scheduled end-of-period cancellation before the subscription terminates |
|
|
100
100
|
| `updateSubscriptionQuantity(ctx, { stripeSubscriptionId, quantity })` | Update subscription seat quantity |
|
|
101
101
|
|
|
102
102
|
### Durable recovery claims
|
|
@@ -446,7 +446,7 @@ recovery costs and credits remain host-owned policy. See Stripe's
|
|
|
446
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
447
|
| `updateDispute(ctx, { stripeDisputeId, evidence?, metadata?, submit?, stripeAccountId? })` | Submit/stage dispute evidence (`submit: true` finalizes the response) |
|
|
448
448
|
| `closeDispute(ctx, { stripeDisputeId, stripeAccountId? })` | Accept a dispute (concede the chargeback) — irreversible |
|
|
449
|
-
| `reverseTransfers(ctx, { sourceChargeId, percent?, amount? })`
|
|
449
|
+
| `reverseTransfers(ctx, { sourceChargeId, percent?, amount?, operationId? })` | Reverse split/destination transfers for a charge (the primitive behind automatic dispute clawback; also callable manually) |
|
|
450
450
|
|
|
451
451
|
`uploadDisputeEvidence` shipped in [0.14.0](https://github.com/FantasticDevHQ/better-stripe/releases/tag/v0.14.0).
|
|
452
452
|
Call it from an authenticated server adapter with a session-derived actor. A seller
|
|
@@ -587,7 +587,7 @@ and [uploaded screenshots and provider records](https://github.com/FantasticDevH
|
|
|
587
587
|
|
|
588
588
|
## Reversal history and revision maintenance
|
|
589
589
|
|
|
590
|
-
`stripe.reversalObservations` reads original claimed-slice history and maintains a bounded diagnostic index. Its physical operation references survive release/deletion and distinguish reuse of a business operation ID. Exact bucket/owner pages, original/latest payloads and generation-aware continuation remain unknown coverage. These methods do not execute reversals, certify current ownership or authorize closure. See [financial observations](financial-observations.md#claimed-reversal-history).
|
|
590
|
+
`stripe.reversalObservations` reads original claimed-slice history and maintains a bounded diagnostic index. Its physical operation references survive release/deletion and distinguish reuse of a business operation ID. Exact bucket/owner pages, original/latest payloads and generation-aware continuation remain unknown coverage. These methods do not execute reversals, certify current ownership or authorize closure. See [financial observations](financial-observations.md#claimed-reversal-slice-history).
|
|
591
591
|
|
|
592
592
|
`stripe.payoutRevisionMigration` exposes trusted-host `activateAccount`, `begin`, `resume`, `get` and `results`. Existing destinations keep legacy revision authority until explicitly activated. Activation and inventory are bounded storage maintenance, with held outcomes for ambiguous or unrepresentable legacy authority. Installing the package does not run a migration. See the [migration guide](payout-revision-migration.md) before relying on the tested large-operation path or changing component versions.
|
|
593
593
|
|
|
@@ -600,3 +600,15 @@ and [uploaded screenshots and provider records](https://github.com/FantasticDevH
|
|
|
600
600
|
row reads and no Stripe request. The [read contract](read-contracts.md#bounded-product-and-price-identity)
|
|
601
601
|
explains duplicate handling and the host authorization boundary. Existing
|
|
602
602
|
provider-ID getters keep their first-row semantics.
|
|
603
|
+
|
|
604
|
+
## Native metered billing
|
|
605
|
+
|
|
606
|
+
`stripe.usage` groups the shared ledger/delivery APIs and all three model
|
|
607
|
+
controllers. Start with [typed model recipes](metered-usage.md) and
|
|
608
|
+
[setup](metering-setup.md). Follow the domain contracts for [catalog](usage-catalog.md),
|
|
609
|
+
[subscriptions](usage-subscriptions.md), [ledger](usage-ledger.md),
|
|
610
|
+
[delivery](usage-delivery.md), [observations](usage-observations.md),
|
|
611
|
+
[allowances/limits](usage-limits.md), [paid credits](usage-credits.md),
|
|
612
|
+
[corrections](usage-corrections.md) and [settlement](usage-settlement.md).
|
|
613
|
+
These are trusted host APIs. Browser-selected payer, realm, meter or provider
|
|
614
|
+
references do not establish authorization.
|
package/docs/configuration.md
CHANGED
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
### Environment Variables
|
|
4
4
|
|
|
5
|
-
| Variable | Required | Read by | Description
|
|
6
|
-
| -------------------------- | ----------- | --------- |
|
|
7
|
-
| `STRIPE_SECRET_KEY` | Yes | Component | Declared in the component's `convex.config.ts` (required) and read by the component (e.g. `getStripeMode`). Also passed explicitly via the `BetterStripe` constructor and `registerRoutes`. The installing app must wire it to the component — see below.
|
|
8
|
-
| `STRIPE_WEBHOOK_SECRET` | Yes | App | Signing secret for the V1 snapshot event destination. Read by `registerRoutes` in the app, not the component.
|
|
9
|
-
| `STRIPE_WEBHOOK_SECRET_V2` | No\* | App | Signing secret for the V2 thin event destination (Connect account events). \*Required whenever your V2 destination has its own secret (the usual case); falls back to `STRIPE_WEBHOOK_SECRET` if unset.
|
|
10
|
-
| `STRIPE_PUBLISHABLE_KEY` | Yes (React) | Frontend | A public, frontend-only key. Supply it from the frontend's own env (`VITE_STRIPE_PUBLISHABLE_KEY` / `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`) and pass it as the `publishableKey` prop to the React components.
|
|
5
|
+
| Variable | Required | Read by | Description |
|
|
6
|
+
| -------------------------- | ----------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
7
|
+
| `STRIPE_SECRET_KEY` | Yes | Component | Declared in the component's `convex.config.ts` (required) and read by the component (e.g. `getStripeMode`). Also passed explicitly via the `BetterStripe` constructor and `registerRoutes`. The installing app must wire it to the component — see below. |
|
|
8
|
+
| `STRIPE_WEBHOOK_SECRET` | Yes | App | Signing secret for the V1 snapshot event destination. Read by `registerRoutes` in the app, not the component. |
|
|
9
|
+
| `STRIPE_WEBHOOK_SECRET_V2` | No\* | App | Signing secret for the V2 thin event destination (Connect account events). \*Required whenever your V2 destination has its own secret (the usual case); falls back to `STRIPE_WEBHOOK_SECRET` if unset. |
|
|
10
|
+
| `STRIPE_PUBLISHABLE_KEY` | Yes (React) | Frontend | A public, frontend-only key. Supply it from the frontend's own env (`VITE_STRIPE_PUBLISHABLE_KEY` / `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`) and pass it as the `publishableKey` prop to the React components. The component also accepts it optionally through `app.use` for `stripe.getPublishableKey`; frontend props still need the public key explicitly. |
|
|
11
11
|
|
|
12
12
|
### Wiring component env vars
|
|
13
13
|
|
|
@@ -40,11 +40,39 @@ the deployment env — no `app.use` wiring required.
|
|
|
40
40
|
|
|
41
41
|
### Stripe API Version
|
|
42
42
|
|
|
43
|
-
The
|
|
43
|
+
The default API version is `2026-09-30.endive`. The supported customer-only
|
|
44
|
+
Accounts v2 opt-in is `STRIPE_CUSTOMER_PREVIEW_API_VERSION`, currently
|
|
45
|
+
`2026-09-30.preview`. Other values are rejected. This is a constructor option,
|
|
46
|
+
not a `STRIPE_API_VERSION` environment variable. Account eligibility and request
|
|
47
|
+
version are separate requirements; read [Accounts v2 setup](accounts-v2-preview.md).
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import {
|
|
51
|
+
BetterStripe,
|
|
52
|
+
STRIPE_CUSTOMER_PREVIEW_API_VERSION,
|
|
53
|
+
} from "@fantastic.dev/better-stripe";
|
|
54
|
+
import { components } from "./_generated/api";
|
|
55
|
+
|
|
56
|
+
export const stripe = new BetterStripe(components.betterStripe, {
|
|
57
|
+
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
|
|
58
|
+
// Omit for the default Connect/GA integration.
|
|
59
|
+
stripeApiVersion: STRIPE_CUSTOMER_PREVIEW_API_VERSION,
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Use `stripe.registerRoutes(http, config)` to inherit this client's key/version,
|
|
64
|
+
or pass the same `stripeApiVersion` explicitly to standalone `registerRoutes`.
|
|
65
|
+
Pin snapshot event destinations to the matching version. Changing package
|
|
66
|
+
defaults follows the release process; upgrading a client does not migrate existing
|
|
67
|
+
provider destinations. See [migration notes](../MIGRATION.md).
|
|
44
68
|
|
|
45
69
|
### SDK Management
|
|
46
70
|
|
|
47
|
-
The
|
|
71
|
+
The package manages Stripe clients for its public operations. The shared client
|
|
72
|
+
cache is keyed by API key and supported API version. Durable provider adapters
|
|
73
|
+
can create isolated clients with their own retry policy. Pass credentials through
|
|
74
|
+
the documented constructor or internal provider-action boundary; do not journal
|
|
75
|
+
secrets or duplicate the package's Stripe operations in host code.
|
|
48
76
|
|
|
49
77
|
## TypeScript setup
|
|
50
78
|
|
package/docs/development.md
CHANGED
|
@@ -2,9 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
### Development toolchain
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
Use Node.js 24, as CI does, and the pinned pnpm version in `package.json`.
|
|
6
|
+
The package supports Node.js 20+, but the Vite example requires Node.js 22.12+.
|
|
7
|
+
From the repository root, run `pnpm install --frozen-lockfile` and
|
|
8
|
+
`pnpm run build:clean`. After configuring the example's existing Convex development
|
|
9
|
+
deployment, `pnpm dev` starts its backend watcher and Vite frontend. Use the
|
|
10
|
+
localhost URL Vite prints, normally http://localhost:5173. For a frontend-only
|
|
11
|
+
server against an already deployed backend, run `pnpm run dev:frontend` from
|
|
12
|
+
`example/`. See
|
|
8
13
|
[the example setup guide](https://github.com/FantasticDevHQ/better-stripe/blob/main/example/README.md).
|
|
9
14
|
|
|
10
15
|
The BetterStripe example separates visitor, customer, affiliate, seller, and
|
|
@@ -37,7 +42,8 @@ See [affiliate configuration and testing](https://github.com/FantasticDevHQ/bett
|
|
|
37
42
|
|
|
38
43
|
The public React exports include `AffiliatePayoutEditor`, `PlanPricingEditor`,
|
|
39
44
|
`Pagination`, and `useCursorPagination`. The example supplies styling through
|
|
40
|
-
render props; its backend owns authorization
|
|
45
|
+
render props; its backend owns authorization and rule inheritance. The package owns durable
|
|
46
|
+
transfer execution, retained financial records and provider reconciliation.
|
|
41
47
|
See [the workflow reference](react-workflows.md#percentage-or-fixed-affiliate-payouts)
|
|
42
48
|
and [the UI reuse audit](react-workflows-audit.md).
|
|
43
49
|
|
|
@@ -46,6 +52,14 @@ formatting, typechecks, codegen drift check, tests, and repository quality gates
|
|
|
46
52
|
used by CI. Policy lives in `repo-gates.config.json`; measured baselines live in
|
|
47
53
|
`gates/`. Fix failures without weakening the gates or raising existing budgets.
|
|
48
54
|
|
|
55
|
+
Use `pnpm run check:package` to clean/rebuild the package and run the artifact
|
|
56
|
+
checks in one command. It verifies public documentation imports and local links,
|
|
57
|
+
recursively linked guides in the actual tarball, and extracted usage consumers
|
|
58
|
+
for public types, runtime accounting and React rendering. It uses deterministic
|
|
59
|
+
fixtures without provider credentials or deployment changes. Native component
|
|
60
|
+
analysis remains a separate authorized development probe in
|
|
61
|
+
[the usage handoff evidence](https://github.com/FantasticDevHQ/better-stripe/tree/main/docs/evidence/usage-handoff).
|
|
62
|
+
|
|
49
63
|
Coverage checks enforce the committed floors in `gates/coverage-budgets.json`.
|
|
50
64
|
`pnpm run check:coverage` and `pnpm run check:all` never edit that file or fail
|
|
51
65
|
because coverage improved. Ordinary feature PRs should leave the budget file alone.
|
|
@@ -104,7 +118,13 @@ pnpm codegen:lib # regen src/component/_generated only
|
|
|
104
118
|
pnpm codegen:example # regen example/convex/_generated only
|
|
105
119
|
```
|
|
106
120
|
|
|
107
|
-
All three require a configured dev deployment
|
|
121
|
+
All three require a configured dev deployment, normally selected by a prior
|
|
122
|
+
`pnpm exec convex dev` from `example/`. They generate local bindings and, for
|
|
123
|
+
components, upload and analyze definitions against the selected development
|
|
124
|
+
deployment. Codegen does not replace its serving application or run a data
|
|
125
|
+
migration; deploying updated handlers still requires `convex dev` or
|
|
126
|
+
`convex dev --once` from `example/`. Keep secrets and deployment-key overrides
|
|
127
|
+
out of the wrong terminal. See [safe development selection](metering-setup.md#run-the-repository-example).
|
|
108
128
|
|
|
109
129
|
**CI gate.** Two layers verify the committed files are not stale:
|
|
110
130
|
|
package/docs/marketplace.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Marketplace economics
|
|
2
2
|
|
|
3
|
-
The platform is always the merchant of record (Skool-style marketplace model): sellers are Connect recipients, not merchants. This section covers the fee, split, payout, dispute, and refund/descriptor primitives that implement that model.
|
|
3
|
+
The platform is always the merchant of record (Skool-style marketplace model): sellers are Connect recipients, not merchants. This section covers the fee, split, payout, dispute, and refund/descriptor primitives that implement that model. Amounts use the currency's minor units, cents for USD. Do not assume two decimal places for every currency.
|
|
4
4
|
|
|
5
5
|
### Fee Model
|
|
6
6
|
|
|
@@ -30,9 +30,19 @@ const { feeAmount, percentApplied, fixedApplied, tier } = computeFee(2999, {
|
|
|
30
30
|
|
|
31
31
|
**How the fee is charged** depends on shape and charge type:
|
|
32
32
|
|
|
33
|
-
-
|
|
34
|
-
-
|
|
35
|
-
|
|
33
|
+
- Percent-only subscription fees use `application_fee_percent`.
|
|
34
|
+
- A one-time destination charge with a known amount computes
|
|
35
|
+
`application_fee_amount` before confirmation, including percent-only rates.
|
|
36
|
+
- Fixed/tiered subscription fees are computed on draft `invoice.created` and set
|
|
37
|
+
as `application_fee_amount`. A synchronously finalized first invoice misses
|
|
38
|
+
that draft window; `invoice.paid` collects its fee through a retained partial
|
|
39
|
+
destination-transfer reversal.
|
|
40
|
+
- A deferred one-time fee cannot be attached to a succeeded PaymentIntent as
|
|
41
|
+
`application_fee_amount`. The webhook processor collects it through a partial
|
|
42
|
+
reversal of the original destination transfer with retained recovery evidence.
|
|
43
|
+
|
|
44
|
+
See [first-invoice fee handling](overview.md#roadmap--known-gaps) for replay
|
|
45
|
+
and duplicate-collection guards.
|
|
36
46
|
|
|
37
47
|
Fees only apply to **destination charges** (`destinationAccountId` set, or a single-recipient `split`). The **separate-charges-and-transfers** path (multi-recipient `split`) never uses `application_fee` — the platform's cut is realized by transferring less than was charged (see Split Engine below).
|
|
38
48
|
|
|
@@ -86,7 +96,13 @@ const result = computeSplit(10000, { percent: 10 }, [
|
|
|
86
96
|
|
|
87
97
|
### Payouts
|
|
88
98
|
|
|
89
|
-
|
|
99
|
+
Stripe-managed automatic payouts are the default. `listPayouts` reads history
|
|
100
|
+
and `createPayout` submits an authorized payout. The package also supports
|
|
101
|
+
explicit recipient-held custom policies, verified manual schedule changes and
|
|
102
|
+
automatic workers. Those require consent, source/recovery verification and
|
|
103
|
+
the [payout policy controls](settlement.md#recipient-held-payout-policy-controls).
|
|
104
|
+
The presentational `PayoutSchedule` component shows a supplied balance and next
|
|
105
|
+
payout; that component offers no withdrawal command. See [React workflows](react-workflows.md#payout-settings).
|
|
90
106
|
|
|
91
107
|
### Disputes
|
|
92
108
|
|
|
@@ -94,21 +110,29 @@ The platform is merchant of record, so a chargeback lands on the platform's Stri
|
|
|
94
110
|
|
|
95
111
|
1. **Clawback** — a monetary `charge.dispute.created` event uses the disputed charge's original gross amount to calculate affiliate commission exposure. Inquiry/warning, prevented, and already-won payloads do not trigger recovery. Affiliate legs share the original-principal exposure axis with refunds; seller and other legs retain the existing reversal allocation. The dispute ID identifies the operation, and a missing authoritative charge amount causes recovery to retry.
|
|
96
112
|
2. **Reinstatement** — if the dispute is won (`.closed` with `status: "won"`, or `.funds_reinstated`), the existing `reinstateTransfers` path creates new transfers from the platform balance. Affiliate restoration uses exact reversal/offset receipts, preserves independent successful refunds, and cancels unpaid dispute debt. Failed or uncertain restoration remains visible until reconciled. See [recovery limitations](affiliate-clawbacks.md#verification-evidence).
|
|
97
|
-
3. **Auto-cancel** — on dispute open, the disputed subscription (resolved PaymentIntent → invoice → subscription) is canceled by default (`registerRoutes`'s `autoCancelOnDispute`, default `true`; pairs with `
|
|
113
|
+
3. **Auto-cancel** — on dispute open, the disputed subscription (resolved PaymentIntent → invoice → subscription) is canceled by default (`registerRoutes`'s `autoCancelOnDispute`, default `true`; pairs with `cancelDisputedSubscriptionImmediately`, default `false` → cancel-at-period-end, matching the Skool model of "cancel now, remove access at cycle end").
|
|
98
114
|
|
|
99
115
|
Sellers respond to their own disputes without platform staff involvement, via an embedded Stripe Connect session:
|
|
100
116
|
|
|
101
117
|
```typescript
|
|
102
|
-
//
|
|
118
|
+
// Host helper authenticates ctx.auth and authorizes the original seller account.
|
|
103
119
|
export const createDisputeSession = action({
|
|
104
|
-
args: {
|
|
105
|
-
handler: async (ctx
|
|
120
|
+
args: {},
|
|
121
|
+
handler: async (ctx) => {
|
|
122
|
+
const stripeAccountId = await requireAuthorizedSellerAccount(ctx);
|
|
123
|
+
return stripe.createDisputeSession(ctx, { stripeAccountId });
|
|
124
|
+
},
|
|
106
125
|
});
|
|
107
126
|
```
|
|
108
127
|
|
|
109
128
|
`stripe.createDisputeSession(ctx, { stripeAccountId })` creates an Account Session scoped to `disputes_list`/`payment_disputes` — mount it with the `ConnectProvider`/`EmbeddedDisputes` React components (see [Embedded Disputes](react-api.md#embedded-disputes-stripe-connect)), or build a custom UI on `updateDispute`/`closeDispute` plus the headless `DisputesList`/`DisputeDetail`/`EvidenceForm` components and `buildDisputeEvidence`/`disputeEvidenceCountdown` helpers (see [React Components](react-api.md#react-components)).
|
|
110
129
|
|
|
111
|
-
`stripe.reverseTransfers(ctx, { sourceChargeId, percent?, amount? })`
|
|
130
|
+
`stripe.reverseTransfers(ctx, { sourceChargeId, percent?, amount?, operationId? })`
|
|
131
|
+
exposes the existing reversal primitive. Supply a stable, server-derived
|
|
132
|
+
`operationId` to retain original slices and idempotency keys across retries.
|
|
133
|
+
Without it the call is a one-shot reversal with no idempotency protection; an
|
|
134
|
+
uncertain outcome must not be blindly retried. Authorize the original charge,
|
|
135
|
+
amount and recovery policy before invoking it.
|
|
112
136
|
|
|
113
137
|
For commissions tracked by the recovery ledger, generic manual reversal is
|
|
114
138
|
rejected. Use `createRefund` for a real refund or `stripe.affiliateRecovery.retry`
|
package/docs/overview.md
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
## Features
|
|
4
4
|
|
|
5
5
|
- **V2 Accounts API** -- Account creation, onboarding, Connect/marketplace, merchant and recipient configurations
|
|
6
|
-
- **Products and Prices** --
|
|
7
|
-
- **Checkout** --
|
|
6
|
+
- **Products and Prices** -- Creation, reads, updates and deactivation, with product trial-day defaults
|
|
7
|
+
- **Checkout** -- Checkout Sessions with redirect, embedded, custom Elements and preview form modes; React also supports the separate PaymentIntent flow
|
|
8
8
|
- **Subscriptions** -- Lifecycle management including cancel, reactivate, quantity updates, and trial tracking
|
|
9
9
|
- **Marketplace fees** -- Platform fee config (percent, fixed, tiered), resolved per-call or as a global default, applied via `application_fee_percent`/`application_fee_amount` or computed per invoice/charge
|
|
10
10
|
- **Split engine** -- Single-recipient destination charges or multi-recipient separate-charges-and-transfers (store + affiliate(s)), computed and executed by the webhook engine
|
|
@@ -128,7 +128,18 @@ Historical payout adoption and funded-account activation also use complete pagin
|
|
|
128
128
|
|
|
129
129
|
## Metered usage
|
|
130
130
|
|
|
131
|
-
|
|
131
|
+
Native Stripe metered billing supports pay as you go, included monthly units with
|
|
132
|
+
overages, and payment-backed prepaid credits through `stripe.usage`. The package
|
|
133
|
+
owns scoped atomic recording, reservations, durable delivery, reconciliation,
|
|
134
|
+
allowance/credit accounting, corrections and original-payment settlement.
|
|
135
|
+
Hosts authorize billable work and choose units, prices and policies.
|
|
136
|
+
|
|
137
|
+
Start with [sandbox setup](metering-setup.md) and [public model recipes](metered-usage.md).
|
|
138
|
+
The [example walkthrough](usage-example.md) demonstrates all three models using
|
|
139
|
+
the package's [reusable React workflows](usage-react.md) and
|
|
140
|
+
[configuration UI](usage-configuration.md). See [verification and limits](usage-verification.md)
|
|
141
|
+
for actual native evidence and [opt-in rollout](usage-rollout.md) for adoption,
|
|
142
|
+
drain, model transitions and rollback. Metronome is not required.
|
|
132
143
|
|
|
133
144
|
## Resources
|
|
134
145
|
|
package/docs/react-api.md
CHANGED
|
@@ -2,7 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
## React Hooks
|
|
4
4
|
|
|
5
|
-
Import from `@fantastic.dev/better-stripe/react`.
|
|
5
|
+
Import from `@fantastic.dev/better-stripe/react`. Read factories accept the host's Convex query binding. Command workflows use
|
|
6
|
+
host callbacks, Convex mutations/actions or Stripe.js according to the flow.
|
|
7
|
+
Authenticate and authorize those host endpoints; a React component is not an
|
|
8
|
+
authorization boundary.
|
|
6
9
|
|
|
7
10
|
Read hooks are exported as factory functions that take the app's `useQuery` binding and a query function reference, allowing them to work with any component registration name. Hooks that take a single ID argument accept `undefined` and skip the query (via Convex's `"skip"` sentinel) until the ID is available.
|
|
8
11
|
|
|
@@ -226,7 +229,7 @@ currency support. See the [React workflow guide](react-workflows.md).
|
|
|
226
229
|
|
|
227
230
|
| Component | Description |
|
|
228
231
|
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
229
|
-
| `PayoutSchedule` | Recipient balance + next-payout display, fed by a `balance` snapshot and `listPayouts` rows.
|
|
232
|
+
| `PayoutSchedule` | Recipient balance + next-payout display, fed by a `balance` snapshot and `listPayouts` rows. This display component offers no manual-withdrawal action; the package's separate payout policy and command APIs remain available. |
|
|
230
233
|
| `EarningsSummary` | Gross / reversals & adjustments / net + latest payout, fed by `useEarnings(accountId)`. Reversals cover both deferred fee collection and refund/dispute clawbacks — not a pure fees figure, hence the "Reversals & adjustments" label rather than "Fees". |
|
|
231
234
|
| `SplitBreakdown` | Per-sale store / affiliate / other / platform split lines, fed by `useSplitBreakdown`. The platform line reads "unknown" (not $0) when the hook wasn't given the sale amount. |
|
|
232
235
|
|
|
@@ -243,6 +246,10 @@ The app-owned alternative to [Embedded Disputes](#embedded-disputes-stripe-conne
|
|
|
243
246
|
|
|
244
247
|
### Embedded Disputes (Stripe Connect)
|
|
245
248
|
|
|
249
|
+
`createDisputeSession` is a trusted server API. Authenticate the caller and
|
|
250
|
+
resolve/authorize their original seller account before creating an AccountSession.
|
|
251
|
+
Never expose a public action that forwards an arbitrary browser account ID.
|
|
252
|
+
|
|
246
253
|
The Stripe-hosted alternative to the headless dispute components: each seller
|
|
247
254
|
views and responds to their own disputes via Stripe's embedded `disputes_list`
|
|
248
255
|
/ `payment_disputes` components, driven by the Account Session that
|
|
@@ -256,10 +263,14 @@ views and responds to their own disputes via Stripe's embedded `disputes_list`
|
|
|
256
263
|
**Dependencies:** the wrapper uses [`@stripe/react-connect-js`](https://www.npmjs.com/package/@stripe/react-connect-js) and [`@stripe/connect-js`](https://www.npmjs.com/package/@stripe/connect-js), which ship as regular dependencies of this package (same convention as `@stripe/react-stripe-js` / `@stripe/stripe-js`) -- no extra install step. ConnectJS components are client-only iframes; render them in client components.
|
|
257
264
|
|
|
258
265
|
```tsx
|
|
259
|
-
// convex/stripe.ts
|
|
266
|
+
// convex/stripe.ts, server side.
|
|
267
|
+
// Implement this helper using ctx.auth and the original seller-account mapping.
|
|
260
268
|
export const createDisputeSession = action({
|
|
261
|
-
args: {
|
|
262
|
-
handler: async (ctx
|
|
269
|
+
args: {},
|
|
270
|
+
handler: async (ctx) => {
|
|
271
|
+
const stripeAccountId = await requireAuthorizedSellerAccount(ctx);
|
|
272
|
+
return stripe.createDisputeSession(ctx, { stripeAccountId });
|
|
273
|
+
},
|
|
263
274
|
});
|
|
264
275
|
|
|
265
276
|
// Seller disputes page (client side)
|
|
@@ -268,14 +279,12 @@ import {
|
|
|
268
279
|
EmbeddedDisputes,
|
|
269
280
|
} from "@fantastic.dev/better-stripe/react";
|
|
270
281
|
|
|
271
|
-
function SellerDisputes(
|
|
282
|
+
function SellerDisputes() {
|
|
272
283
|
const createSession = useAction(api.stripe.createDisputeSession);
|
|
273
284
|
return (
|
|
274
285
|
<ConnectProvider
|
|
275
286
|
publishableKey={import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY}
|
|
276
|
-
fetchClientSecret={async () =>
|
|
277
|
-
(await createSession({ stripeAccountId })).clientSecret
|
|
278
|
-
}
|
|
287
|
+
fetchClientSecret={async () => (await createSession({})).clientSecret}
|
|
279
288
|
>
|
|
280
289
|
<EmbeddedDisputes />
|
|
281
290
|
</ConnectProvider>
|
package/docs/testing.md
CHANGED
|
@@ -4,26 +4,36 @@ Import from `@fantastic.dev/better-stripe/testing`.
|
|
|
4
4
|
|
|
5
5
|
### assertTestEnvironment
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Validate the exact secret used to construct a raw stripe-node client before
|
|
8
|
+
running native fixtures. The helper accepts an explicit key or falls back to
|
|
9
|
+
`process.env.STRIPE_SECRET_KEY`:
|
|
8
10
|
|
|
9
11
|
```typescript
|
|
10
12
|
import { assertTestEnvironment } from "@fantastic.dev/better-stripe/testing";
|
|
11
13
|
|
|
12
|
-
assertTestEnvironment(); // Throws
|
|
14
|
+
assertTestEnvironment(process.env.STRIPE_SECRET_KEY); // Throws for missing/non-test keys.
|
|
13
15
|
```
|
|
14
16
|
|
|
15
17
|
### Fixture Factories
|
|
16
18
|
|
|
17
|
-
Typed factories
|
|
19
|
+
Typed factories create Stripe sandbox resources through a raw `Stripe` SDK,
|
|
20
|
+
not a `BetterStripe` instance:
|
|
18
21
|
|
|
19
22
|
```typescript
|
|
23
|
+
import Stripe from "stripe";
|
|
20
24
|
import {
|
|
25
|
+
assertTestEnvironment,
|
|
21
26
|
createTestAccount,
|
|
22
27
|
createTestPrice,
|
|
23
28
|
createTestProduct,
|
|
24
29
|
createTestSubscription,
|
|
25
30
|
} from "@fantastic.dev/better-stripe/testing";
|
|
26
31
|
|
|
32
|
+
const key = process.env.STRIPE_SECRET_KEY;
|
|
33
|
+
if (!key) throw new Error("Sandbox key required");
|
|
34
|
+
assertTestEnvironment(key);
|
|
35
|
+
const stripe = new Stripe(key);
|
|
36
|
+
|
|
27
37
|
const account = await createTestAccount(stripe, { email: "test@example.com" });
|
|
28
38
|
const product = await createTestProduct(stripe, { name: "Pro Plan" });
|
|
29
39
|
const price = await createTestPrice(stripe, {
|
|
@@ -33,6 +43,16 @@ const price = await createTestPrice(stripe, {
|
|
|
33
43
|
});
|
|
34
44
|
```
|
|
35
45
|
|
|
46
|
+
Keep the validated key and SDK instance together. The factories' internal guard
|
|
47
|
+
can fall back to the process environment when the SDK does not expose its key;
|
|
48
|
+
it does not independently attest an arbitrary SDK client. Do not pass a different
|
|
49
|
+
client while validating only the environment's test key.
|
|
50
|
+
|
|
51
|
+
These helpers create native Stripe test resources, not component mirror rows.
|
|
52
|
+
`createTestSubscription` takes a classic Stripe Customer ID in `customerId`;
|
|
53
|
+
do not pass an Accounts v2 `acct_...` ID there. Use the configured public
|
|
54
|
+
BetterStripe subscription APIs for Accounts v2 application flows.
|
|
55
|
+
|
|
36
56
|
### Mock Webhook Events
|
|
37
57
|
|
|
38
58
|
Factories for creating mock webhook events in tests:
|
|
@@ -46,7 +66,12 @@ import {
|
|
|
46
66
|
} from "@fantastic.dev/better-stripe/testing";
|
|
47
67
|
|
|
48
68
|
const event = mockCheckoutCompleted({
|
|
49
|
-
|
|
69
|
+
id: "cs_test_123",
|
|
50
70
|
metadata: { userId: "user_abc" },
|
|
51
71
|
});
|
|
52
72
|
```
|
|
73
|
+
|
|
74
|
+
`mockAccountUpdated` produces a classic `account.updated` snapshot fixture.
|
|
75
|
+
It is not an Accounts v2 thin-event fixture. Thin-event tests must supply the
|
|
76
|
+
appropriate event reference and mock the original provider lookup separately.
|
|
77
|
+
The factories construct test payloads; they do not sign HTTP webhook requests.
|
|
@@ -39,8 +39,11 @@ unavailable estimates. A plan or price change on the same item does not reset
|
|
|
39
39
|
the local allowance. Estimates exclude taxes, discounts, fixed
|
|
40
40
|
fees, rounding and other invoice lines. They are not finalized amounts or limits
|
|
41
41
|
that authorize work. Strict allowance reservations are implemented separately.
|
|
42
|
-
|
|
43
|
-
|
|
42
|
+
The generic usage summary always leaves prepaid estimate/credit fields
|
|
43
|
+
unavailable with `credit_balance_requires_scoped_reader`. Read the original
|
|
44
|
+
binding's `stripe.usage.getCreditBalance` and purchase reconciliation separately;
|
|
45
|
+
see [payment-backed credits](usage-credits.md). A usage summary never infers
|
|
46
|
+
available credits from consumed units, even after a credit account is configured.
|
|
44
47
|
|
|
45
48
|
`read(ctx, {scope, page: {period, limit, cursor}})` returns immutable event history
|
|
46
49
|
with current delivery state. For an event's delivery audit:
|
package/docs/webhooks.md
CHANGED
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
Register the webhook endpoint on your Convex HTTP router:
|
|
8
8
|
|
|
9
9
|
```typescript
|
|
10
|
-
import {
|
|
10
|
+
import { stripe } from "./stripe"; // Your configured BetterStripe instance.
|
|
11
11
|
|
|
12
|
-
registerRoutes(http,
|
|
12
|
+
stripe.registerRoutes(http, {
|
|
13
13
|
webhookPath: "/stripe/webhook", // Default path
|
|
14
14
|
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
|
|
15
15
|
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
|
|
@@ -47,7 +47,15 @@ const v2 = await stripe.setupEventDestination(ctx, {
|
|
|
47
47
|
});
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
-
The method
|
|
50
|
+
The method finds an existing destination matching URL and payload type and
|
|
51
|
+
updates its events, or creates a new one. It rejects incompatible existing
|
|
52
|
+
snapshot versions and customer-preview event scopes instead of silently
|
|
53
|
+
migrating them. Preserve the original destination and signing secret until its
|
|
54
|
+
explicit replacement is configured. See [preview webhook migration](accounts-v2-preview.md).
|
|
55
|
+
|
|
56
|
+
The instance method `stripe.registerRoutes` inherits the configured SDK key and
|
|
57
|
+
API version. Standalone `registerRoutes(http, components.betterStripe, config)`
|
|
58
|
+
remains available; supply the same `stripeApiVersion` explicitly for a preview client.
|
|
51
59
|
|
|
52
60
|
#### Admin UI setup
|
|
53
61
|
|
|
@@ -57,12 +65,19 @@ The example app includes an `/admin/setup` page that handles webhook creation, e
|
|
|
57
65
|
|
|
58
66
|
```typescript
|
|
59
67
|
import {
|
|
60
|
-
BETTER_STRIPE_WEBHOOK_EVENTS, // V1 snapshot
|
|
61
|
-
BETTER_STRIPE_V2_WEBHOOK_EVENTS, // V2 thin
|
|
62
|
-
ALL_BETTER_STRIPE_EVENTS, // Combined
|
|
68
|
+
BETTER_STRIPE_WEBHOOK_EVENTS, // Default V1 snapshot event names
|
|
69
|
+
BETTER_STRIPE_V2_WEBHOOK_EVENTS, // Default Connect V2 thin event names
|
|
70
|
+
ALL_BETTER_STRIPE_EVENTS, // Combined defaults, not every optional event handler
|
|
63
71
|
} from "@fantastic.dev/better-stripe";
|
|
64
72
|
```
|
|
65
73
|
|
|
74
|
+
Customer-only preview clients select `BETTER_STRIPE_CUSTOMER_ACCOUNT_EVENTS`
|
|
75
|
+
for their default thin destination instead of the Connect list. Metered billing
|
|
76
|
+
also handles `v1.billing.meter.error_report_triggered` and
|
|
77
|
+
`v1.billing.meter.no_meter_found` as signed thin events. Those names are not in
|
|
78
|
+
`ALL_BETTER_STRIPE_EVENTS`; configure them explicitly as described in
|
|
79
|
+
[asynchronous metering errors](usage-delivery.md#receive-asynchronous-native-validation-errors).
|
|
80
|
+
|
|
66
81
|
### Event Processing
|
|
67
82
|
|
|
68
83
|
Records synced from Stripe objects without `userId` metadata are stored unattributed (`userId: ""`) and are not returned by user-scoped queries.
|
|
@@ -70,11 +85,34 @@ Records synced from Stripe objects without `userId` metadata are stored unattrib
|
|
|
70
85
|
The webhook handler processes events through these steps:
|
|
71
86
|
|
|
72
87
|
1. Verify Stripe signature
|
|
73
|
-
2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `
|
|
88
|
+
2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `processed`, `ignored`, or still within its processing lease, return 200 immediately. A stale processing lease can be retried. If the previous delivery `failed` (its writes rolled back), the ledger row is reset and the event is reprocessed on Stripe's retry.
|
|
74
89
|
3. Upsert the component-owned domain table. When `webhooks` is configured, the upsert runs through `syncWebhook` — an internal mutation that performs the upsert **and** the sync trigger in the same transaction.
|
|
75
90
|
4. On failure, mark the ledger row `failed` and return 500 so Stripe retries; otherwise mark it `processed`
|
|
76
91
|
5. Schedule the matching `after*` async hook via `ctx.scheduler` (separate action)
|
|
77
92
|
|
|
93
|
+
### Required V1 hook delivery
|
|
94
|
+
|
|
95
|
+
By default, `onEvent` and `events[type]` callbacks are best-effort.
|
|
96
|
+
For selected verified V1 events, `retryOnHookError(event)` can require them to
|
|
97
|
+
succeed before acknowledgment:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
retryOnHookError: (event) => event.type === "checkout.session.completed",
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
For that selection, component processing commits first; the callbacks run before
|
|
104
|
+
the event is marked processed. Callback failures return 500 and permit redelivery.
|
|
105
|
+
A concurrent in-flight delivery returns 503, and a failed reservation/completion
|
|
106
|
+
also returns 500. An abandoned processing lease becomes retryable after ten
|
|
107
|
+
minutes. Sync triggers and callbacks must remain idempotent by `event.id` or a
|
|
108
|
+
durable business key because they can run again after partial success.
|
|
109
|
+
|
|
110
|
+
Unselected callbacks, V2 hooks and scheduled `asyncWebhook` hooks keep best-effort
|
|
111
|
+
acknowledgment behavior. Required fulfillment belongs in the selected V1
|
|
112
|
+
`onEvent`/`events` path, not a scheduled hook. Refund synchronization independently
|
|
113
|
+
requires ledger success even without an application retry selector. See
|
|
114
|
+
[the migration contract](../MIGRATION.md#remove-dojos-consumer-patch).
|
|
115
|
+
|
|
78
116
|
### Ledger-Based Deduplication
|
|
79
117
|
|
|
80
118
|
The component maintains a `webhookEvents` table that tracks every event by its Stripe event ID. This provides:
|
package/package.json
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.68.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.68.1",
|
|
4
|
+
"description": "Convex component for Stripe Accounts v2, subscriptions, metered billing and Connect marketplaces, with React workflows.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
7
7
|
"convex",
|
|
8
|
-
"component"
|
|
8
|
+
"component",
|
|
9
|
+
"billing",
|
|
10
|
+
"subscriptions",
|
|
11
|
+
"metered-billing",
|
|
12
|
+
"usage-based-billing",
|
|
13
|
+
"stripe-connect",
|
|
14
|
+
"react"
|
|
9
15
|
],
|
|
10
16
|
"homepage": "https://github.com/FantasticDevHQ/better-stripe#readme",
|
|
11
17
|
"bugs": {
|
|
@@ -61,63 +67,11 @@
|
|
|
61
67
|
"files": [
|
|
62
68
|
"dist",
|
|
63
69
|
"src",
|
|
64
|
-
"docs
|
|
65
|
-
"docs/
|
|
66
|
-
"docs/affiliate-clawbacks.md",
|
|
67
|
-
"docs/accounts-v2-preview.md",
|
|
68
|
-
"docs/react-workflows-audit.md",
|
|
69
|
-
"CHANGELOG.md",
|
|
70
|
-
"MIGRATION.md",
|
|
71
|
-
"docs/read-contracts.md",
|
|
72
|
-
"docs/billing-history.md",
|
|
73
|
-
"docs/subscription-payment-methods.md",
|
|
74
|
-
"docs/invoice-payment-pages.md",
|
|
75
|
-
"docs/checkout-session-pages.md",
|
|
76
|
-
"docs/refund-context.md",
|
|
77
|
-
"docs/refund-command-evidence.md",
|
|
78
|
-
"docs/personal-account-mapping.md",
|
|
79
|
-
"docs/financial-ownership.md",
|
|
80
|
-
"docs/financial-observations.md",
|
|
81
|
-
"docs/architecture/component-extraction.md",
|
|
82
|
-
"docs/architecture/durable-execution.md",
|
|
83
|
-
"docs/architecture/recovery-workflow.md",
|
|
84
|
-
"docs/balance-funding-state.md",
|
|
85
|
-
"docs/balance-funding-workflow.md",
|
|
86
|
-
"docs/processing-cost-reconciliation.md",
|
|
87
|
-
"docs/example-balance-funding-cutover.md",
|
|
88
|
-
"docs/example-recovery-cutover.md",
|
|
89
|
-
"docs/releasing.md",
|
|
90
|
-
"docs/release-handoff.md",
|
|
91
|
-
"docs/setup-intent-recovery.md",
|
|
92
|
-
"docs/metered-usage.md",
|
|
93
|
-
"docs/metering-setup.md",
|
|
94
|
-
"docs/README.md",
|
|
95
|
-
"docs/overview.md",
|
|
96
|
-
"docs/client-api.md",
|
|
97
|
-
"docs/webhooks.md",
|
|
98
|
-
"docs/marketplace.md",
|
|
99
|
-
"docs/react-api.md",
|
|
100
|
-
"docs/testing.md",
|
|
101
|
-
"docs/configuration.md",
|
|
102
|
-
"docs/architecture.md",
|
|
103
|
-
"docs/development.md",
|
|
104
|
-
"docs/usage-ledger.md",
|
|
105
|
-
"docs/usage-catalog.md",
|
|
106
|
-
"docs/usage-delivery.md",
|
|
107
|
-
"docs/usage-observations.md",
|
|
108
|
-
"docs/usage-subscriptions.md",
|
|
109
|
-
"docs/usage-credits.md",
|
|
110
|
-
"docs/usage-limits.md",
|
|
111
|
-
"docs/usage-corrections.md",
|
|
112
|
-
"docs/usage-settlement.md",
|
|
113
|
-
"docs/usage-security.md",
|
|
114
|
-
"docs/usage-react.md",
|
|
70
|
+
"docs/*.md",
|
|
71
|
+
"docs/architecture/*.md",
|
|
115
72
|
"docs/evidence/native-metering",
|
|
116
|
-
"
|
|
117
|
-
"
|
|
118
|
-
"docs/payout-revision-migration.md",
|
|
119
|
-
"docs/usage-verification.md",
|
|
120
|
-
"docs/usage-rollout.md"
|
|
73
|
+
"CHANGELOG.md",
|
|
74
|
+
"MIGRATION.md"
|
|
121
75
|
],
|
|
122
76
|
"scripts": {
|
|
123
77
|
"build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
|
|
@@ -153,7 +107,8 @@
|
|
|
153
107
|
"check:ci-parity": "repo-gates check-ci-parity",
|
|
154
108
|
"check:coverage": "node scripts/check-coverage.mjs",
|
|
155
109
|
"format:check": "pnpm run format",
|
|
156
|
-
"check:agents": "repo-gates check-agents"
|
|
110
|
+
"check:agents": "repo-gates check-agents",
|
|
111
|
+
"check:package": "pnpm run build:clean && vitest run scripts/documentation-contracts.test.mjs scripts/packed-docs.test.mjs scripts/public-docs.test.mjs scripts/usage-contracts-packed.test.mjs scripts/usage-composition-packed.test.mjs scripts/usage-models-packed.test.mjs"
|
|
157
112
|
},
|
|
158
113
|
"dependencies": {
|
|
159
114
|
"@convex-dev/workflow": "0.4.10",
|