@fantastic.dev/better-stripe 0.50.3 → 0.51.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,10 +1,12 @@
1
1
  # Metered usage feasibility
2
2
 
3
3
  Status: investigation in progress, reviewed 2026-10-18. BetterStripe does not yet
4
- expose metered billing APIs. The provider, first billable unit and pricing model
5
- must be selected before implementing provider-specific catalog, delivery or UI.
6
- This document records the compatibility questions and repeatable access preflight.
7
- It does not claim a successful billing sandbox run.
4
+ expose operational metered billing APIs. Configuration and quantity helpers are
5
+ available at `@fantastic.dev/better-stripe/usage`. All three models are required. Provider
6
+ feasibility must establish a compatible architecture before provider-specific
7
+ catalog, delivery or UI implementation.
8
+ This document records the native sandbox evidence, repeatable probes and remaining
9
+ compatibility questions. Invoice finalization and settlement remain unverified.
8
10
 
9
11
  ## Existing integration constraints
10
12
 
@@ -27,29 +29,125 @@ proceeds and original payment provenance.
27
29
  | Provider guidance | Stripe directs new usage integrations to Metronome, including existing flat-rate subscriptions adding usage | Recommended evaluation path for new usage integrations |
28
30
  | Credentials | Existing Stripe key, subject to permissions and API access | Separate Metronome sandbox/account token and explicit Stripe integration enrollment |
29
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 |
30
- | Accounts v2 | `acct_` payer ingestion and invoice identity remain unverified | `customer_account` invoice delivery remains unverified; ingest aliases alone do not establish payment identity |
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 |
31
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 |
32
34
  | Catalog | Meter attached to recurring metered price | Billable metric, product, rate card and customer contract |
33
35
  | Invoices | Stripe owns subscription invoicing | Metronome rates usage and pushes separate invoices to Stripe, including when recurring subscriptions coexist |
34
36
  | Cost/access | Confirm account eligibility and current Billing pricing before selection | Confirm enrollment, commercial terms and extra credential acceptance before selection |
35
37
 
36
- No provider is selected. Evaluate Metronome first because it is Stripe's current
37
- recommendation. Adopt it only after proving the Accounts v2 and settlement
38
- contracts and explicitly accepting the additional service credentials. Keep Billing
39
- Meters as a comparison candidate, not an automatic fallback if access fails.
40
- Neither candidate currently has proven end-to-end support in this repository.
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.
41
44
 
42
- ## Pricing-model decision
45
+ ## Required billing models
43
46
 
44
- The product owner must choose pay-as-you-go, included monthly units with overages,
45
- or prepaid credits, and name the first billable unit. Pay-as-you-go is the proposed
46
- smallest starting scope. This proposal is not approval. Other models remain
47
- unselected. In particular, do not create a second wallet or infer prepaid access
48
- rules from the existing balance-funding integration.
47
+ BetterStripe must provide simple typed package APIs and reusable UI for:
49
48
 
