@fantastic.dev/better-stripe 0.68.1 → 0.70.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.
@@ -1,250 +1,165 @@
1
- # Run all three native billing models
2
-
3
- The example at `/demo/metered-usage` uses the public BetterStripe package against a
4
- Stripe sandbox. It provisions a dedicated Accounts v2 customer, test clock,
5
- product, meter, price and managed subscription per persona and model. Usage,
6
- delivery, allowance reservations, credits, corrections and settlement live in the
7
- component. The example stores fixture provenance and synthetic application work.
8
-
9
- Start with [sandbox setup](metering-setup.md). Use your existing Stripe sandbox;
10
- no Metronome account or token is needed. Run the example backend and frontend
11
- from the `example` directory with `pnpm dev`. Keep test keys in the backend
12
- Convex environment. Do not copy secret values into commands, screenshots, source
13
- files or browser storage.
14
-
15
- ## Demo security model
16
-
17
- This repository's persona switcher is a test-only convenience, not authentication.
18
- Choose Customer, Seller or Admin, then Metered billing. Each operation rechecks
19
- the server's persona binding and test key. If an authenticated identity is present,
20
- it must match the persona's stored token identifier. Visitor and affiliate
21
- personas cannot operate the workflow. Do not expose these demo endpoints as a
22
- production billing service.
23
-
24
- In your app, replace the persona lookup with real authentication and server-owned
25
- customer, product, entitlement and recipient authorization. Never trust a browser
26
- account ID, product ID, price, rate or settlement policy. See
27
- [authorization and recovery](usage-security.md).
28
-
29
- Admin and seller personas can configure the unit, precision, currency, exact price,
30
- version and model-specific terms before setup. Customers run the server-owned
31
- defaults. Setup retries retain the original native identities and configuration.
32
- A saved meter and subscription keep their original terms. Archive a resolved run
33
- before configuring its replacement.
1
+ # Attach metered billing to products
2
+
3
+ The example at `/demo/metered-usage` connects native Stripe metering to the same
4
+ catalog products that sellers and admins manage elsewhere in the app. It uses the
5
+ public BetterStripe APIs and React workflows. No Metronome account is required.
6
+
7
+ ## Try Maya's coaching membership
8
+
9
+ 1. Start the example with the [setup guide](metering-setup.md). Choose Seller and
10
+ Maya's Fitness Studio, then Metered billing. Maya has metered billing enabled
11
+ by default. Sasha's Ceramics starts disabled and continues selling its regular
12
+ products without usage charges.
13
+ 2. Select an existing product, or create **Fitness Coaching Membership** under
14
+ Products. Each product row links to its metered billing settings.
15
+ 3. Choose Included monthly usage. The example defaults to a **USD 20 monthly
16
+ base fee, 60 coaching minutes included per billing period, then USD 1 per
17
+ extra minute**. Adjust the terms before attaching them.
18
+ 4. Compare **via API** and **BetterStripe components**, then Attach billing to
19
+ product. Both create the same server-authorized product offering. The server
20
+ pins the original product, configuration, meter and prices. Once attached,
21
+ terms are read-only in both views. Create another product for different terms;
22
+ this example does not migrate existing subscribers to a new price.
23
+ 5. Choose Customer. The store lists the membership with its base fee, included
24
+ minutes and overage rate. Review membership opens Your metered services.
25
+ Subscribe to this product creates or resumes the original Stripe Checkout.
26
+ Seed the example's customer accounts in Admin → Setup first if they are missing.
27
+ 6. Open Stripe Checkout and pay with test card `4242 4242 4242 4242`, a future
28
+ expiry and any test CVC. Return to Metered billing and Refresh enrollment.
29
+ Checkout redirects and an `active` subscription alone do not authorize work.
30
+ 7. Complete a coaching session with its actual number of minutes. For example,
31
+ 75 minutes consumes the 60 included minutes and records 15 overage minutes.
32
+ The package reserves allowance, records usage and commits the example's
33
+ completed-session marker in one Convex mutation. Delivery runs afterward.
34
+ 8. Compare the headless usage/history UI with `UsageBilling` and `UsageHistory`.
35
+ Accepted usage is an estimate; native aggregation can lag. Overage appears on
36
+ Stripe's monthly invoice, separately from the monthly base fee. Preview next
37
+ invoice reads Stripe's current draft estimate, including the fixed fee. Cancel
38
+ renewal stops the next renewal while retaining the original current period,
39
+ usage history and any unused credit liabilities.
40
+
41
+ The new product flow reuses the customer's existing, server-linked Accounts v2
42
+ account from the example's account setup and its original
43
+ subscription periods. It does not create a new payer or test clock for every
44
+ visit, advance shared customers into the future, or archive shared products.
45
+ The original checkout intent is reused across integration views and retries.
46
+ A failed coaching request keeps its original identity and quantity in the tab's
47
+ session storage so a reload can retry it without accepting new units. This is a
48
+ demo convenience, not authorization. External coaching or report services still
49
+ need their own durable idempotent work protocol.
50
+
51
+ ## Admin and store access
52
+
53
+ Admin → Metered billing contains independent **Store access** controls and
54
+ **Platform service products**. Enable Sasha only when that store needs metered
55
+ products. Server-side checks enforce store enablement and original product
56
+ ownership; the browser cannot grant itself access.
57
+
58
+ Disabling a store stops new configuration and new enrollment intents. Pending
59
+ unpaid checkout creation/resumption is blocked while disabled. An already paid,
60
+ original Checkout can still be reconciled. Existing purchased subscriptions keep
61
+ serving their original terms and retain their usage/history. Disabling is not
62
+ cancellation or a refund, and does not retire shared Stripe resources.
63
+
64
+ An admin configures the platform's own products. A seller configures only its own
65
+ products. Admins enable stores separately; enabling a store does not change its
66
+ prices or subscribe anyone.
34
67
 
