@fantastic.dev/better-stripe 0.68.0 → 0.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -88,32 +88,42 @@ The persona switcher is test-only, not production authentication. In an applicat
88
88
  authenticate callers and resolve/authorize original payer, product, price, activity
89
89
  and recipient policy on the server. See [usage security](usage-security.md).
90
90
 
91
- ## Verify each model
92
-
93
- Choose one model, then Set up sandbox. Setup retains its original resource IDs
94
- across retries. Defaults below are this example's USD 1 per whole-call fixture;
95
- applications choose their own units, precision and policies.
96
-
97
- | Model | Exercise | Expected result |
98
- | ---------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
99
- | Pay as you go | Three five-call jobs, replay one, observe, close/resume period | Effective/native 15, original usage invoice USD 15; replay adds no work or usage |
100
- | Included monthly usage | Ten included calls, then another five | 15 consumed, 10 included, 5 overage; original usage invoice USD 5 |
101
- | Paid prepaid | Try work unpaid, buy/confirm ten units, consume twice, try more | Unpaid work held, verified grant 10, consumed 10, excess denied; original purchase USD 10, usage invoice USD 0 |
102
-
103
- Follow [the complete walkthrough](usage-example.md) for correction, delivery,
104
- original payment/fee/transfer proof and cleanup. Aggregation may lag; refresh an
105
- original request rather than inventing another event ID. Close/resume waits for
106
- complete local/native equality, zero reservations and resolved correction/purchase
107
- intents before advancing only that fixture's test clock. Future renewal allowance
108
- is `not_active_yet` until its period is active on the real server. Do not forge
109
- future timestamps or show a fake zero balance.
110
-
111
- Archive/resume cleanup only after original paid invoice, cash and settlement
112
- verification. Cleanup rechecks fresh original financial evidence; unresolved
113
- payments, refunds, disputes, reservations, unknown sends and credit liabilities
114
- remain retained. Only owned test resources are stopped. Payers, clocks and all
115
- financial history remain. Unspent paid credits require original-source recovery;
116
- reset does not delete them. After successful archive, configure a new isolated run.
91
+ ## Verify the product flows
92
+
93
+ Set the server-owned checkout return origin to your Vite URL. This value is not a
94
+ secret. For a default Vite server:
95
+
96
+ ```sh
97
+ pnpm exec convex env set FRONTEND_URL http://localhost:5173
98
+ ```
99
+
100
+ Use `http://localhost:4319` instead when Vite is running on port 4319. Set this
101
+ before creating an enrollment. The example retains the original return origin
102
+ with that enrollment, so changing the environment does not rewrite an existing
103
+ Checkout intent.
104
+
105
+ Choose Seller → Maya's Fitness Studio → Metered billing. Attach Included monthly
106
+ usage to the coaching membership product. The default terms are USD 20 monthly,
107
+ 60 included coaching minutes and USD 1 per extra minute. Compare the via API and
108
+ BetterStripe components tabs before and after attachment.
109
+
110
+ Choose Customer, review the membership, complete its original test Checkout,
111
+ refresh enrollment, and record coaching minutes. Admin → Metered billing controls
112
+ store enablement separately. Sasha's Ceramics starts disabled. For pay as you go,
113
+ create another coaching product with a zero monthly base price. For prepaid,
114
+ configure the admin's own Store analytics reports product and verify that work is
115
+ held before a paid grant and denied after credit exhaustion.
116
+
117
+ Follow [the product walkthrough](usage-example.md) for exact steps, authorization,
118
+ payment verification, retained history and the mixed-invoice seller-settlement
119
+ limitation. Product subscriptions use actual native billing periods and the
120
+ customer's original account; this flow does not advance shared test clocks.
121
+
122
+ For isolated clock-driven renewal, correction and cleanup checks, use Admin →
123
+ Developer protocol diagnostics and follow the separate
124
+ [protocol diagnostics guide](usage-protocol-diagnostics.md). Those runs retain
125
+ their dedicated original resources and financial evidence. Never use diagnostic
126
+ cleanup to archive a seller's shared product or a real customer's account.
117
127
 
118
128
  ## Install in your own Convex application
119
129
 
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** -- Full CRUD with trial day management as a first-class feature
7
- - **Checkout** -- Both embedded (custom UI mode) and redirect checkout session creation
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
- 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.
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`. All hooks use Convex's `useQuery` and `useMutation` internally.
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. Payouts are automatic/rolling — no manual-withdrawal action is offered. |
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 — expose the account session (server side)
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: { stripeAccountId: v.string() },
262
- handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
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({ stripeAccountId }: { stripeAccountId: string }) {
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
- Guards against running test fixtures with live Stripe keys:
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 if STRIPE_SECRET_KEY does not start with sk_test_
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 for creating Stripe test data:
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
- stripeSessionId: "cs_test_123",
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.