50
- Record the unit, decimal precision, aggregation formula, billing interval, currency,
51
- price/version and payer/seller scope with the decision. Host limits and entitlement
52
- rules are separate from an eventually consistent provider usage total.
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.
93
+
94
+ ```ts
95
+ import {
96
+ defineUsagePlan,
97
+ parseUsageQuantity,
98
+ } from "@fantastic.dev/better-stripe/usage";
99
+
100
+ const terms = {
101
+ key: "api_requests",
102
+ version: "v1",
103
+ unit: { name: "request", precision: 0 },
104
+ rate: { currency: "usd", unitAmountDecimal: "2" },
105
+ };
106
+ const payAsYouGo = defineUsagePlan({ ...terms, model: "pay_as_you_go" });
107
+ const included = defineUsagePlan({
108
+ ...terms,
109
+ model: "included_overage",
110
+ includedQuantity: "1000",
111
+ reset: "billing_period",
112
+ });
113
+ const prepaid = defineUsagePlan({
114
+ ...terms,
115
+ model: "prepaid",
116
+ insufficientBalance: "reject",
117
+ });
118
+ const exact = parseUsageQuantity("123", payAsYouGo.unit.precision);
119
+ // exact.scaledQuantity is "123", a JSON/Convex-safe integer string.
120
+ ```
121
+
122
+ The initial shared quantity contract supports 0–6 decimal places, nonnegative
123
+ canonical decimal strings, and at most 18 digits in the scaled integer. It rejects
124
+ rounding, exponent notation and JavaScript numeric inputs. A provider adapter must
125
+ apply its own tighter bounds before accepting usage. `parseUsageQuantity` removes
126
+ trailing fractional zeros and preserves exact values beyond JavaScript's safe
127
+ integer range. Provider/catalog, delivery and reservation APIs remain unfinished.
128
+
129
+ ## Native event scope and identity
130
+
131
+ `prepareUsageRecord` validates and snapshots a native event before persistence.
132
+ Its scope contains `stripeAccountId` for the Stripe realm, `customerAccount` for
133
+ the Accounts v2 payer, `meterId`, and `livemode`. The binding preserves the mapped
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.
137
+
138
+ Use one stable `sourceEventId` per real activity. The deduplication identity covers
139
+ test/live mode, realm, payer, meter and that source ID. Plan changes, mapped-customer
140
+ changes and quantity/time corrections do not create a new identity; acceptance must
141
+ compare the original immutable event and reject conflicting replay. Occurrence
142
+ time is Unix seconds. Adapters must enforce Stripe's supported event windows and
143
+ retain original time, rather than replacing it with the retry time.
144
+
145
+ `UsageDeliveryState` distinguishes queued, sending, provider-accepted, rejected,
146
+ unknown and held delivery. Locally recorded acceptance is the ledger transaction;
147
+ provider acceptance is only a receipt. Aggregation and invoicing require independent
148
+ reconciliation evidence. An adjustment retains the original event and receipts.
149
+ A finalized/paid invoice is not inferred from a delivery state or preview. These
150
+ contracts prepare the shared ledger/delivery work; they do not implement it.
53
151
 
54
152
  ## Access preflight
55
153
 
@@ -70,23 +168,47 @@ failure, not evidence that a billing identity or model is unsupported. The scrip
70
168
  has no connected-account selector and does not test that realm. It is a development
71
169
  tool in the repository, not a public package API.
72
170
 
171
+ ## Three-model sandbox runner
172
+
173
+ ```sh
174
+ node scripts/metering-sandbox.mjs
175
+ # Explicit optional test-card purchase proof, refunded during cleanup:
176
+ node scripts/metering-sandbox.mjs --verify-test-payment
177
+ ```
178
+
179
+ Inject a test key into the process environment. Both paths reject live keys before
180
+ networking. Each run creates an isolated Accounts v2 payer and three independent
181
+ meter/product/price/subscription sets. It verifies the provider-owned customer
182
+ mapping, sends 15 units twice with one event/idempotency identity and polls bounded
183
+ usage summaries before previewing each invoice. No invoice is explicitly finalized.
184
+
185
+ The default credit grant is promotional, so it does not prove a paid purchase.
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.
194
+
73
195
  ## Sandbox acceptance matrix
74
196
 
75
- Run the following after credentials and product decisions are available. Capture
197
+ Run the following with sandbox credentials and the confirmed three-model scope. Capture
76
198
  sanitized request shapes, API versions, timestamps, status codes and assertions.
77
199
  Keep secrets and raw customer/provider payloads out of evidence and workflow state.
78
200
 
79
- | Scenario | Required proof | Current result |
80
- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
81
- | Platform Accounts v2 payer | Meter/contract creation, ingestion, aggregate and invoice all refer to the authorized payer | Unverified |
82
- | Connected seller | Prove catalog/event realm and payer ownership, destination/transfer economics and paid-invoice provenance | Unverified |
83
- | Non-Connect account | Prove identity and invoice flow without silently provisioning an alternative payer | Unverified |
84
- | Duplicate delivery | Same source event and provider identifier produce one aggregate contribution | Unverified |
85
- | Shared meter | Two subscriptions for one customer show the actual aggregation boundary; no inferred per-subscription event targeting | Unverified |
86
- | Correction | Original event, reason and receipt retained; provider cancellation window and finalized-invoice behavior demonstrated | Unverified |
87
- | Invoice closeout | Original event time, delayed aggregate, finalized invoice line and payment/processing costs reconcile | Unverified |
88
- | Test clocks | Determine which provider clock drives event timestamps and invoice periods, without assuming virtual time advances ingestion | Unverified |
89
- | Packed consumer | Verify eventual public contracts from the built tarball with linked guides present | Deferred until public APIs exist |
201
+ | Scenario | Required proof | Current result |
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 |
90
212
 
