@fantastic.dev/better-stripe 0.67.0 → 0.67.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 +6 -0
- package/README.md +17 -20
- package/docs/README.md +2 -1
- package/docs/metered-usage.md +174 -356
- package/docs/metering-setup.md +175 -168
- package/docs/usage-catalog.md +1 -1
- package/docs/usage-ledger.md +9 -8
- package/docs/usage-rollout.md +147 -0
- package/package.json +3 -2
package/docs/metered-usage.md
CHANGED
|
@@ -1,389 +1,207 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Native Stripe metered billing
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
This document records the native sandbox evidence, repeatable probes and remaining
|
|
9
|
-
compatibility questions. Invoice finalization and settlement remain unverified.
|
|
3
|
+
BetterStripe supports pay as you go, included monthly units with overages, and
|
|
4
|
+
paid prepaid credits through native Stripe Billing Meters, subscriptions and
|
|
5
|
+
Billing Credit Grants. The public package owns durable usage, delivery, allowance
|
|
6
|
+
and credit accounting, corrections, original-payment settlement and reusable React
|
|
7
|
+
workflows. Hosts own authentication, billable business activity and billing policy.
|
|
10
8
|
|
|
11
|
-
|
|
9
|
+
Start with [native setup](metering-setup.md), run the
|
|
10
|
+
[three example flows](usage-example.md), then use the
|
|
11
|
+
[verification matrix](usage-verification.md). For an existing application, follow
|
|
12
|
+
[opt-in adoption and rollback](usage-rollout.md). Metronome is optional; it is not a
|
|
13
|
+
credential, dependency or prerequisite for this integration. No Metronome adapter
|
|
14
|
+
is included.
|
|
12
15
|
|
|
13
|
-
|
|
14
|
-
the platform Stripe client. See `src/client/billing/subscriptions.ts` and
|
|
15
|
-
[financial ownership](financial-ownership.md). Adding a separate v1 Customer is a
|
|
16
|
-
new identity/payment-method mapping contract, not an interchangeable identifier.
|
|
17
|
-
Existing fixed-price subscriptions, checkout and settlement must keep working.
|
|
16
|
+
## Choose a model and define units
|
|
18
17
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
18
|
+
| Model | Customer behavior | Package accounting |
|
|
19
|
+
| ------------------ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
20
|
+
| `pay_as_you_go` | Pays for effective usage on the subscription invoice | Immutable usage plus optional entitlement/cap reservations |
|
|
21
|
+
| `included_overage` | Gets included units each verified monthly period, then pays for overage | Atomic included/overage reservations, hard or soft limits, separate period counters |
|
|
22
|
+
| `prepaid` | Buys units before consumption | Verified original payment and price-scoped grant, atomic reservation/consumption, exhaustion and recovery |
|
|
24
23
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
|
29
|
-
| Provider guidance | Stripe directs new usage integrations to Metronome, including existing flat-rate subscriptions adding usage | Recommended evaluation path for new usage integrations |
|
|
30
|
-
| Credentials | Existing Stripe key, subject to permissions and API access | Separate Metronome sandbox/account token and explicit Stripe integration enrollment |
|
|
31
|
-
| Payer identity | Guide maps meter payloads to Stripe Customer IDs; installed Stripe 23.0.0 meter types expose `by_id` only | Documented invoice delivery configuration uses `stripe_customer_id` with a `cus_` ID |
|
|
32
|
-
| Accounts v2 | Platform sandbox mapping to `cus_`, aggregates and invoice-preview payer identity verified; other modes remain unverified | `customer_account` invoice delivery remains unverified; ingest aliases alone do not establish payment identity |
|
|
33
|
-
| Connect | Stripe documents connected-account requests and different rate limits; this does not prove a platform-owned Accounts v2 payer works in that realm | Multi-entity connections are documented; equivalence to Connect destination charges or separate transfers remains unverified |
|
|
34
|
-
| Catalog | Meter attached to recurring metered price | Billable metric, product, rate card and customer contract |
|
|
35
|
-
| Invoices | Stripe owns subscription invoicing | Metronome rates usage and pushes separate invoices to Stripe, including when recurring subscriptions coexist |
|
|
36
|
-
| Cost/access | Confirm account eligibility and current Billing pricing before selection | Confirm enrollment, commercial terms and extra credential acceptance before selection |
|
|
37
|
-
|
|
38
|
-
Native Stripe Billing Meters is the default implementation target for BetterStripe.
|
|
39
|
-
It uses the existing Stripe integration and credentials, with native sandbox
|
|
40
|
-
aggregation and invoice-preview evidence for all three models. Metronome remains an
|
|
41
|
-
optional comparison, not a setup prerequisite. See the [developer and AI-agent setup
|
|
42
|
-
guide](metering-setup.md). Remaining account/settlement gaps must be verified before
|
|
43
|
-
claiming compatibility for those flows.
|
|
44
|
-
|
|
45
|
-
## Required billing models
|
|
46
|
-
|
|
47
|
-
BetterStripe must provide simple typed package APIs and reusable UI for:
|
|
48
|
-
|
|
49
|
-
- Pay-as-you-go.
|
|
50
|
-
- Included monthly usage with overages.
|
|
51
|
-
- Prepaid credits.
|
|
52
|
-
|
|
53
|
-
Developers configure units, precision, rates, intervals, allowances and credit
|
|
54
|
-
policies for their apps. No global first billable unit or single-model choice is
|
|
55
|
-
required. Share durable usage acceptance, delivery, scoped readers and
|
|
56
|
-
reconciliation across the three models. The example app must demonstrate a
|
|
57
|
-
complete runnable flow for each through package APIs and package React components.
|
|
58
|
-
|
|
59
|
-
Purchased prepaid credits require verified successful payment before becoming
|
|
60
|
-
spendable. Reuse existing payment/funding/recovery contracts where applicable and
|
|
61
|
-
avoid a duplicate monetary wallet. Define credit reservation, consumption,
|
|
62
|
-
expiration, refund and dispute behavior explicitly. Provider aggregates and invoice
|
|
63
|
-
previews are estimates and cannot enforce a strict real-time limit.
|
|
64
|
-
|
|
65
|
-
## Provider feasibility by model
|
|
66
|
-
|
|
67
|
-
| Model | Billing Meters candidate | Metronome candidate | Required proof |
|
|
68
|
-
| ------------------------------------ | --------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
|
69
|
-
| Pay-as-you-go | Meter, recurring usage price and subscription invoice | Metric, usage rate and contract invoice | Authorized payer, aggregate, rated invoice and original payment |
|
|
70
|
-
| Included monthly usage plus overages | Tiered usage price or explicit allowance/rating integration | Contract allowance/credit configuration plus usage rate | Reset, allowance boundary, overage and no double billing |
|
|
71
|
-
| Prepaid credits | Billing credit grants applied to eligible metered invoice lines | Payment-gated prepaid commitments | Successful purchase, grant, consumption, exhaustion and refund/dispute recovery |
|
|
72
|
-
|
|
73
|
-
The native sandbox has verified aggregation and invoice previews for all three
|
|
74
|
-
mechanisms. Finalized billing, complete credit accounting and remaining account
|
|
75
|
-
modes still require verification. All three models remain required. Stripe billing credit grants apply to eligible
|
|
76
|
-
metered subscription invoices at finalization; they do not themselves implement
|
|
77
|
-
an atomic real-time access limit. Verify the provider credit rules against the
|
|
78
|
-
existing marketplace settlement contracts before using them for seller flows.
|
|
79
|
-
|
|
80
|
-
Stripe documents that Accounts v2 subscription responses include both a mapped
|
|
81
|
-
`customer` and `customer_account`, and that `/v1/customers` supports account IDs.
|
|
82
|
-
Investigate this provider-owned mapping for meter ingestion instead of provisioning
|
|
83
|
-
a separate payer. Verify exact account ownership and provider realm before adoption.
|
|
84
|
-
|
|
85
|
-
## Shared configuration contracts
|
|
86
|
-
|
|
87
|
-
`defineUsagePlan` validates and copies a model's terms. It does not provision a
|
|
88
|
-
meter, authorize a payer, record usage, enforce limits or charge a customer.
|
|
89
|
-
The `rate.unitAmountDecimal` is a decimal string of minor currency units per whole
|
|
90
|
-
billable unit. It accepts up to 12 integer and 12 fractional digits. Currency codes
|
|
91
|
-
must contain three lowercase letters; adapters must additionally verify actual
|
|
92
|
-
currency/provider eligibility. Treat a plan key/version as immutable once used.
|
|
24
|
+
Developers choose the unit, precision, price and policy. This example uses whole
|
|
25
|
+
requests at USD 1 per request. Rates are decimal strings of **minor currency
|
|
26
|
+
units per whole billable unit**, so USD `"100"` means USD 1, not USD 100.
|
|
93
27
|
|
|
94
28
|
```ts
|
|
95
|
-
import {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
} from "@fantastic.dev/better-stripe/usage";
|
|
99
|
-
|
|
100
|
-
const terms = {
|
|
101
|
-
key: "api_requests",
|
|
29
|
+
import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
|
|
30
|
+
const common = {
|
|
31
|
+
key: "requests",
|
|
102
32
|
version: "v1",
|
|
103
33
|
unit: { name: "request", precision: 0 },
|
|
104
|
-
rate: { currency: "usd", unitAmountDecimal: "
|
|
105
|
-
};
|
|
106
|
-
const payAsYouGo = defineUsagePlan({ ...
|
|
34
|
+
rate: { currency: "usd", unitAmountDecimal: "100" },
|
|
35
|
+
} as const;
|
|
36
|
+
const payAsYouGo = defineUsagePlan({ ...common, model: "pay_as_you_go" });
|
|
107
37
|
const included = defineUsagePlan({
|
|
108
|
-
...
|
|
38
|
+
...common,
|
|
109
39
|
model: "included_overage",
|
|
110
|
-
includedQuantity: "
|
|
40
|
+
includedQuantity: "10",
|
|
111
41
|
reset: "billing_period",
|
|
112
42
|
});
|
|
113
43
|
const prepaid = defineUsagePlan({
|
|
114
|
-
...
|
|
44
|
+
...common,
|
|
115
45
|
model: "prepaid",
|
|
116
46
|
insufficientBalance: "reject",
|
|
117
47
|
});
|
|
118
|
-
const exact = parseUsageQuantity("123", payAsYouGo.unit.precision);
|
|
119
|
-
// exact.scaledQuantity is "123", a JSON/Convex-safe integer string.
|
|
120
48
|
```
|
|
121
49
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
trailing fractional zeros and preserves exact values beyond JavaScript's safe
|
|
127
|
-
integer range. Provider/catalog, delivery and reservation APIs remain unfinished.
|
|
50
|
+
Select one plan for an original binding. Do not submit one activity to all three
|
|
51
|
+
alternatives. Configuration validates terms; it does not provision resources,
|
|
52
|
+
authorize a caller or fund credits. Use a new version, event name and price lookup
|
|
53
|
+
key for changed terms. Preserve old prices and original activity bindings.
|
|
128
54
|
|
|
129
|
-
##
|
|
55
|
+
## Provision the original binding
|
|
130
56
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
`stripeCustomerId`, `stripePriceId`, native `eventName`, pinned API version and
|
|
135
|
-
full plan/version terms. The host must authorize and verify these references on
|
|
136
|
-
the server. Passing validation does not prove ownership or provider eligibility.
|
|
57
|
+
In an authenticated host action, authorize the issuer realm, product and Accounts
|
|
58
|
+
v2 payer. Resolve the payer's provider-owned mapped `cus_` identity; do not create
|
|
59
|
+
an unrelated Customer to hide a mapping error.
|
|
137
60
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
61
|
+
```ts
|
|
62
|
+
const meter = await stripe.ensureUsageMeter(ctx, {
|
|
63
|
+
scope: { stripeAccountId: issuerId, livemode: false },
|
|
64
|
+
plan: selectedPlan,
|
|
65
|
+
eventName: "requests_v1",
|
|
66
|
+
displayName: "Requests v1",
|
|
67
|
+
});
|
|
68
|
+
const price = await stripe.ensureUsagePrice(ctx, {
|
|
69
|
+
scope: { stripeAccountId: issuerId, livemode: false },
|
|
70
|
+
plan: selectedPlan,
|
|
71
|
+
meterId: meter.id,
|
|
72
|
+
stripeProductId: authorizedProductId,
|
|
73
|
+
lookupKey: "requests_v1_usd",
|
|
74
|
+
});
|
|
75
|
+
const enrollment = await stripe.usage.ensureSubscription(
|
|
76
|
+
ctx,
|
|
77
|
+
{
|
|
78
|
+
requestId: originalSignupId,
|
|
79
|
+
meters: [
|
|
80
|
+
{
|
|
81
|
+
scope: {
|
|
82
|
+
stripeAccountId: issuerId,
|
|
83
|
+
customerAccount: payerId,
|
|
84
|
+
meterId: meter.id,
|
|
85
|
+
livemode: false,
|
|
86
|
+
},
|
|
87
|
+
binding: {
|
|
88
|
+
stripeCustomerId: mappedCustomerId,
|
|
89
|
+
stripePriceId: price.stripePriceId,
|
|
90
|
+
eventName: meter.event_name,
|
|
91
|
+
plan: selectedPlan,
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
],
|
|
95
|
+
fixedPriceIds: [],
|
|
96
|
+
collection: { method: "send_invoice", daysUntilDue: 30 },
|
|
97
|
+
},
|
|
98
|
+
{ stripeSecretKey },
|
|
99
|
+
);
|
|
177
100
|
```
|
|
178
101
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
usage summaries before previewing each invoice. No invoice is explicitly finalized.
|
|
102
|
+
Persist and reuse the verified `enrollment.bindings` and original signup identity.
|
|
103
|
+
Read native status and period before admitting work. See
|
|
104
|
+
[catalog](usage-catalog.md) and [subscriptions](usage-subscriptions.md) for Checkout,
|
|
105
|
+
automatic collection, supported native shapes and bounded recovery.
|
|
184
106
|
|
|
185
|
-
|
|
186
|
-
The optional flag creates a 100-cent sandbox PaymentIntent with Stripe's test card.
|
|
187
|
-
Only a verified succeeded payment for the exact payer, currency and received amount
|
|
188
|
-
permits a paid credit grant. Cleanup expires credits, refunds the successful test
|
|
189
|
-
payment, cancels subscriptions without invoicing/proration, archives prices/products
|
|
190
|
-
and deactivates meters. Test payer records and historical provider evidence remain.
|
|
191
|
-
Cleanup success means the corresponding API request succeeded, not that an
|
|
192
|
-
asynchronous refund has settled. A failed run can leave test resources requiring
|
|
193
|
-
operator cleanup; never rerun an old operation as a new live payment.
|
|
107
|
+
## Admit work through the component
|
|
194
108
|
|
|
195
|
-
|
|
109
|
+
For pay as you go and included usage, configure the original verified period with
|
|
110
|
+
`configureAllowance`. Choose entitlement, `overage`, and a `none`, `soft` or `hard`
|
|
111
|
+
limit. `reserveAllowance` enforces that policy before work; included units and
|
|
112
|
+
billable overage derive from the immutable plan. See [limits](usage-limits.md).
|
|
196
113
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
114
|
+
For prepaid, call `purchaseCredits` with a stable business purchase ID and the
|
|
115
|
+
original credit binding. Send its `clientSecret` only to the authenticated
|
|
116
|
+
purchaser's payment UI. After payment, call `observeCreditPurchase`; only its
|
|
117
|
+
verified ready grant makes units spendable. `reserveCredits` rejects insufficient
|
|
118
|
+
or unreconciled backing. Consumption never creates another cash charge. See
|
|
119
|
+
[paid credits](usage-credits.md). Credits cover the issuer's own services, not a
|
|
120
|
+
third-party seller wallet or reseller redemption.
|
|
200
121
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
| Platform Accounts v2 payer | Meter/contract creation, ingestion, aggregate and invoice all refer to the authorized payer | Unverified |
|
|
204
|
-
| Connected seller | Prove catalog/event realm and payer ownership, destination/transfer economics and paid-invoice provenance | Unverified |
|
|
205
|
-
| Non-Connect account | Prove identity and invoice flow without silently provisioning an alternative payer | Unverified |
|
|
206
|
-
| Duplicate delivery | Same source event and provider identifier produce one aggregate contribution | Unverified |
|
|
207
|
-
| Shared meter | Two subscriptions for one customer show the actual aggregation boundary; no inferred per-subscription event targeting | Unverified |
|
|
208
|
-
| Correction | Original event, reason and receipt retained; provider cancellation window and finalized-invoice behavior demonstrated | Unverified |
|
|
209
|
-
| Invoice closeout | Original event time, delayed aggregate, finalized invoice line and payment/processing costs reconcile | Unverified |
|
|
210
|
-
| Test clocks | Determine which provider clock drives event timestamps and invoice periods, without assuming virtual time advances ingestion | Unverified |
|
|
211
|
-
| Packed consumer | Verify eventual public contracts from the built tarball with linked guides present | Configuration helpers verified; operational APIs pending |
|
|
212
|
-
|
|
213
|
-
For Billing Meters, event uniqueness is enforced for at least a rolling 24-hour
|
|
214
|
-
window. Acceptance permits timestamps within 35 calendar days in the past or five
|
|
215
|
-
minutes in the future. Cancellation is limited to events sent within 24 hours.
|
|
216
|
-
Aggregation is asynchronous. Accepted late events can appear in summaries without
|
|
217
|
-
changing a finalized invoice. Preserve local deduplication and an explicit unknown
|
|
218
|
-
delivery state beyond the safe retry window. Events have no subscription selector.
|
|
219
|
-
|
|
220
|
-
Metronome's quickstart uses a customer UUID or ingest alias and transaction ID,
|
|
221
|
-
string-valued numerical properties and a 34-day backdating window. Confirm exact
|
|
222
|
-
retention, correction and retry guarantees for the chosen API and account before
|
|
223
|
-
encoding them as constants. Its invoice integration documentation and Stripe's
|
|
224
|
-
integration overview use different metadata names for invoice mapping. Inspect the
|
|
225
|
-
actual sandbox invoice rather than trusting a single assumed metadata key.
|
|
226
|
-
|
|
227
|
-
## Evidence recorded so far
|
|
228
|
-
|
|
229
|
-
On 2026-10-18 the platform sandbox returned HTTP 200 for the meter access preflight.
|
|
230
|
-
The three-model run on `2026-09-30.endive` verified the provider-owned Accounts v2
|
|
231
|
-
mapping, catalog/subscription creation, event acceptance, an aggregate of exactly
|
|
232
|
-
15 units after identical retries, and invoice-preview payer identity for each model.
|
|
233
|
-
Preview totals were 30 cents for pay-as-you-go at 2 cents/unit, 10 cents after a
|
|
234
|
-
10-unit free tier, and zero after a 100-cent promotional grant.
|
|
235
|
-
|
|
236
|
-
All thirteen requested cleanup operations succeeded. No real customer email was
|
|
237
|
-
used. These observations are platform-scope test evidence. They do not prove
|
|
238
|
-
Connect seller flows, non-Connect preview enrollment, paid purchases, finalized
|
|
239
|
-
invoices, payment/processing costs, corrections or marketplace settlement. The
|
|
240
|
-
optional purchase probe is separate and must be recorded explicitly when run.
|
|
241
|
-
Metronome is optional and has not been provisioned. Native Stripe is the implementation target; all three models remain in scope.
|
|
242
|
-
|
|
243
|
-
The configuration/quantity tests cover all three models, invalid terms, exact
|
|
244
|
-
values beyond safe integers and caller-mutation isolation. A packed consumer test
|
|
245
|
-
loads the real `./usage` export and exercises the same three configurations.
|
|
246
|
-
|
|
247
|
-
## Primary sources
|
|
248
|
-
|
|
249
|
-
- [Stripe usage-based billing](https://docs.stripe.com/billing/usage-based)
|
|
250
|
-
- [Stripe's guidance on recording usage](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage)
|
|
251
|
-
- [Record usage with the API](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage-api)
|
|
252
|
-
- [Create a meter event](https://docs.stripe.com/api/billing/meter-event/create)
|
|
253
|
-
- [Configure meters and corrections](https://docs.stripe.com/billing/subscriptions/usage-based/meters/configure)
|
|
254
|
-
- [How Metronome works with Stripe](https://docs.stripe.com/billing/how-metronome-works-with-stripe)
|
|
255
|
-
- [Metronome API quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
|
|
256
|
-
- [Metronome invoice integration](https://docs.metronome.com/integrations/invoice-integrations/stripe)
|
|
257
|
-
|
|
258
|
-
- [Accounts v2 customer interoperability](https://docs.stripe.com/accounts-v2/use-accounts-as-customers)
|
|
259
|
-
- [Stripe billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits)
|
|
260
|
-
|
|
261
|
-
A later optional purchase run verified a succeeded 100-cent sandbox payment for
|
|
262
|
-
the exact payer/currency, created a paid grant and requested its refund. All 14
|
|
263
|
-
cleanup calls succeeded. Its prepaid aggregate was 15 and preview total was zero;
|
|
264
|
-
its included-usage aggregation did not catch up before the polling bound. This
|
|
265
|
-
later run is not a second complete three-model aggregation proof. Neither run
|
|
266
|
-
finalized a metered invoice or verified seller settlement.
|
|
267
|
-
|
|
268
|
-
## Host authorization and observation contracts
|
|
269
|
-
|
|
270
|
-
`authorizeUsageRecord` prepares a server-resolved event, invokes the host's
|
|
271
|
-
`authorize` callback for its exact scope, then `authorizeActivity` for the source
|
|
272
|
-
activity, and only then calls the supplied acceptance function. A denial throws
|
|
273
|
-
before acceptance. Resolve bindings and activity identity on the server; copying
|
|
274
|
-
browser-supplied payer, price or quantity into the helper is not authorization.
|
|
275
|
-
The component APIs are trusted host boundaries. Never export their mutations as
|
|
276
|
-
unauthenticated application endpoints.
|
|
122
|
+
The host resolves the immutable business activity and authorizes it before this
|
|
123
|
+
shared mutation pattern:
|
|
277
124
|
|
|
278
125
|
```ts
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
if (
|
|
289
|
-
throw new Error("
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
126
|
+
const receipt = await authorizeUsageRecord(
|
|
127
|
+
ctx,
|
|
128
|
+
policy,
|
|
129
|
+
serverEvent,
|
|
130
|
+
async (event) => {
|
|
131
|
+
const reservation =
|
|
132
|
+
event.binding.plan.model === "prepaid"
|
|
133
|
+
? await stripe.usage.reserveCredits(ctx, { event, subscription })
|
|
134
|
+
: await stripe.usage.reserveAllowance(ctx, { event, subscription });
|
|
135
|
+
if (reservation.state === "denied" || reservation.state === "released")
|
|
136
|
+
throw new Error("Usage is not admitted");
|
|
137
|
+
const receipt = await stripe.usage.record(ctx, {
|
|
138
|
+
event,
|
|
139
|
+
subscription,
|
|
140
|
+
reservationId: reservation.reservationId,
|
|
141
|
+
});
|
|
142
|
+
await applyDatabaseWorkOnce(ctx, originalActivityId, receipt);
|
|
143
|
+
return receipt;
|
|
294
144
|
},
|
|
295
|
-
|
|
296
|
-
declare const ctx: Context;
|
|
297
|
-
// Resolve this from authenticated activity and verified native billing bindings.
|
|
298
|
-
declare const serverRecord: unknown;
|
|
299
|
-
// Supply the component's atomic acceptance adapter when implementing the ledger.
|
|
300
|
-
declare const accept: (record: PreparedUsageRecord) => Promise<string>;
|
|
301
|
-
const eventId = await authorizeUsageRecord(ctx, policy, serverRecord, accept);
|
|
145
|
+
);
|
|
302
146
|
```
|
|
303
147
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
acceptance. `UsageCreditProvenance` ties a reservation/allocation to its original
|
|
365
|
-
grant, verified purchase PaymentIntent, currency, amount, unit quantity and plan
|
|
366
|
-
version. A grant may cover multiple events; an event may allocate several grants.
|
|
367
|
-
Never fabricate one purchase/grant from a local balance total.
|
|
368
|
-
|
|
369
|
-
`UsageCorrectionOutcome` distinguishes request, provider acceptance, confirmed
|
|
370
|
-
cancellation, held/unsupported cases and required invoice adjustment. Confirmed
|
|
371
|
-
cancellation is an adjustment observation linked to the original event, rather
|
|
372
|
-
than overwriting its original delivery or invoice receipt. A requested or
|
|
373
|
-
provider-accepted correction must not release spendable credits until confirmed.
|
|
374
|
-
|
|
375
|
-
The [packed consumer fixture](https://github.com/FantasticDevHQ/better-stripe/blob/main/scripts/fixtures/usage-consumer.ts) compiles concrete authorization and activity callbacks plus record/read/reconcile adapters for all three models against the actual package tarball. It returns alternative model paths and never submits one activity to multiple models.
|
|
376
|
-
|
|
377
|
-
## Native lifecycle verification, 2026-10-18
|
|
378
|
-
|
|
379
|
-
The [managed subscription guide](usage-subscriptions.md) now covers native
|
|
380
|
-
metered/mixed subscriptions, Checkout, closeout and retained lifecycle history.
|
|
381
|
-
The [test-clock run](evidence/native-metering/clock-finalization-run.json) verified
|
|
382
|
-
Accounts v2 payer mapping, all three 15-unit aggregates and finalized invoice
|
|
383
|
-
totals of 30/10/0 USD cents for pay-as-you-go/included-overage/prepaid. The prepaid
|
|
384
|
-
purchase was a separate verified 100-cent test payment. All 15 cleanup requests
|
|
385
|
-
succeeded, including grant expiry, the test refund request and clock deletion.
|
|
386
|
-
The [prior lag run](evidence/native-metering/clock-lag-run.json) remains visible;
|
|
387
|
-
it stopped before advancement while prepaid aggregation was pending. These
|
|
388
|
-
results supplement the earlier investigation table. They do not prove production
|
|
389
|
-
billing, non-Connect modes, strict credit accounting or seller settlement.
|
|
148
|
+
Import `authorizeUsageRecord` from the `/usage` entry point. `policy`,
|
|
149
|
+
`serverEvent`, `subscription` and `applyDatabaseWorkOnce` are authenticated host
|
|
150
|
+
adapters. The business adapter must read a completion marker keyed by the
|
|
151
|
+
original business activity and apply work once in this same Convex transaction.
|
|
152
|
+
Usage replay alone does not make arbitrary application work idempotent. Keep the
|
|
153
|
+
original reservation reference for completed work; do not re-reserve new capacity
|
|
154
|
+
under another ID after closing its account. External effects require a durable,
|
|
155
|
+
idempotent work protocol rather than a database-only transaction.
|
|
156
|
+
|
|
157
|
+
Recording atomically commits usage, reservation consumption and an outbox. It
|
|
158
|
+
performs no provider I/O. Schedule `usage.startDelivery` after commit, or provide
|
|
159
|
+
its supported transactional dispatch handle. The host's internal provider action
|
|
160
|
+
uses `usageDeliveryArgs` / `usageDeliveryResult` and delegates to `usage.deliver`
|
|
161
|
+
with execution-time credentials. See [ledger](usage-ledger.md),
|
|
162
|
+
[delivery and callbacks](usage-delivery.md), and [authorization](usage-security.md).
|
|
163
|
+
|
|
164
|
+
## Read, display and settle
|
|
165
|
+
|
|
166
|
+
Use `getSummary` for bounded local totals, `observeProviderUsage` / `reconcile` for
|
|
167
|
+
native aggregation, and `readInvoiceUsage` for original invoice lines. A delivery
|
|
168
|
+
receipt is not aggregation or payment. A preview or estimate is not a finalized
|
|
169
|
+
invoice. Missing, stale, partial or unknown evidence remains unavailable or held.
|
|
170
|
+
|
|
171
|
+
The `/react` entry point supplies `UsageConfiguration`, `UsagePriceRow`,
|
|
172
|
+
`UsageBilling`, `UsageSummary`, `UsageAllowance`, `UsageCredits` and paginated
|
|
173
|
+
`UsageHistory`. Bind them to authenticated host readers; browser view keys are
|
|
174
|
+
cache identities, not authorization. Server types also have neutral exports from
|
|
175
|
+
`/usage`. See [React views](usage-react.md) and
|
|
176
|
+
[configuration UI](usage-configuration.md).
|
|
177
|
+
|
|
178
|
+
For pay as you go and included overage, `getInvoiceSale` verifies original paid
|
|
179
|
+
proceeds before `settleInvoice`. For prepaid, use `getCreditPurchaseRevenue` and
|
|
180
|
+
`settleCreditPurchase` on the original purchase. A zero-dollar usage invoice must
|
|
181
|
+
not create another sale or affiliate commission. Actual processing fees,
|
|
182
|
+
recipient eligibility, refunds and disputes retain their original sources. See
|
|
183
|
+
[settlement](usage-settlement.md) and [corrections](usage-corrections.md).
|
|
184
|
+
|
|
185
|
+
## Precision, windows and retained limits
|
|
186
|
+
|
|
187
|
+
Quantities are canonical decimal strings with 0–6 fractional digits and at most
|
|
188
|
+
18 scaled integer digits. Never round or pass JS floating-point quantities. Native
|
|
189
|
+
catalog/credit adapters apply tighter bounds where required. Occurrence time is
|
|
190
|
+
original business time in Unix seconds, within the immutable half-open period and
|
|
191
|
+
Stripe's 35-day past / five-minute future window. Retrying does not change time.
|
|
192
|
+
|
|
193
|
+
Provider aggregation is asynchronous. Unknown sends cannot be blindly retried,
|
|
194
|
+
even inside provider deduplication windows. Native creation recovery stops blind
|
|
195
|
+
writes after 23 hours. Correction, cancellation and late invoice-adjustment
|
|
196
|
+
windows are separately documented in [corrections](usage-corrections.md).
|
|
197
|
+
|
|
198
|
+
Local retained-event quotas are bounded at 100,000 per scope; read pages contain
|
|
199
|
+
1–100 rows. Other audit, purchase and native-proof bounds have explicit held/error
|
|
200
|
+
states in their domain guides. There is no financial-history deletion/reset API.
|
|
201
|
+
Keep original IDs, prices, API/definition versions and worker handlers available
|
|
202
|
+
while operations can resume. Follow [rollout and recovery](usage-rollout.md).
|
|
203
|
+
|
|
204
|
+
The [verification matrix](usage-verification.md) records exact tested account
|
|
205
|
+
modes, actual fees and transfer proof, future-test-clock limits, injected failures
|
|
206
|
+
and unverified live-money/throughput cases. Historical feasibility probes remain
|
|
207
|
+
in the repository; they do not replace the package's ledger or paid-source proof.
|