35
68
  ## Pay as you go
36
69
 
37
- 1. Select Pay as you go, then Set up sandbox.
38
- 2. Run five units three times. The default price is USD 1 per call.
39
- 3. Replay last work. Its source identity, quantity and occurrence time stay fixed;
40
- the synthetic application work and usage acceptance happen once.
41
- 4. Observe native usage. If delivery is queued, use Resume queued deliveries.
42
- Stripe aggregation is asynchronous. Refresh until the aggregate is 15.
43
- 5. Close or resume original billing period. This fences new work, checks complete
44
- local/native equality, drains reservations and checks every correction and
45
- purchase intent. It advances only this run's test clock.
46
- 6. Resume after the clock is ready. The server finds the unique original cycle
47
- invoice, verifies its meter lines, finalizes it and pays with Stripe's sandbox
48
- card. The default invoice is USD 15.
49
-
50
- The outcome separately shows invoice payment, original cash verification, actual
51
- processing fees and any verified recipient transfers. A paid invoice alone does
52
- not imply that settlement is ready.
53
-
54
- ## Included monthly usage and overages
55
-
56
- Select Included monthly usage. The defaults include ten calls per original
57
- monthly period, then USD 1 per additional call. Run three five-unit jobs. The
58
- package allowance view shows 15 consumed, ten included, five billable overage
59
- units and the soft-limit warning at 12. The native invoice is USD 5.
60
-
61
- Closing the period observes the next native subscription period. When that period
62
- is active on the Convex server, its separate allowance starts at zero consumed
63
- and ten remaining included units. The old period and history stay unchanged. A
64
- test clock can move ahead of real time; future renewal allowance is explicitly
65
- unavailable. Its view stays read-only until the period is active on the server and
66
- new event times are inside the provider's real acceptance window. This demo does not forge
67
- future work timestamps to simulate another month's consumption.
70
+ Create a separate Maya product such as **Additional coaching minutes** and choose
71
+ Pay as you go. Set the monthly base fee to zero and the unit price to USD 1 per
72
+ minute. Customers enroll through Checkout, then record completed coaching
73
+ minutes. Stripe bills the units at the end of the native monthly period.
74
+ A positive base fee is also supported and shares the metered subscription.
68
75
 
69
76
  ## Paid prepaid credits
70
77
 