91
213
  For Billing Meters, event uniqueness is enforced for at least a rolling 24-hour
92
214
  window. Acceptance permits timestamps within 35 calendar days in the past or five
@@ -104,12 +226,23 @@ actual sandbox invoice rather than trusting a single assumed metadata key.
104
226
 
105
227
  ## Evidence recorded so far
106
228
 
107
- The repository uses Stripe 23.0.0 and pins `2026-09-30.endive`. Its installed meter
108
- creation types permit `customer_mapping.type: 'by_id'`; this is a type inspection,
109
- not proof that Accounts v2 ingestion is supported or unsupported. The access probe
110
- has automated tests covering rejection of live/missing keys, a single read-only
111
- request and sanitization of provider errors. Actual provider access, usage delivery,
112
- aggregation, invoices, payment provenance and Metronome access remain unverified.
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.
113
246
 
114
247
  ## Primary sources
115
248
 
@@ -121,3 +254,122 @@ aggregation, invoices, payment provenance and Metronome access remain unverified
121
254
  - [How Metronome works with Stripe](https://docs.stripe.com/billing/how-metronome-works-with-stripe)
122
255
  - [Metronome API quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
123
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.
277
+
278
+ ```ts
279
+ import {
280
+ authorizeUsageRecord,
281
+ type UsageAuthorization,
282
+ type PreparedUsageRecord,
283
+ } from "@fantastic.dev/better-stripe/usage";
284
+
285
+ type Context = { userId: string; customerAccount: string; activityId: string };
286
+ const policy: UsageAuthorization<Context> = {
287
+ async authorize(ctx, { scope }) {
288
+ if (!ctx.userId || ctx.customerAccount !== scope.customerAccount)
289
+ throw new Error("Unauthorized usage scope");
290
+ },
291
+ async authorizeActivity(ctx, record) {
292
+ if (record.sourceEventId !== ctx.activityId || record.quantity !== "1")
293
+ throw new Error("Activity is not billable under these terms");
294
+ },
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);
302
+ ```
303
+
304
+ The same adapter handles each of the three configurations above. Hosts own actor,
305
+ tenant, entitlement and billable-activity policy. The component owns deduplication,
306
+ financial history, delivery and credit accounting. Credentials remain in host
307
+ internal actions. They must never enter records, workflow arguments or receipts.
308
+
309
+ `UsagePageRequest` uses a half-open `[start, end)` period in Unix seconds, an opaque
310
+ cursor and a limit of 1–100. `validateUsagePageRequest` rejects invalid intervals,
311
+ unsafe timestamps and oversized cursors. Every page must reauthorize the original
312
+ scope and period. Readers must distinguish an incomplete scan from a complete
313
+ zero total; never sum different currencies or pricing versions implicitly.
314
+
315
+ `UsageObservations` keeps local acceptance, provider acceptance, aggregation,
316
+ estimates and invoice observations separate. `UsageAvailability` explicitly
317
+ represents unsupported and unavailable provider/account modes, reason and retry
318
+ policy. Missing observations are not zero. `observedAt` is Unix seconds;
319
+ acceptance timestamps are assigned by the component, independently of original
320
+ occurrence time. Native v1 delivery uses sum aggregation and integer scaled units;
321
+ price conversion must preserve the configured whole-unit rate exactly or reject
322
+ unsupported precision. A provider acceptance receipt is not aggregation or payment.
323
+
324
+ ## Corrections, retention and transitions
325
+
326
+ `UsageCorrectionRequest` identifies the original scope/source event, an immutable
327
+ correction ID and reason. Cancellation retains the original quantity, timestamp,
328
+ provider event identifier and every receipt. A replacement uses a new source event
329
+ only after cancellation is confirmed; finalized invoice changes require explicit
330
+ billing adjustments rather than silently rewriting usage. Native cancellation
331
+ windows and uncertain responses can produce unsupported or held results. No
332
+ financial outcome follows merely from requesting a correction.
333
+
334
+ `UsageRetentionPolicy` retains financial evidence. Retention of temporary execution
335
+ payloads may be configured separately, but cleanup must preserve event identities,
336
+ pricing snapshots, unresolved receipts, payments, reservations and correction
337
+ links. There is no automatic financial-history deletion contract. Bounded pages
338
+ and per-scope quotas apply before acceptance; an exhausted quota rejects new work
339
+ without deleting old evidence. Large-volume exports retain original identities
340
+ and must be reconciled before any future explicit archival feature.
341
+
342
+ `UsageTransitionRequest` drains pending usage and resolves reservations before an
343
+ explicit effective boundary. Versions are immutable. A model/rate/unit/currency
344
+ change creates a new version and native price; existing credit grants retain their
345
+ original terms. No implicit currency conversion, credit conversion, subscription
346
+ migration or historical re-rating is permitted. `assertUsageReplay` compares
347
+ normalized immutable terms and rejects changed replay on the original identity,
348
+ including time, currency, mapped customer and version. A transition must never
349
+ turn a prepaid consumption into a new pay-as-you-go charge.
350
+
351
+ These are shared contracts and host-boundary helpers. Runtime catalog, acceptance,
352
+ delivery, correction and transition adapters are implemented in subsequent tickets.
353
+
354
+ `UsageContractPort` defines shared `record`, paginated `read`, `reconcile` and
355
+ `capabilities` requests/results for host adapters. `record` is an atomic local
356
+ acceptance receipt; `read` returns bounded history, not provider completeness;
357
+ `reconcile` returns independent observations and never resends events to repair a
358
+ mismatch. Check capabilities and availability for the selected scope. These
359
+ interfaces specify the adapters being implemented, not an available engine.
360
+
361
+ `UsageSubscriptionBinding` ties the verified native subscription/item and monthly
362
+ period to its price. Store it as immutable routing provenance when accepting
363
+ usage. Invoice IDs are later observations because the invoice may not exist at
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.
@@ -0,0 +1,183 @@
1
+ # Set up native Stripe metering
2
+
3
+ BetterStripe's default metering path uses your existing Stripe sandbox. You do not
4
+ need a Metronome account or token. Stripe recommends Metronome for new usage-based
5
+ integrations, but Billing Meters APIs remain available. This project is building
6
+ native Stripe integration into the existing BetterStripe Convex component.
7
+
8
+ Current status: shared configuration/quantity helpers and repository sandbox probes
9
+ are implemented. Operational recording, durable delivery, allowance/credit
10
+ accounting and the three example UI flows are still under development. The probes
11
+ below verify provider behavior directly; they are not public BetterStripe billing
12
+ workflows. See [metered usage contracts and evidence](metered-usage.md).
13
+
14
+ ## Prerequisites
15
+
16
+ Use Node 20 or later and the repository's pinned pnpm version. Start with an
17
+ existing Stripe sandbox and a secret key for that sandbox, plus a Convex development
18
+ deployment for the example. Keep the sandbox separate from production resources.
19
+ Use the existing [Accounts v2 setup](accounts-v2-preview.md) for your account mode;
20
+ Connect GA and customer-only public preview have different enrollment/version
21
+ requirements. The probes pin `2026-09-30.endive`, as the package does by default.
22
+ They do not prove a non-Connect preview configuration.
23
+
24
+ From the repository root:
25
+
26
+ ```sh
27
+ pnpm install --frozen-lockfile
28
+ pnpm run build
29
+ ```
30
+
31
+ If the example is not linked to a development deployment, follow the repository's
32
+ example setup first. Run Convex deployment commands from `example/`, and check its
33
+ `.env.local` deployment selection before setting credentials. Do not use `--prod`
34
+ for these steps. A Stripe sandbox key and a Convex deployment credential are
35
+ different credentials; one cannot replace the other.
36
+
37
+ ## Supply the existing Stripe sandbox key
38
+
39
+ The required variable is `STRIPE_SECRET_KEY`. Use a server-only value, never a
40
+ `VITE_`/browser variable. A `sk_test_` key is accepted by the probes; live keys are
41
+ rejected before requests. An access failure with a restricted key does not prove
42
+ that a billing model is unsupported.
43
+
44
+ To configure the example deployment, use the Convex dashboard's environment-variable
45
+ editor or pipe a secret from your secret manager into the CLI. For example, from
46
+ `example/`, replacing the reference with your own 1Password item:
47
+
48
+ ```sh
49
+ op read 'op://YourVault/YourStripeSandbox/secret-key' |
50
+ pnpm exec convex env set STRIPE_SECRET_KEY
51
+ ```
52
+
53
+ The value travels through stdin instead of shell history or a command argument.
54
+ Do not run `convex env get` or `op read` by itself in a recorded session. If the
55
+ variable is already configured correctly, leave it in place.
56
+
57
+ For repository-local probes, create an ignored `.env.metering` file containing a
58
+ secret reference, not a copied secret value:
59
+
60
+ ```dotenv
61
+ STRIPE_SECRET_KEY=op://YourVault/YourStripeSandbox/secret-key
62
+ ```
63
+
64
+ Use one authorized interactive terminal for subsequent `op` commands. On macOS,
65
+ 1Password CLI authorization is per terminal/account and expires after ten minutes
66
+ of inactivity or when the app locks. Do not use keepalives or plaintext caches.
67
+ Developers using another secret manager can inject the same process environment
68
+ without 1Password.
69
+
70
+ ## Run the read-only access check
71
+
72
+ From the repository root:
73
+
74
+ ```sh
75
+ op run --env-file=.env.metering -- node scripts/metering-feasibility.mjs
76
+ ```
77
+
78
+ Expected result: `status: 200` and `accessible: true`. Other verification flags
79
+ remain `unverified`, because this command only reads the meter endpoint. It does
80
+ not create customers, catalogs, events, invoices or charges. On 401/403, check the
81
+ sandbox, key permissions and deployment selection before changing code.
82
+
83
+ ## Run all three native-provider scenarios
84
+
85
+ ```sh
86
+ op run --env-file=.env.metering -- node scripts/metering-sandbox.mjs
87
+ ```
88
+
89
+ This creates synthetic test resources. The same provider-owned Accounts v2 payer
90
+ mapping is used for subscriptions and meter events; it does not create an
91
+ independent v1 payer to work around identity mismatches. Each model has its own
92
+ meter and subscription. The default prepaid fixture is promotional credit, which
93
+ is not proof of a paid purchase.
94
+
95
+ | Scenario | Fixture | Expected aggregate | Expected preview total |
96
+ | ---------------------------- | ------------------------------------------------- | ------------------ | ---------------------- |
97
+ | Pay-as-you-go | 15 units at 2 US cents/unit | 15 | 30 cents |
98
+ | Included usage plus overages | First 10 units free, then 2 cents/unit | 15 | 10 cents |
99
+ | Prepaid | 100-cent credit applied to the same 15-unit usage | 15 | 0 cents |
100
+
101
+ The runner retries the identical event with the same idempotency identity. Bounded
102
+ polling allows aggregation to catch up. An accepted event alone is insufficient;
103
+ look for `aggregationVerified` and `invoiceIdentityVerified` for every model and
104
+ compare preview totals with the table. A zero aggregate or preview while delivery
105
+ is delayed is not a successful free-usage result. Do not rerun with new source IDs
106
+ to repair delayed aggregation, because that can double bill.
107
+
108
+ The optional purchase check is explicit:
109
+
110
+ ```sh
111
+ op run --env-file=.env.metering -- node scripts/metering-sandbox.mjs --verify-test-payment
112
+ ```
113
+
114
+ It creates a sandbox PaymentIntent with Stripe's test card, verifies succeeded
115
+ status, payer, currency and received amount, then grants paid credits. Pending or
116
+ mismatched payments must not grant credits. It requests a refund during cleanup.
117
+ No live payments are authorized by this guide. This is a provider feasibility
118
+ probe, not the component's future production credit purchase API.
119
+
120
+ On this API version PaymentIntent filtering uses `allowed_payment_method_types`.
121
+ The older `payment_method_types` parameter is rejected. The runner uses the current
122
+ parameter. See the source for the exact pinned request contract.
123
+
124
+ ## Cleanup and evidence
125
+
126
+ The runner expires its grant, requests a refund for a verified test purchase,
127
+ cancels its subscriptions without invoicing/proration, archives its prices and
128
+ products, and deactivates its meters. Payer records and provider history remain.
129
+ Check every cleanup result. API acceptance does not mean an asynchronous refund
130
+ has settled. A failed run can require manual cleanup; do not delete unresolved
131
+ financial evidence or touch another application's resources.
132
+
133
+ Save sanitized result JSON and current test/CI links in PR evidence. Exclude API
134
+ keys, client secrets, personal emails and raw provider payloads. Record which model,
135
+ account mode, API version and stage actually ran. These tests do not by themselves
136
+ prove finalized invoices, seller settlement, affiliate economics, corrections,
137
+ shared-meter subscription boundaries or strict real-time prepaid access limits.
138
+
139
+ Run repository verification before handing off changes:
140
+
141
+ ```sh
142
+ pnpm exec vitest run scripts/metering-feasibility.test.mjs scripts/metering-sandbox.test.mjs
143
+ pnpm exec vitest run src/client/usage/contracts.test.ts scripts/usage-contracts-packed.test.mjs
144
+ pnpm run check:all
145
+ ```
146
+
147
+ ## Instructions for AI agents
148
+
149
+ Read this guide, the linked usage contracts and repository `AGENTS.md` first.
150
+ Confirm the selected development deployment and the secret source without printing
151
+ values. Use the existing sandbox and credentials. Do not create a Metronome account
152
+ as a prerequisite or provision an alternative customer identity to hide a mismatch.
153
+
154
+ Keep source-event IDs stable and distinguish transport acceptance, aggregation,
155
+ invoice previews and paid invoices. Configuration validation does not authorize a
156
+ payer or enable billing. Hosts authorize tenants and billable activity. Component
157
+ mutations and durable workers must own accounting and delivery once implemented.
158
+
159
+ When a check fails, record its stage and sanitized classification. Fix request or
160
+ fixture errors before retrying, keep financial operation identities stable, and
161
+ report unverified behavior explicitly. Check the source and current primary docs
162
+ when provider parameter names change. Do not weaken repository gates or replace
163
+ provider proof with mocked output.
164
+
165
+ ## Optional Metronome evaluation
166
+
167
+ Metronome is a separate service with its own signup, token and Stripe connection.
168
+ Its signup asks for work email, name, company, country and employee range. Those
169
+ are Metronome onboarding fields, not native Stripe metering requirements.
170
+
171
+ If a host independently chooses Metronome, use its sandbox token and connect the
172
+ intended Stripe test environment. Verify identity and invoice provenance against
173
+ BetterStripe before claiming support. This repository currently has no Metronome
174
+ adapter or verified Metronome sandbox setup. Native Stripe users can ignore this
175
+ optional path.
176
+
177
+ Primary references:
178
+
179
+ - [Stripe usage recording](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage)
180
+ - [Accounts v2 customer interoperability](https://docs.stripe.com/accounts-v2/use-accounts-as-customers)
181
+ - [Stripe meter event API](https://docs.stripe.com/api/billing/meter-event/create)
182
+ - [Stripe billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits)
183
+ - [Metronome quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.50.3",
3
+ "version": "0.51.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -46,6 +46,10 @@
46
46
  "./_generated/component.js": {
47
47
  "types": "./dist/component/_generated/component.d.ts",
48
48
  "default": "./dist/component/_generated/component.js"
49
+ },
50
+ "./usage": {
51
+ "types": "./dist/client/usage/index.d.ts",
52
+ "default": "./dist/client/usage/index.js"
49
53
  }
50
54
  },
51
55
  "main": "./dist/client/index.js",
@@ -86,6 +90,7 @@
86
90
  "docs/release-handoff.md",
87
91
  "docs/setup-intent-recovery.md",
88
92
  "docs/metered-usage.md",
93
+ "docs/metering-setup.md",
89
94
  "docs/README.md",
90
95
  "docs/overview.md",
91
96
  "docs/client-api.md",
@@ -1,17 +1,13 @@
1
1
  // @vitest-environment edge-runtime
2
2
  import { expect, it, vi } from "vitest";
3
- import schema from "../component/schema.js";
3
+ import { schema, modules } from "../test.js";
4
4
  import { BetterStripe } from "./index.js";
5
5
  import type { RunCtx } from "./helpers.js";
6
6
  import { components, initConvexTest } from "./setup.test.js";
7
7
  import { componentRef } from "./webhooks/helpers.js";
8
8
  it("drains every original reference through the actual public SDK and component", async () => {
9
9
  const t = initConvexTest();
10
- t.registerComponent(
11
- "betterStripe",
12
- schema,
13
- import.meta.glob("../component/**/*.ts"),
14
- );
10
+ t.registerComponent("betterStripe", schema, modules);
15
11
  const client = new BetterStripe(components.betterStripe);
16
12
  const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
17
13
  for (let i = 0; i < 101; i++)