@fantastic.dev/better-stripe 0.55.0 → 0.56.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.
- package/CHANGELOG.md +6 -0
- package/README.md +3 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +216 -38
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +92 -3
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +216 -38
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +92 -3
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/usage/catalogPrices.d.ts +2 -0
- package/dist/client/usage/catalogPrices.d.ts.map +1 -1
- package/dist/client/usage/catalogPrices.js +15 -0
- package/dist/client/usage/catalogPrices.js.map +1 -1
- package/dist/client/usage/client.d.ts +2 -2
- package/dist/client/usage/client.d.ts.map +1 -1
- package/dist/client/usage/client.js +2 -2
- package/dist/client/usage/client.js.map +1 -1
- package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
- package/dist/client/usage/deliveryProvider.js +26 -1
- package/dist/client/usage/deliveryProvider.js.map +1 -1
- package/dist/client/usage/index.d.ts +4 -0
- package/dist/client/usage/index.d.ts.map +1 -1
- package/dist/client/usage/index.js +1 -0
- package/dist/client/usage/index.js.map +1 -1
- package/dist/client/usage/subscription.fixtures.d.ts +118 -0
- package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
- package/dist/client/usage/subscription.fixtures.js +84 -0
- package/dist/client/usage/subscription.fixtures.js.map +1 -0
- package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
- package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
- package/dist/client/usage/subscriptionAbandonment.js +82 -0
- package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
- package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
- package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
- package/dist/client/usage/subscriptionCancellation.js +39 -0
- package/dist/client/usage/subscriptionCancellation.js.map +1 -0
- package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
- package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
- package/dist/client/usage/subscriptionCheckout.js +94 -0
- package/dist/client/usage/subscriptionCheckout.js.map +1 -0
- package/dist/client/usage/subscriptionClient.d.ts +267 -0
- package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
- package/dist/client/usage/subscriptionClient.js +93 -0
- package/dist/client/usage/subscriptionClient.js.map +1 -0
- package/dist/client/usage/subscriptionErrors.d.ts +5 -0
- package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
- package/dist/client/usage/subscriptionErrors.js +9 -0
- package/dist/client/usage/subscriptionErrors.js.map +1 -0
- package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
- package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
- package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
- package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
- package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
- package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
- package/dist/client/usage/subscriptionLifecycle.js +87 -0
- package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
- package/dist/client/usage/subscriptionProvider.d.ts +111 -0
- package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
- package/dist/client/usage/subscriptionProvider.js +147 -0
- package/dist/client/usage/subscriptionProvider.js.map +1 -0
- package/dist/client/usage/subscriptionTerms.d.ts +161 -0
- package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
- package/dist/client/usage/subscriptionTerms.js +242 -0
- package/dist/client/usage/subscriptionTerms.js.map +1 -0
- package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
- package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
- package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
- package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +2 -0
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
- package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
- package/dist/client/webhooks/usageSubscriptions.js +54 -0
- package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
- package/dist/component/_generated/api.d.ts +14 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +160 -5
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/accountClosure/mutations.d.ts.map +1 -1
- package/dist/component/accountClosure/mutations.js +10 -0
- package/dist/component/accountClosure/mutations.js.map +1 -1
- package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
- package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
- package/dist/component/earnings/triggers.d.ts +192 -4
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/schema.d.ts +92 -3
- package/dist/component/schema.js +5 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/mutations.d.ts.map +1 -1
- package/dist/component/usage/mutations.js +5 -0
- package/dist/component/usage/mutations.js.map +1 -1
- package/dist/component/usage/queries.d.ts +2 -0
- package/dist/component/usage/queries.d.ts.map +1 -1
- package/dist/component/usage/schema.d.ts +14 -7
- package/dist/component/usage/schema.d.ts.map +1 -1
- package/dist/component/usage/schema.js +5 -1
- package/dist/component/usage/schema.js.map +1 -1
- package/dist/component/usageDelivery/fields.d.ts +3 -2
- package/dist/component/usageDelivery/fields.d.ts.map +1 -1
- package/dist/component/usageDelivery/fields.js +2 -1
- package/dist/component/usageDelivery/fields.js.map +1 -1
- package/dist/component/usageDelivery/helpers.d.ts +4 -3
- package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
- package/dist/component/usageDelivery/mutations.d.ts +3 -3
- package/dist/component/usageDelivery/queries.d.ts +17 -3
- package/dist/component/usageDelivery/queries.d.ts.map +1 -1
- package/dist/component/usageDelivery/queries.js +20 -3
- package/dist/component/usageDelivery/queries.js.map +1 -1
- package/dist/component/usageDelivery/schema.d.ts +2 -2
- package/dist/component/usageDelivery/steps.d.ts +1 -1
- package/dist/component/usageDelivery/steps.d.ts.map +1 -1
- package/dist/component/usageDelivery/steps.js +12 -1
- package/dist/component/usageDelivery/steps.js.map +1 -1
- package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
- package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/abandonment.js +59 -0
- package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
- package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
- package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/acceptance.js +38 -0
- package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
- package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
- package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/helpers.js +28 -0
- package/dist/component/usageSubscriptions/helpers.js.map +1 -0
- package/dist/component/usageSubscriptions/history.d.ts +46 -0
- package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/history.js +46 -0
- package/dist/component/usageSubscriptions/history.js.map +1 -0
- package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
- package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/mutations.js +252 -0
- package/dist/component/usageSubscriptions/mutations.js.map +1 -0
- package/dist/component/usageSubscriptions/queries.d.ts +81 -0
- package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/queries.js +70 -0
- package/dist/component/usageSubscriptions/queries.js.map +1 -0
- package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
- package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/retirement.js +80 -0
- package/dist/component/usageSubscriptions/retirement.js.map +1 -0
- package/dist/component/usageSubscriptions/schema.d.ts +191 -0
- package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
- package/dist/component/usageSubscriptions/schema.js +69 -0
- package/dist/component/usageSubscriptions/schema.js.map +1 -0
- package/dist/test.d.ts +6 -0
- package/dist/test.d.ts.map +1 -0
- package/dist/test.js +15 -0
- package/dist/test.js.map +1 -0
- package/docs/README.md +2 -0
- package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
- package/docs/evidence/native-metering/clock-lag-run.json +111 -0
- package/docs/evidence/native-metering/paid-run.json +107 -0
- package/docs/evidence/native-metering/promotional-run.json +103 -0
- package/docs/metered-usage.md +14 -0
- package/docs/metering-setup.md +5 -1
- package/docs/usage-subscriptions.md +278 -0
- package/package.json +4 -2
- package/src/client/index.ts +8 -0
- package/src/client/usage/catalogPrices.ts +21 -0
- package/src/client/usage/client.ts +2 -2
- package/src/client/usage/deliveryProvider.test.ts +70 -1
- package/src/client/usage/deliveryProvider.ts +43 -2
- package/src/client/usage/index.ts +9 -0
- package/src/client/usage/subscription.fixtures.ts +84 -0
- package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
- package/src/client/usage/subscriptionAbandonment.ts +116 -0
- package/src/client/usage/subscriptionCancellation.ts +90 -0
- package/src/client/usage/subscriptionCheckout.test.ts +31 -0
- package/src/client/usage/subscriptionCheckout.ts +152 -0
- package/src/client/usage/subscriptionClient.test.ts +316 -0
- package/src/client/usage/subscriptionClient.ts +204 -0
- package/src/client/usage/subscriptionErrors.ts +14 -0
- package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
- package/src/client/usage/subscriptionLifecycle.ts +165 -0
- package/src/client/usage/subscriptionProvider.test.ts +48 -0
- package/src/client/usage/subscriptionProvider.ts +247 -0
- package/src/client/usage/subscriptionTerms.test.ts +158 -0
- package/src/client/usage/subscriptionTerms.ts +294 -0
- package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
- package/src/client/webhooks/processors.ts +2 -0
- package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
- package/src/client/webhooks/usageSubscriptions.ts +81 -0
- package/src/component/_generated/api.ts +14 -0
- package/src/component/_generated/component.ts +200 -0
- package/src/component/accountClosure/mutations.ts +12 -0
- package/src/component/schema.ts +10 -0
- package/src/component/usage/mutations.ts +5 -0
- package/src/component/usage/schema.ts +5 -1
- package/src/component/usageDelivery/fields.ts +2 -0
- package/src/component/usageDelivery/queries.ts +30 -3
- package/src/component/usageDelivery/steps.ts +22 -1
- package/src/component/usageSubscriptions/abandonment.ts +80 -0
- package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
- package/src/component/usageSubscriptions/acceptance.ts +66 -0
- package/src/component/usageSubscriptions/helpers.ts +33 -0
- package/src/component/usageSubscriptions/history.test.ts +69 -0
- package/src/component/usageSubscriptions/history.ts +68 -0
- package/src/component/usageSubscriptions/mutations.test.ts +205 -0
- package/src/component/usageSubscriptions/mutations.ts +275 -0
- package/src/component/usageSubscriptions/queries.ts +78 -0
- package/src/component/usageSubscriptions/retirement.ts +105 -0
- package/src/component/usageSubscriptions/schema.ts +73 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiVersion": "2026-09-30.endive",
|
|
3
|
+
"observedAt": "2026-10-18T03:20:46.727Z",
|
|
4
|
+
"models": [
|
|
5
|
+
{
|
|
6
|
+
"model": "pay_as_you_go",
|
|
7
|
+
"catalogCreated": true,
|
|
8
|
+
"eventAccepted": true,
|
|
9
|
+
"aggregatedQuantity": 15,
|
|
10
|
+
"aggregationVerified": true,
|
|
11
|
+
"duplicateRetryVerified": true,
|
|
12
|
+
"invoiceIdentityVerified": true,
|
|
13
|
+
"previewTotal": 30,
|
|
14
|
+
"currency": "usd",
|
|
15
|
+
"paymentVerified": false,
|
|
16
|
+
"creditPurchaseVerified": false,
|
|
17
|
+
"invoiceFinalizationVerified": false
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"model": "included_overage",
|
|
21
|
+
"catalogCreated": true,
|
|
22
|
+
"eventAccepted": true,
|
|
23
|
+
"aggregatedQuantity": 15,
|
|
24
|
+
"aggregationVerified": true,
|
|
25
|
+
"duplicateRetryVerified": true,
|
|
26
|
+
"invoiceIdentityVerified": true,
|
|
27
|
+
"previewTotal": 10,
|
|
28
|
+
"currency": "usd",
|
|
29
|
+
"paymentVerified": false,
|
|
30
|
+
"creditPurchaseVerified": false,
|
|
31
|
+
"invoiceFinalizationVerified": false
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"model": "prepaid",
|
|
35
|
+
"catalogCreated": true,
|
|
36
|
+
"eventAccepted": true,
|
|
37
|
+
"aggregatedQuantity": 15,
|
|
38
|
+
"aggregationVerified": true,
|
|
39
|
+
"duplicateRetryVerified": true,
|
|
40
|
+
"invoiceIdentityVerified": true,
|
|
41
|
+
"previewTotal": 0,
|
|
42
|
+
"currency": "usd",
|
|
43
|
+
"paymentVerified": false,
|
|
44
|
+
"creditPurchaseVerified": false,
|
|
45
|
+
"invoiceFinalizationVerified": false
|
|
46
|
+
}
|
|
47
|
+
],
|
|
48
|
+
"cleanup": [
|
|
49
|
+
{
|
|
50
|
+
"kind": "credit",
|
|
51
|
+
"success": true
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"kind": "subscription",
|
|
55
|
+
"success": true
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"kind": "price",
|
|
59
|
+
"success": true
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
"kind": "product",
|
|
63
|
+
"success": true
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"kind": "meter",
|
|
67
|
+
"success": true
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"kind": "subscription",
|
|
71
|
+
"success": true
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
"kind": "price",
|
|
75
|
+
"success": true
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"kind": "product",
|
|
79
|
+
"success": true
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"kind": "meter",
|
|
83
|
+
"success": true
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
"kind": "subscription",
|
|
87
|
+
"success": true
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
"kind": "price",
|
|
91
|
+
"success": true
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
"kind": "product",
|
|
95
|
+
"success": true
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
"kind": "meter",
|
|
99
|
+
"success": true
|
|
100
|
+
}
|
|
101
|
+
],
|
|
102
|
+
"payerMappingVerified": true
|
|
103
|
+
}
|
package/docs/metered-usage.md
CHANGED
|
@@ -373,3 +373,17 @@ than overwriting its original delivery or invoice receipt. A requested or
|
|
|
373
373
|
provider-accepted correction must not release spendable credits until confirmed.
|
|
374
374
|
|
|
375
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.
|
package/docs/metering-setup.md
CHANGED
|
@@ -7,7 +7,9 @@ native Stripe integration into the existing BetterStripe Convex component.
|
|
|
7
7
|
|
|
8
8
|
Current status: shared configuration/quantity helpers and repository sandbox probes
|
|
9
9
|
are implemented. Atomic recording and bounded local history are available through the
|
|
10
|
-
[usage ledger](usage-ledger.md). [Durable provider delivery](usage-delivery.md)
|
|
10
|
+
[usage ledger](usage-ledger.md). [Durable provider delivery](usage-delivery.md),
|
|
11
|
+
[scoped observations](usage-observations.md) and [managed metered subscriptions](usage-subscriptions.md)
|
|
12
|
+
are available. Allowance/credit
|
|
11
13
|
accounting and the three example UI flows are still under development. The probes
|
|
12
14
|
below verify provider behavior directly; they are not public BetterStripe billing
|
|
13
15
|
workflows. See [metered usage contracts and evidence](metered-usage.md).
|
|
@@ -186,3 +188,5 @@ Primary references:
|
|
|
186
188
|
Use the [native catalog guide](usage-catalog.md) to provision versioned meters and prices through BetterStripe.
|
|
187
189
|
|
|
188
190
|
Use the [usage observation guide](usage-observations.md) for bounded local reads, native aggregate refreshes and honest invoice/credit availability.
|
|
191
|
+
|
|
192
|
+
For managed package enrollment, mixed fixed/metered items, Checkout, period-end cancellation and test-clock invoice verification, follow [usage subscriptions](usage-subscriptions.md).
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
# Metered subscriptions and invoice lifecycle
|
|
2
|
+
|
|
3
|
+
Use [native setup](metering-setup.md) and the [catalog APIs](usage-catalog.md)
|
|
4
|
+
first. `stripe.usage` provides managed subscriptions for pay-as-you-go, monthly
|
|
5
|
+
included usage with overages, and prepaid usage. Each uses the original native
|
|
6
|
+
meter/price binding. Purchased prepaid grants and strict allowance reservations
|
|
7
|
+
are separate accounting APIs. Creating a subscription does not fund credits or
|
|
8
|
+
authorize consumption.
|
|
9
|
+
|
|
10
|
+
## Create a metered or mixed subscription
|
|
11
|
+
|
|
12
|
+
Authenticate the caller and authorize the entire realm, Accounts v2 payer and
|
|
13
|
+
every meter on the server. Resolve `meters` from server-owned catalog bindings.
|
|
14
|
+
Do not accept a browser-supplied payer, price, plan, quantity or arbitrary JSON
|
|
15
|
+
for a component mutation. The native key must own the requested realm and mode.
|
|
16
|
+
The component verifies the Accounts v2 payer's native customer mapping.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
const signup = {
|
|
20
|
+
requestId: activity.subscriptionSignupId, // Stable across retries.
|
|
21
|
+
meters: [{ scope: verifiedScope, binding: originalBinding }],
|
|
22
|
+
fixedPriceIds: [], // Optional monthly licensed prices, e.g. a base fee.
|
|
23
|
+
collection: { method: "send_invoice" as const, daysUntilDue: 30 },
|
|
24
|
+
};
|
|
25
|
+
const current = await stripe.usage.ensureSubscription(ctx, signup, {
|
|
26
|
+
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
|
|
27
|
+
});
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
For automatic collection, use
|
|
31
|
+
`{method: "charge_automatically", defaultPaymentMethod: attachedPaymentMethodId}`.
|
|
32
|
+
The payment method must belong to the authorized payer. Initial payment can be
|
|
33
|
+
incomplete; an incomplete subscription is not permission to deliver work.
|
|
34
|
+
|
|
35
|
+
A request supports 1–10 unique meters and up to 10 fixed prices, in one currency,
|
|
36
|
+
realm, mode and payer mapping. All items use monthly prices. Managed creation
|
|
37
|
+
uses native flexible billing. Metered items omit `quantity`; fixed items use one.
|
|
38
|
+
Tiered rates remain nullable in native item observations. Display the original
|
|
39
|
+
plan's exact rate and unit rather than treating a nullable native rate as zero.
|
|
40
|
+
Fixed fees, taxes and other invoice lines are separate from metered line amounts.
|
|
41
|
+
|
|
42
|
+
The component persists immutable signup terms and atomically locks each native
|
|
43
|
+
customer/meter before creation. Changed terms under the same request ID conflict.
|
|
44
|
+
Concurrent payer aliases cannot reserve that native customer/meter twice. Native
|
|
45
|
+
subscription discovery is bounded to ten pages of 100. Active overlapping meter
|
|
46
|
+
subscriptions, incomplete item pages and ambiguous identities block creation.
|
|
47
|
+
Use managed enrollment for every writer in that realm. Component locks cannot
|
|
48
|
+
serialize independent Dashboard/API writers or unrelated external Checkout
|
|
49
|
+
sessions; preflight checks detect existing native overlaps, and hosts must
|
|
50
|
+
prevent concurrent external enrollment.
|
|
51
|
+
|
|
52
|
+
A stable Stripe idempotency key and retained native ID survive component write
|
|
53
|
+
failures. An absent pinned object never triggers recreation. Recovery can discover
|
|
54
|
+
a matching original subscription; an unresolved create is held after 23 hours
|
|
55
|
+
instead of sending a new billable request after Stripe's idempotency window.
|
|
56
|
+
Keep the original request ID and resolve that outcome before starting another.
|
|
57
|
+
Provider errors contain fixed messages and typed `UsageSubscriptionError.code`
|
|
58
|
+
values, without raw Stripe response bodies or credentials.
|
|
59
|
+
|
|
60
|
+
## Checkout
|
|
61
|
+
|
|
62
|
+
Use the same original bindings with a Checkout collection policy:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const session = await stripe.usage.ensureCheckout(
|
|
66
|
+
ctx,
|
|
67
|
+
{
|
|
68
|
+
...signup,
|
|
69
|
+
collection: {
|
|
70
|
+
method: "checkout",
|
|
71
|
+
successUrl: "https://your-app.example/billing/success",
|
|
72
|
+
cancelUrl: "https://your-app.example/billing",
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
{ stripeSecretKey: process.env.STRIPE_SECRET_KEY },
|
|
76
|
+
);
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Redirect to the returned `url` only while its status is `open`. Open, completed
|
|
80
|
+
and expired sessions retain their original identity. An expired signup is not
|
|
81
|
+
silently replaced. A completed session exposes its verified subscription after
|
|
82
|
+
native retrieval. The redirect is not payment or enrollment evidence; use the
|
|
83
|
+
subscription and invoice observations. Pending signup locks stay held until the native outcome is reconciled,
|
|
84
|
+
preventing another concurrent signup. For a verified expired session with no
|
|
85
|
+
subscription, PaymentIntent or SetupIntent and no payment received, call
|
|
86
|
+
`abandonSignup(ctx, ref, providerOptions)`. The same API supports a verified
|
|
87
|
+
`incomplete_expired` subscription only when its original initial invoice is void
|
|
88
|
+
and unpaid, with no recorded usage or pending reservations. It retains the
|
|
89
|
+
original terms and closure evidence, then permits a new request ID. Unknown
|
|
90
|
+
creates, incomplete payments and unresolved financial references stay held.
|
|
91
|
+
|
|
92
|
+
## Read current terms and retained history
|
|
93
|
+
|
|
94
|
+
The subscription reference has no single meter because a subscription can contain
|
|
95
|
+
several:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
const ref = {
|
|
99
|
+
scope: {
|
|
100
|
+
stripeAccountId: verifiedScope.stripeAccountId,
|
|
101
|
+
customerAccount: verifiedScope.customerAccount,
|
|
102
|
+
livemode: verifiedScope.livemode,
|
|
103
|
+
},
|
|
104
|
+
requestId: signup.requestId,
|
|
105
|
+
};
|
|
106
|
+
const cached = await stripe.usage.getSubscription(ctx, ref); // Reactive query.
|
|
107
|
+
const refreshed = await stripe.usage.observeSubscription(ctx, ref, {
|
|
108
|
+
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
|
|
109
|
+
});
|
|
110
|
+
const history = await stripe.usage.readSubscriptionHistory(ctx, {
|
|
111
|
+
...ref,
|
|
112
|
+
kind: "subscription",
|
|
113
|
+
limit: 20,
|
|
114
|
+
cursor: null,
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The managed mirror includes every item, original source binding and actual
|
|
119
|
+
collection policy. Native collection method, invoice due days and configured
|
|
120
|
+
automatic payment method must match the original agreement. Delivery verifies
|
|
121
|
+
that policy again immediately before sending. Each metered binding contains its own native subscription/item/price
|
|
122
|
+
and half-open Unix-second period. Renewals produce a new snapshot; prior periods
|
|
123
|
+
remain immutable. Refresh before authorizing current work. Cached observation
|
|
124
|
+
times are not a guarantee of current native state. Historical prices are never
|
|
125
|
+
replaced by current prices. Changed or incomplete native items return an error
|
|
126
|
+
until their provenance is resolved.
|
|
127
|
+
|
|
128
|
+
History supports `subscription`, `invoice` and `retirement`, bounded pages of
|
|
129
|
+
1–100 and `isDone`/`cursor`. Continue until done, including an empty final page
|
|
130
|
+
when necessary. Duplicate snapshots deduplicate; older in-flight observations
|
|
131
|
+
cannot replace a newer current projection. Each enrollment retains at most
|
|
132
|
+
100,000 immutable history observations. Exhaustion blocks new writes and requires
|
|
133
|
+
an explicit archival/migration plan; financial evidence is never automatically
|
|
134
|
+
deleted. Existing fixed-price APIs remain compatible and retain their existing
|
|
135
|
+
read contracts. Use these managed readers for the full metered item list.
|
|
136
|
+
|
|
137
|
+
Managed subscription and invoice webhooks re-read native state before projection.
|
|
138
|
+
They retain the `bsUsageIntent` marker created by the package. Preserve that
|
|
139
|
+
metadata and the configured webhook routes. Older signed payloads cannot directly
|
|
140
|
+
rewind managed state. Native lookup failures leave the webhook retryable with a
|
|
141
|
+
fixed redacted error. Hosts may also refresh explicitly after downtime.
|
|
142
|
+
|
|
143
|
+
## Closeout, cancellation and model changes
|
|
144
|
+
|
|
145
|
+
Managed v1 closes new acceptance and new delivery attempts 60 seconds before the
|
|
146
|
+
original period ends. This is an operational buffer, not proof of invoice
|
|
147
|
+
inclusion. New acceptance requires the original active managed binding; receipt
|
|
148
|
+
replays still return the original record after closeout. New usage is rejected
|
|
149
|
+
when the native period/binding is closed or has changed. Queue work for the next
|
|
150
|
+
verified service period before it runs; do not move completed activity's original
|
|
151
|
+
timestamp, source ID or pricing to make it billable again.
|
|
152
|
+
|
|
153
|
+
Delivery rechecks the cutoff after preflight and reserves transport time before
|
|
154
|
+
sending. Queued usage that reaches closeout becomes held with
|
|
155
|
+
`billing_period_closed`. In-flight responses remain recorded, including unknown
|
|
156
|
+
outcomes. Inspect [delivery history](usage-delivery.md), native aggregates and
|
|
157
|
+
invoices; resolve held/unknown/rejected usage through the correction workflow.
|
|
158
|
+
Neither a clock advance nor an API receipt proves ingestion or invoicing.
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
await stripe.usage.setCancelAtPeriodEnd(
|
|
162
|
+
ctx,
|
|
163
|
+
{
|
|
164
|
+
...ref,
|
|
165
|
+
operationId: cancellationCommandId,
|
|
166
|
+
cancelAtPeriodEnd: true,
|
|
167
|
+
},
|
|
168
|
+
providerOptions,
|
|
169
|
+
);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Use a new command ID with `cancelAtPeriodEnd: false` to undo scheduled cancellation
|
|
173
|
+
before Stripe cancels the subscription. Commands serialize per enrollment, reject
|
|
174
|
+
changed retries, retain unknown outcomes, and stop blind writes after 23 hours.
|
|
175
|
+
A replay returns the original command result; refresh separately for current
|
|
176
|
+
state. A canceled native subscription cannot be reactivated.
|
|
177
|
+
|
|
178
|
+
There is no managed immediate-delete, mid-cycle price swap, automatic proration,
|
|
179
|
+
credit conversion or account-closure shortcut. Native mid-cycle changes can omit
|
|
180
|
+
old or late usage, including in flexible billing. Use period-end cancellation,
|
|
181
|
+
drain delivery and resolve reservations, then observe the final period invoice.
|
|
182
|
+
Account closure preparation checks indexed enrollment locks for both the payer
|
|
183
|
+
and the billing realm, including retries. Signup checks pending and completed
|
|
184
|
+
closures before reserving enrollment. Both checks run in their respective
|
|
185
|
+
transactions, so concurrent closure and signup cannot both proceed. Retirement
|
|
186
|
+
or verified abandonment releases the locks.
|
|
187
|
+
|
|
188
|
+
An account closure must follow the same closeout process before deactivating its
|
|
189
|
+
customer configuration or credentials. External changes are detected on refresh;
|
|
190
|
+
they never rewrite retained events. Generic subscription APIs still require host
|
|
191
|
+
policy for lifecycle operations. Account closure uses the enrollment guard above.
|
|
192
|
+
|
|
193
|
+
After native cancellation, a finalized cycle invoice covering the closed period,
|
|
194
|
+
and no pending local sends, validation errors, reservations or cancellation
|
|
195
|
+
commands, retire the enrollment:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
await stripe.usage.retireSubscription(
|
|
199
|
+
ctx,
|
|
200
|
+
{ ...ref, invoiceId: finalInvoiceId },
|
|
201
|
+
providerOptions,
|
|
202
|
+
);
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
This releases its enrollment locks so a new request ID can configure a new model
|
|
206
|
+
or price. Original events, invoices, purchases and credits remain associated with
|
|
207
|
+
their original terms. Retirement does not establish payment or exact invoice
|
|
208
|
+
reconciliation; its result explicitly retains `billingReconciliation: "required"`.
|
|
209
|
+
No historical activity is copied or rebilled. Unused credits do not become credit
|
|
210
|
+
on a new price or currency. Resolve their original expiry/refund policy separately.
|
|
211
|
+
|
|
212
|
+
## Invoice evidence and late usage
|
|
213
|
+
|
|
214
|
+
`observeSubscriptionInvoice(ctx, {...ref, invoiceId}, providerOptions)` verifies
|
|
215
|
+
native realm/mode, payer, subscription and original metered item references,
|
|
216
|
+
then retains a bounded observation for each configured meter. Historical line
|
|
217
|
+
periods and prices remain native evidence. Missing/incomplete lines stay
|
|
218
|
+
unavailable, never an inferred zero. Whole-invoice totals include fixed lines;
|
|
219
|
+
matching meter amounts remain separate. Use `readInvoiceUsage` for previews as
|
|
220
|
+
described in [usage observations](usage-observations.md). Managed history retains
|
|
221
|
+
existing invoice observations, including finalized and paid status.
|
|
222
|
+
|
|
223
|
+
A paid invoice can be covered by credits or marked paid out of band. Its
|
|
224
|
+
`paymentEvidence` stays `not_resolved`. Prepaid application must not create a new
|
|
225
|
+
usage payment or seller settlement. Verify actual payment provenance separately
|
|
226
|
+
before distributing money. These managed readers do not finalize, charge, refund
|
|
227
|
+
or settle invoices.
|
|
228
|
+
|
|
229
|
+
Stripe accepts eligible meter events within its ingestion window, but late
|
|
230
|
+
acceptance does not guarantee invoice inclusion. Configure and verify the native
|
|
231
|
+
invoice finalization grace period for your delivery latency. Only applicable
|
|
232
|
+
cycle/phase-transition invoices collect grace-period usage. Threshold and initial
|
|
233
|
+
invoices have earlier cutoffs, and mid-cycle price changes have additional late
|
|
234
|
+
usage limitations. Do not resend accepted usage under a new ID to fix an invoice.
|
|
235
|
+
|
|
236
|
+
## Verify native test-clock behavior
|
|
237
|
+
|
|
238
|
+
From the repository root, using the test-only secret reference configured in
|
|
239
|
+
[setup](metering-setup.md):
|
|
240
|
+
|
|
241
|
+
```sh
|
|
242
|
+
op run --env-file=.env.metering -- node scripts/metering-sandbox.mjs \
|
|
243
|
+
--verify-test-payment --finalize-test-invoices
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
This test-only probe attaches a test clock when first configuring the Accounts v2
|
|
247
|
+
customer, creates all three metered subscriptions, and confirms the 15-unit native
|
|
248
|
+
aggregates before advancing a billing period. It waits for clock readiness,
|
|
249
|
+
retrieves period-end invoices and explicitly finalizes a matching draft when
|
|
250
|
+
needed. It reports native totals and identity/finalization checks separately from
|
|
251
|
+
payment evidence. Expected totals are 30 USD cents for pay-as-you-go, 10 cents for
|
|
252
|
+
included overages and zero for credit-covered prepaid consumption. The prepaid
|
|
253
|
+
purchase is a separate 100-cent test payment. Synthetic usage uses the clock's
|
|
254
|
+
frozen timestamp. A bounded final re-read handles delayed aggregates before any
|
|
255
|
+
billing-clock advancement. Cleanup expires the grant, requests
|
|
256
|
+
its test refund, cancels subscriptions, archives catalog resources and deletes the
|
|
257
|
+
clock. Inspect every cleanup result.
|
|
258
|
+
|
|
259
|
+
This probe does not prove production clock behavior, application settlement or
|
|
260
|
+
strict credit reservation accounting. It creates synthetic sandbox resources and
|
|
261
|
+
rejects live keys before requests. Clock advancement is not evidence that meter
|
|
262
|
+
ingestion has completed. Keep the sanitized output as reviewer evidence and
|
|
263
|
+
report lag or unsupported account modes explicitly.
|
|
264
|
+
|
|
265
|
+
The [successful sandbox run](evidence/native-metering/clock-finalization-run.json)
|
|
266
|
+
confirmed all three 15-unit aggregates, final totals of 30/10/0 USD cents, the
|
|
267
|
+
separate paid prepaid purchase and all 15 cleanup requests. The
|
|
268
|
+
[earlier bounded lag run](evidence/native-metering/clock-lag-run.json) confirmed
|
|
269
|
+
only the first two aggregates and stopped before clock advancement. Both are
|
|
270
|
+
retained so missing data cannot be mistaken for a zero charge or successful
|
|
271
|
+
finalization.
|
|
272
|
+
|
|
273
|
+
Primary references: [native usage cutoff rules](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage-api),
|
|
274
|
+
[finalization grace periods](https://docs.stripe.com/billing/subscriptions/usage-based/configure-grace-period),
|
|
275
|
+
[flexible/classic changes and cancellation](https://docs.stripe.com/billing/subscriptions/usage-based/manage-billing-setup),
|
|
276
|
+
and [Accounts v2 test clocks](https://docs.stripe.com/billing/testing/test-clocks/api-advanced-usage),
|
|
277
|
+
[expired Checkout sessions](https://docs.stripe.com/api/checkout/sessions/expire),
|
|
278
|
+
and [initial payment expiry](https://docs.stripe.com/billing/subscriptions/overview).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.56.0",
|
|
4
4
|
"description": "A Convex component for Stripe V2 Accounts API integration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
@@ -104,7 +104,9 @@
|
|
|
104
104
|
"docs/usage-ledger.md",
|
|
105
105
|
"docs/usage-catalog.md",
|
|
106
106
|
"docs/usage-delivery.md",
|
|
107
|
-
"docs/usage-observations.md"
|
|
107
|
+
"docs/usage-observations.md",
|
|
108
|
+
"docs/usage-subscriptions.md",
|
|
109
|
+
"docs/evidence/native-metering"
|
|
108
110
|
],
|
|
109
111
|
"scripts": {
|
|
110
112
|
"build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
|
package/src/client/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { UsageSubscriptionError } from "./usage/subscriptionErrors.js";
|
|
1
2
|
export { UsageCatalogError } from "./usage/catalogTypes.js";
|
|
2
3
|
export type {
|
|
3
4
|
UsageCatalogScope,
|
|
@@ -1861,3 +1862,10 @@ export type {
|
|
|
1861
1862
|
UsageInvoiceObservation,
|
|
1862
1863
|
UsageInvoiceLine,
|
|
1863
1864
|
} from "./usage/invoiceObservation.js";
|
|
1865
|
+
|
|
1866
|
+
export type {
|
|
1867
|
+
UsageSubscriptionOptions,
|
|
1868
|
+
UsageSubscriptionView,
|
|
1869
|
+
} from "./usage/subscriptionTerms.js";
|
|
1870
|
+
export type { UsageSubscriptionRef } from "./usage/subscriptionLifecycle.js";
|
|
1871
|
+
export type { UsageSubscriptionInvoice } from "./usage/subscriptionInvoiceSchema.js";
|
|
@@ -249,3 +249,24 @@ export async function ensureUsagePrice(
|
|
|
249
249
|
});
|
|
250
250
|
return price;
|
|
251
251
|
}
|
|
252
|
+
|
|
253
|
+
/** Validate an already pinned native price without creating or adopting it. */
|
|
254
|
+
export function verifyPinnedUsagePrice(
|
|
255
|
+
price: Stripe.Price,
|
|
256
|
+
scope: UsagePriceOptions["scope"],
|
|
257
|
+
plan: UsagePriceOptions["plan"],
|
|
258
|
+
meterId: string,
|
|
259
|
+
) {
|
|
260
|
+
const productId =
|
|
261
|
+
typeof price.product === "string" ? price.product : price.product.id;
|
|
262
|
+
if (!price.lookup_key) return incompatible();
|
|
263
|
+
const opts = {
|
|
264
|
+
scope,
|
|
265
|
+
plan,
|
|
266
|
+
meterId,
|
|
267
|
+
stripeProductId: productId,
|
|
268
|
+
lookupKey: price.lookup_key,
|
|
269
|
+
};
|
|
270
|
+
const { rate, included } = termsFor(opts);
|
|
271
|
+
verifyPrice(price, opts, rate, included);
|
|
272
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { UsageSubscriptionClient } from "./subscriptionClient.js";
|
|
2
2
|
import type { Component, RunCtx } from "../helpers.js";
|
|
3
3
|
import { runMutationOrThrow } from "../helpers.js";
|
|
4
4
|
import { componentRef } from "../webhooks/helpers.js";
|
|
@@ -46,7 +46,7 @@ function decode({ event, delivery }: StoredView): UsageEventView {
|
|
|
46
46
|
};
|
|
47
47
|
}
|
|
48
48
|
/** Trusted host facade. Authenticate and authorize each exact scope first. */
|
|
49
|
-
export class UsageLedgerClient extends
|
|
49
|
+
export class UsageLedgerClient extends UsageSubscriptionClient {
|
|
50
50
|
constructor(component: Component) {
|
|
51
51
|
super(component);
|
|
52
52
|
}
|
|
@@ -11,7 +11,11 @@ const scope = {
|
|
|
11
11
|
meterId: "mtr_calls",
|
|
12
12
|
livemode: false,
|
|
13
13
|
};
|
|
14
|
-
function setup(
|
|
14
|
+
function setup(
|
|
15
|
+
status = 200,
|
|
16
|
+
errorCode = "parameter_invalid_integer",
|
|
17
|
+
nativeOverrides: Record<string, unknown> = {},
|
|
18
|
+
) {
|
|
15
19
|
const now = Math.floor(Date.now() / 1000);
|
|
16
20
|
const record = prepareUsageRecord({
|
|
17
21
|
scope,
|
|
@@ -32,6 +36,12 @@ function setup(status = 200, errorCode = "parameter_invalid_integer") {
|
|
|
32
36
|
occurredAt: now,
|
|
33
37
|
});
|
|
34
38
|
const saved = {
|
|
39
|
+
billingCutoff: null as number | null,
|
|
40
|
+
managedCollection: null as {
|
|
41
|
+
method: "send_invoice" | "charge_automatically";
|
|
42
|
+
daysUntilDue: number | null;
|
|
43
|
+
defaultPaymentMethod: string | null;
|
|
44
|
+
} | null,
|
|
35
45
|
event: {
|
|
36
46
|
recordJson: JSON.stringify(record),
|
|
37
47
|
subscriptionJson: JSON.stringify({
|
|
@@ -88,6 +98,7 @@ function setup(status = 200, errorCode = "parameter_invalid_integer") {
|
|
|
88
98
|
livemode: false,
|
|
89
99
|
customer: "cus_buyer",
|
|
90
100
|
customer_account: "acct_buyer",
|
|
101
|
+
...nativeOverrides,
|
|
91
102
|
}
|
|
92
103
|
: status === 200
|
|
93
104
|
? {
|
|
@@ -205,3 +216,61 @@ it("holds duplicate/uncertain errors and a lost response instead of retrying tra
|
|
|
205
216
|
).toHaveLength(1);
|
|
206
217
|
}
|
|
207
218
|
});
|
|
219
|
+
|
|
220
|
+
it("withholds a managed send that reaches its billing cutoff during preflight", async () => {
|
|
221
|
+
const f = setup();
|
|
222
|
+
const now = Math.floor(Date.now() / 1000);
|
|
223
|
+
f.saved.billingCutoff = now + 100;
|
|
224
|
+
let reads = 0;
|
|
225
|
+
vi.mocked(f.ctx.runQuery).mockImplementation(async () => {
|
|
226
|
+
reads++;
|
|
227
|
+
return { ...f.saved, billingCutoff: reads === 1 ? now + 100 : now + 10 };
|
|
228
|
+
});
|
|
229
|
+
const result = await deliverUsageProvider(
|
|
230
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
231
|
+
f.ctx,
|
|
232
|
+
f.request,
|
|
233
|
+
{ stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
|
|
234
|
+
);
|
|
235
|
+
expect(result.outcome.status).toBe("unknown");
|
|
236
|
+
expect(f.requests.some((r) => r.path === "/v1/billing/meter_events")).toBe(
|
|
237
|
+
false,
|
|
238
|
+
);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it("withholds a managed send when native manual invoicing drifts to automatic charging", async () => {
|
|
242
|
+
const now = Math.floor(Date.now() / 1000);
|
|
243
|
+
const f = setup(200, "parameter_invalid_integer", {
|
|
244
|
+
status: "active",
|
|
245
|
+
collection_method: "charge_automatically",
|
|
246
|
+
days_until_due: null,
|
|
247
|
+
default_payment_method: "pm_owned",
|
|
248
|
+
items: {
|
|
249
|
+
has_more: false,
|
|
250
|
+
data: [
|
|
251
|
+
{
|
|
252
|
+
id: "si_calls",
|
|
253
|
+
price: { id: "price_calls" },
|
|
254
|
+
current_period_start: now - 1,
|
|
255
|
+
current_period_end: now + 86400,
|
|
256
|
+
},
|
|
257
|
+
],
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
f.saved.billingCutoff = now + 86400 - 60;
|
|
261
|
+
f.saved.managedCollection = {
|
|
262
|
+
method: "send_invoice",
|
|
263
|
+
daysUntilDue: 30,
|
|
264
|
+
defaultPaymentMethod: null,
|
|
265
|
+
};
|
|
266
|
+
const result = await deliverUsageProvider(
|
|
267
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
268
|
+
f.ctx,
|
|
269
|
+
f.request,
|
|
270
|
+
{ stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
|
|
271
|
+
);
|
|
272
|
+
expect(result.outcome.status).toBe("unavailable");
|
|
273
|
+
expect(f.requests.some((r) => r.path === "/v1/billing/meter_events")).toBe(
|
|
274
|
+
false,
|
|
275
|
+
);
|
|
276
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { UsageSubscriptionView } from "./subscriptionTerms.js";
|
|
1
2
|
import Stripe from "stripe";
|
|
2
3
|
import type { StripeApiVersion } from "../stripe-types.js";
|
|
3
4
|
import { z } from "zod";
|
|
@@ -50,7 +51,12 @@ export async function deliverUsageProvider(
|
|
|
50
51
|
ctx.runQuery(componentRef(component, "usageDelivery/queries/snapshot"), {
|
|
51
52
|
scope: args.scope,
|
|
52
53
|
eventId: args.eventId,
|
|
53
|
-
}) as Promise<{
|
|
54
|
+
}) as Promise<{
|
|
55
|
+
event: Doc<"usageEvents">;
|
|
56
|
+
outbox: Doc<"usageOutbox">;
|
|
57
|
+
billingCutoff: number | null;
|
|
58
|
+
managedCollection: UsageSubscriptionView["collection"] | null;
|
|
59
|
+
}>;
|
|
54
60
|
const saved = await read(),
|
|
55
61
|
record = JSON.parse(saved.event.recordJson) as PreparedUsageRecord;
|
|
56
62
|
const eligible = (outbox: Doc<"usageOutbox">) =>
|
|
@@ -64,6 +70,8 @@ export async function deliverUsageProvider(
|
|
|
64
70
|
(outbox.leaseUntil ?? 0) > Date.now() / 1000 + 60;
|
|
65
71
|
if (
|
|
66
72
|
!eligible(saved.outbox) ||
|
|
73
|
+
(saved.billingCutoff !== null &&
|
|
74
|
+
Date.now() / 1000 + 15 >= saved.billingCutoff) ||
|
|
67
75
|
record.binding.apiVersion !== apiVersion ||
|
|
68
76
|
JSON.stringify(record.scope) !== JSON.stringify(args.scope)
|
|
69
77
|
)
|
|
@@ -96,7 +104,40 @@ export async function deliverUsageProvider(
|
|
|
96
104
|
eventName: record.binding.eventName,
|
|
97
105
|
displayName: meter.display_name,
|
|
98
106
|
});
|
|
99
|
-
|
|
107
|
+
const current = await read();
|
|
108
|
+
if (
|
|
109
|
+
!eligible(current.outbox) ||
|
|
110
|
+
(current.billingCutoff !== null &&
|
|
111
|
+
Date.now() / 1000 + 15 >= current.billingCutoff)
|
|
112
|
+
)
|
|
113
|
+
return done({ status: "unknown" });
|
|
114
|
+
if (current.billingCutoff !== null) {
|
|
115
|
+
const collection = current.managedCollection;
|
|
116
|
+
const method =
|
|
117
|
+
typeof subscription.default_payment_method === "string"
|
|
118
|
+
? subscription.default_payment_method
|
|
119
|
+
: (subscription.default_payment_method?.id ?? null);
|
|
120
|
+
if (
|
|
121
|
+
!collection ||
|
|
122
|
+
collection.method !== subscription.collection_method ||
|
|
123
|
+
(collection.method === "send_invoice"
|
|
124
|
+
? collection.daysUntilDue !== subscription.days_until_due
|
|
125
|
+
: collection.defaultPaymentMethod !== method)
|
|
126
|
+
)
|
|
127
|
+
return done({ status: "unavailable" });
|
|
128
|
+
const item = subscription.items.data.find(
|
|
129
|
+
(item) => item.id === binding.subscriptionItemId,
|
|
130
|
+
);
|
|
131
|
+
if (
|
|
132
|
+
subscription.status !== "active" ||
|
|
133
|
+
subscription.items.has_more ||
|
|
134
|
+
!item ||
|
|
135
|
+
item.price.id !== binding.stripePriceId ||
|
|
136
|
+
item.current_period_start !== binding.period.start ||
|
|
137
|
+
item.current_period_end !== binding.period.end
|
|
138
|
+
)
|
|
139
|
+
return done({ status: "unavailable" });
|
|
140
|
+
}
|
|
100
141
|
writing = true;
|
|
101
142
|
const response = await stripe.billing.meterEvents.create(
|
|
102
143
|
{
|
|
@@ -63,3 +63,12 @@ export type {
|
|
|
63
63
|
UsageInvoiceObservation,
|
|
64
64
|
UsageInvoiceLine,
|
|
65
65
|
} from "./invoiceObservation.js";
|
|
66
|
+
|
|
67
|
+
export type {
|
|
68
|
+
UsageSubscriptionOptions,
|
|
69
|
+
UsageSubscriptionView,
|
|
70
|
+
} from "./subscriptionTerms.js";
|
|
71
|
+
export type { UsageSubscriptionRef } from "./subscriptionLifecycle.js";
|
|
72
|
+
export type { UsageSubscriptionInvoice } from "./subscriptionInvoiceSchema.js";
|
|
73
|
+
|
|
74
|
+
export { UsageSubscriptionError } from "./subscriptionErrors.js";
|