71
- 1. Select Prepaid credits and set up its dedicated sandbox resources.
72
- 2. Run five units before funding. Work is held and does not execute.
73
- 3. Create credit purchase. The default original purchase is ten units for USD 10.
74
- Pending payment grants no usable credit.
75
- 4. Confirm sandbox card. The backend uses Stripe's test card and the package
76
- verifies the original captured PaymentIntent, customer and paid credit grant.
77
- 5. Run two five-unit jobs. Replay a successful job before creating another one to
78
- demonstrate idempotency. Another five-unit job is denied after exhaustion.
79
- 6. Observe native usage, then close and resume the period. The native credit grant
80
- covers the consumption invoice. The demo refuses to pay any positive prepaid
81
- invoice remainder with a second cash payment.
82
-
83
- The USD 10 purchase is the only cash source. Credit consumption collects no new
84
- cash. The package reconciles native credit transactions against complete invoice
85
- history. Unavailable observations are shown explicitly, never as a zero balance.
86
-
87
- For production, send the package purchase result's `clientSecret` only to the
88
- properly authenticated purchaser's Stripe payment UI. Do not store or log it.
89
- Confirming a payment in the UI is not proof of usable credits; call
90
- `observeCreditPurchase` and wait for the verified ready grant. See
91
- [paid credit accounting](usage-credits.md).
92
-
93
- Prepaid is limited to the issuer's own services. A seller persona cannot redeem
94
- credits into reseller proceeds. An authorized affiliate can be paid once from the
95
- original purchase; usage does not produce another affiliate sale.
96
-
97
- ## Corrections and retained failures
98
-
99
- Before closing, Correct last accepted event cancels its original native event
100
- through the package. Repeated correction requests keep the same correction ID.
101
- Wait for confirmation and native reaggregation. A new application job can then
102
- use the released capacity. For example, record 15 units, cancel the last five,
103
- then record a different five-unit job. Effective usage is 15, and history retains
104
- 20 originally accepted units plus the five canceled units.
105
-
106
- Unknown delivery outcomes stay held. Resume queued deliveries schedules only
107
- records that the package still classifies as queued; it never resends unknown
108
- attempts. Do not replace the source event ID, change the occurrence time, create
109
- a new run to relabel the same work or invent a provider event identifier. Resolve
110
- the original attempt with verified native evidence using the operational runbook.
111
- A billing or cleanup guard failure preserves all work, purchase and correction
112
- intents for reconciliation.
113
-
114
- The fixture timestamps _new synthetic jobs_ at its retained test clock's original
115
- period start. This keeps native meter events and paid grants on the same logical
116
- clock. Retrying a job never changes that timestamp. Real applications must use
117
- the actual occurrence time of their business event. Delivery checks both real
118
- provider limits and an attached sandbox clock before a native event write.
119
-
120
- ## Ownership and routing
121
-
122
- Customer and admin runs use direct issuer billing. Seller runs pin their original
123
- server-owned seller account and, when available, an existing demo affiliate at
124
- setup. The demo policy is a 10% inclusive platform fee and a 20% affiliate share
125
- of the eligible remainder, with recurring commission eligibility. The package
126
- uses actual processing fees and verifies native payment provenance, recipient
127
- capabilities and transfer identity. Unsupported Connect configurations remain
128
- held. Accounts v2 payer configuration is separate from merchant or recipient
129
- configuration; a customer account is not automatically eligible to receive money.
130
- Prepaid settlement retains issuer revenue and accepts only eligible affiliate
131
- policy, never seller or collaborator redemption.
132
-
133
- ## Scoped cleanup and reset
134
-
135
- Cleanup re-reads the original paid invoice, payment and settlement before stopping
136
- resources. Saved success alone cannot authorize a reset after a refund, dispute or
137
- incomplete settlement recovery. Unavailable fresh evidence keeps the run retained.
138
-
139
- Use Archive or resume scoped cleanup after the original invoice and cash evidence
140
- are verified. It refuses unresolved delivery, corrections, reservations, purchases,
141
- credit backing or settlement. Unspent paid credits require verified refund or
142
- expiry; cleanup cannot wipe them.
143
-
144
- Cleanup requests period-end cancellation, advances only the owned test clock to
145
- the cancellation boundary, checks the final native cycle invoice and retires the
146
- managed enrollment. It deactivates only the owned price, meter and product. It
147
- retains the native payer, clock, invoice/payment evidence and every component
148
- history record. It does not clear any Convex table or another developer's data.
149
- After successful archival, Start new sandbox run creates new isolated resources.
150
- Admin or seller can save a new version before starting that replacement.
151
-
152
- Empty or unresolved runs can require operator reconciliation rather than automatic
153
- archive. In particular, unknown provider outcomes must remain visible and retained.
154
- Never delete a clock or payer to make financial evidence disappear.
155
-
156
- ## Model configuration snippets
157
-
158
- Use the same versioned unit and exact minor-currency rate in each model:
159
-
160
- ```ts
161
- import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
162
- const terms = {
163
- key: "api-calls",
164
- version: "v1",
165
- unit: { name: "call", precision: 0 },
166
- rate: { currency: "usd", unitAmountDecimal: "100" },
167
- } as const;
168
- ```
169
-
170
- Pay as you go bills every effective unit:
171
-
172
- ```ts
173
- const payAsYouGo = defineUsagePlan({ ...terms, model: "pay_as_you_go" });
174
- ```
175
-
176
- Included monthly usage grants ten units before overages in each original period:
177
-
178
- ```ts
179
- const included = defineUsagePlan({
180
- ...terms,
181
- model: "included_overage",
182
- includedQuantity: "10",
183
- reset: "billing_period",
184
- });
185
- ```
186
-
187
- Prepaid consumption requires verified paid grants and rejects insufficient credit:
188
-
189
- ```ts
190
- const prepaid = defineUsagePlan({
191
- ...terms,
192
- model: "prepaid",
193
- insufficientBalance: "reject",
194
- });
195
- // After server authorization and native binding setup:
196
- const purchase = await stripe.usage.purchaseCredits(
197
- ctx,
198
- {
199
- ...originalCreditBinding,
200
- purchaseId: originalBusinessPurchaseId,
201
- quantity: "10",
202
- ownership: "issuer",
203
- rollover: "retain_original_terms",
204
- },
205
- { stripeSecretKey },
206
- );
207
- // Return clientSecret only to the authorized purchaser's payment UI.
208
- // Observe the original purchase after payment; wait for its ready grant.
209
- ```
210
-
211
- Use `ensureUsageMeter`, `ensureUsagePrice` and `usage.ensureSubscription` to bind
212
- the chosen plan to the server-authorized native payer. The exact implementations
213
- are in the example's `meteredUsage/setup.ts` and `meteredUsage/funding.ts`.
214
-
215
- ## Package calls behind the example
216
-
217
- Server code imports neutral types from `@fantastic.dev/better-stripe/usage`; UI
218
- code uses `@fantastic.dev/better-stripe/react`. The example backend lives under
219
- `example/convex/meteredUsage`. Its atomic synthetic-work mutation follows this
220
- pattern, using server-authorized original terms:
221
-
222
- ```ts
223
- const reservation =
224
- model === "prepaid"
225
- ? await stripe.usage.reserveCredits(ctx, { event, subscription })
226
- : await stripe.usage.reserveAllowance(ctx, { event, subscription });
227
- // Handle denied/released reservations before doing any application work.
228
- const receipt = await stripe.usage.record(ctx, {
229
- event,
230
- subscription,
231
- reservationId: reservation.reservationId,
232
- });
233
- // Persist synthetic DB work and receipt in this same mutation transaction.
234
- ```
235
-
236
- Schedule delivery from an action after the transaction commits:
237
-
238
- ```ts
239
- await stripe.usage.startDelivery(ctx, {
240
- scope: original.scope,
241
- eventId: receipt.eventId,
242
- provider: internal.meteredUsage.delivery.deliver,
243
- });
244
- ```
245
-
246
- For external application work, use a durable idempotent work protocol with the
247
- original business identity. A database transaction cannot make an external side
248
- effect atomic. See [ledger](usage-ledger.md), [delivery](usage-delivery.md),
249
- [limits](usage-limits.md), [corrections](usage-corrections.md) and
250
- [settlement](usage-settlement.md) for the complete contracts.
78
+ For the platform, create a product such as **Store analytics reports**. Choose
79
+ Admin → Metered billing → that platform product → Prepaid credits. The example
80
+ uses report units, USD 1 per report and a manual package of ten credits.
81
+
82
+ Choose Customer and Enroll in report service first. Prepaid enrollment uses
83
+ `usage.ensureSubscription` with `send_invoice` collection and a 30-day due
84
+ window. It does not use automatic-collection Checkout. Work remains gated by
85
+ verified credit backing, and enrollment alone collects no cash. Try generating a
86
+ report before funding, then Buy report credits with test card. That explicit
87
+ button confirms Stripe's synthetic Visa on the server. The package verifies the
88
+ original captured payment and paid credit grant before credits become ready.
89
+ Ten reports exhaust a ten-credit package. Another report is denied without work
90
+ or another charge. Retry original credit purchase resumes the retained intent;
91
+ a pending purchase blocks creation of another package until reconciled.
92
+
93
+ Prepaid is supported only for the issuer's own services. Maya and Sasha do not
94
+ receive a third-party wallet or redeem credits into seller proceeds. The package
95
+ owns the balances, reservations, payment evidence and credit accounting.
96
+ For production, send the original purchase result's `clientSecret` only to the
97
+ authenticated purchaser's Stripe payment UI. Replace the synthetic test-card
98
+ confirmation with that UI, then observe the original purchase until it is ready.
99
+
100
+ The product example deliberately supports USD, whole units, whole minor-unit
101
+ rates and bounded native payment amounts. The package supports broader exact
102
+ quantity and rate contracts; see [configuration](usage-configuration.md).
103
+
104
+ ## Payment, allowance and settlement boundaries
105
+
106
+ The example rechecks the original native subscription before new work. For paid
107
+ monthly products it also verifies the original initial invoice and current
108
+ period invoice, exact product/base price/quantity, payer mapping, complete native
109
+ line and funding pages, captured PaymentIntent, and refund/dispute state.
110
+ Unknown, partial, unpaid or changed evidence blocks work. The atomic work mutation
111
+ must match the exact binding that passed the fresh check; a racing refresh cannot
112
+ move it into another unverified billing period.
113
+
114
+ Included allowance is scoped to the original subscription item and native period.
115
+ A renewal starts a new allowance only when that observed period is active on the
116
+ server. Old period usage remains unchanged. Stripe's meter summary endpoint requires
117
+ minute-aligned boundaries. For ordinary Checkout periods with partial-minute
118
+ boundaries, an exact aggregate read is explicitly unsupported. Delivered usage
119
+ is retained and the native invoice preview remains available; the example does
120
+ not round a billing period and claim an exact reconciliation. Credit grants also keep their original
121
+ price and ownership terms.
122
+
123
+ **Automatic seller settlement for mixed fixed-fee and usage invoices is not
124
+ supported by the current verifier.** Customer billing can work while seller
125
+ transfers remain held. The example does not bypass the verifier, report a paid
126
+ invoice as settled earnings, or allocate mixed cash using a browser estimate.
127
+ Existing single-source settlement protocols remain in the separate diagnostics.
128
+
129
+ ## Package APIs and UI implementations
130
+
131
+ The host adapter is in `example/convex/meteredProducts`. Its tables store product
132
+ terms, enrollment provenance, purchase identities and completed application work.
133
+ They are not another usage ledger or credit wallet.
134
+
135
+ The catalog path calls `ensureUsageMeter`, `ensureUsagePrice` and `ensurePrice`.
136
+ For coaching, the enrollment path calls `usage.ensureCheckout` with the metered price and
137
+ `fixedPriceIds: [originalMonthlyBasePriceId]`. Never infer these IDs from the
138
+ browser or purchase a base price alone through regular checkout. The example
139
+ storefront routes metered products to their enrollment workflow. Prepaid report
140
+ services use `usage.ensureSubscription` with `send_invoice`, the collection policy
141
+ required by the package credit-purchase protocol.
142
+
143
+ `product-usage-configuration.tsx` uses `useUsageConfiguration` for the headless
144
+ form and `UsageConfiguration` for the component form. Both receive identical
145
+ host callbacks. `metered-product-usage.tsx` uses `useUsageBilling` and
146
+ `useUsageHistory` for custom rendering, and `UsageBilling` and `UsageHistory`
147
+ for the component view. Switching views does not create another subscription,
148
+ usage event or credit purchase.
149
+
150
+ Demo personas are not production authentication. Each server operation checks
151
+ its test key and persona/resource binding; an authenticated identity, when
152
+ present, must match the persona. Replace this with real authentication and
153
+ server-owned authorization before adapting the example. See
154
+ [security](usage-security.md), [subscriptions](usage-subscriptions.md),
155
+ [ledger](usage-ledger.md), [delivery](usage-delivery.md) and
156
+ [credits](usage-credits.md).
157
+
158
+ ## Developer protocol diagnostics
159
+
160
+ Admin → Metered billing → Developer protocol diagnostics retains the original
161
+ isolated, three-model exercises for corrections, delivery recovery, test-clock
162
+ renewals, original cash/fee/transfer evidence and scoped cleanup. Follow the
163
+ [protocol diagnostics guide](usage-protocol-diagnostics.md). These diagnostic
164
+ runs retain their original resource IDs and historical evidence; they do not
165
+ change the product membership's customer or shared catalog resources.