@hjam91/billing 0.8.0 → 0.10.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/README.md +110 -0
- package/dist/admin.d.ts +58 -0
- package/dist/admin.js +4 -0
- package/dist/config.d.ts +17 -2
- package/dist/hono.js +84 -1
- package/dist/index.d.ts +47 -1
- package/dist/index.js +129 -41
- package/dist/react.d.ts +98 -1
- package/dist/react.js +206 -5
- package/dist/types.d.ts +47 -4
- package/dist/usage.d.ts +39 -0
- package/dist/usage.js +65 -0
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -19,6 +19,22 @@ npm install @hjam91/billing
|
|
|
19
19
|
|
|
20
20
|
`hono` and `react` are optional peer dependencies, needed only for `@hjam91/billing/hono` and `@hjam91/billing/react`.
|
|
21
21
|
|
|
22
|
+
## 0.10.0: tiered plans (priced by a count your app reports)
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// billing.config.ts — the ladder is the source of truth; the service renders it as one tiered Stripe price
|
|
26
|
+
plans: { masjid: { price: { currency: 'usd', interval: 'month', tiers: [{ up_to: 10, amount: 2500 }, { up_to: 25, amount: 3900 }, { up_to: 500, amount: 19900 }] }, unit: 'students' } }
|
|
27
|
+
|
|
28
|
+
await billing.checkout({ accountId, plan: 'masjid', quantity: students, successUrl, cancelUrl }); // starts at the right tier
|
|
29
|
+
const r = await billing.setQuantity(accountId, students); // idempotent: unchanged | applied (now, prorated up a tier; no proration within) | scheduled (down a tier, period end) | requires_action
|
|
30
|
+
if (r.subscription?.over_max) contactUs(r.subscription.reported_quantity); // past the ladder: still active, held at the top tier
|
|
31
|
+
const { plans } = await billing.plans(); // plan.tiers [{from, up_to, amount}], max_quantity, unit
|
|
32
|
+
await billing.changePlan(accountId, 'masjid', { quantity: 6 }); // another ladder, with the count
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Above the ladder, Checkout and plan changes throw `custom_pricing_required`; the owner sets a custom plan or exempts the account.
|
|
36
|
+
`setQuantity` is `changeQuantity` under its new name. Needs a service on migration 0018.
|
|
37
|
+
|
|
22
38
|
## 0.8.0: discounts and offers
|
|
23
39
|
|
|
24
40
|
Needs a billing service with migration 0016. Owner-made discount codes customers type, and automatic offers.
|
|
@@ -46,6 +62,12 @@ for (const o of await billing.offers(orgId)) {
|
|
|
46
62
|
`offers()`, `createOffer({name, audience, …terms, afterDays?, withinDays?, headline?, active?})`,
|
|
47
63
|
`updateOffer(id, {active?, headline?, name?, afterDays?, withinDays?})` (never the money). Creating needs a key with
|
|
48
64
|
the `pricing` scope; on an app billed through the service owner's Stripe account only the owner creates them.
|
|
65
|
+
- Admin, since 0.9.0: `redemptions({accountId?})` answers `{redemptions: RedemptionAdminView[]}`, every code and offer
|
|
66
|
+
redemption newest first (at most 1000) with its subscription, `plan`, `subscription_status` and `discount_active`
|
|
67
|
+
(the subscription still carries a discount); `read` scope. `removeDiscount(accountId, {subscriptionId?})` ends the
|
|
68
|
+
discount on the account's own live discounted subscriptions so the next invoice is full price, and answers the
|
|
69
|
+
account status (`support` scope, like `cancel`; 404 `discount_not_found` when there is none, 409
|
|
70
|
+
`operation_in_progress` under a pending plan change). The code or offer itself is untouched.
|
|
49
71
|
- `billingRoutes` (Hono) adds `GET /offers`, `POST /discount {code, plan?}`, `POST /accept-offer {offer_id}`, and
|
|
50
72
|
`discount_code` / `offer_id` on `POST /checkout`; a refused code answers its `reason`.
|
|
51
73
|
|
|
@@ -174,3 +196,91 @@ needs Node >= 22.18; `.json` / `.mjs` configs work on any supported Node.
|
|
|
174
196
|
|
|
175
197
|
Full API documentation will be published at a public URL (placeholder: _API docs link_). Every export carries TSDoc in
|
|
176
198
|
its `.d.ts`.
|
|
199
|
+
|
|
200
|
+
## Durable usage delivery
|
|
201
|
+
|
|
202
|
+
`flushUsage()` checks each event's result. Applied and replayed events are acknowledged;
|
|
203
|
+
permanent refusals are retained as rejected records, and transient failures retain their
|
|
204
|
+
original idempotency key for retry. An HTTP 200 with missing results does not acknowledge
|
|
205
|
+
usage. Inspect `usageStatus()` and `rejectedUsage()`, correct the cause, then call
|
|
206
|
+
`retryUsage(recordIds)` and `flushUsage()`.
|
|
207
|
+
|
|
208
|
+
The default queue is bounded and process-local. For Cloudflare D1, apply
|
|
209
|
+
`USAGE_QUEUE_SCHEMA` to your app database once and configure the adapter:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
import { createBilling, d1UsageStore } from '@hjam91/billing';
|
|
213
|
+
const billing = createBilling({ baseUrl, appId, secret, usageStore: d1UsageStore(env.DB) });
|
|
214
|
+
await billing.track(accountId, 'credits', 1, { idempotencyKey: jobId });
|
|
215
|
+
ctx.waitUntil(billing.flushUsage());
|
|
216
|
+
const { pending, rejected, oldestPendingAt } = await billing.usageStatus();
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
A configured persistent queue writes the event before attempting its first request.
|
|
220
|
+
Schedule `flushUsage()` in a background job as well, so idle apps recover after an outage.
|
|
221
|
+
Storage failures are logged and never reported as successful persistence. Queue scope
|
|
222
|
+
includes service URL and app ID. Keep the database server-side: records may contain the
|
|
223
|
+
usage properties supplied by your app. Delivery is at least once; service idempotency
|
|
224
|
+
prevents duplicate counting. The service retains deduplication keys for 90 days, so recover
|
|
225
|
+
or resolve rejected records within that window rather than replaying older records blindly.
|
|
226
|
+
|
|
227
|
+
Custom stores implement `UsageStore` from `@hjam91/billing/usage`: `put`, `remove`, `list`
|
|
228
|
+
and `status`. Resolve each operation only after durable storage succeeds. Operations may
|
|
229
|
+
be called concurrently; the application owns retention and access control.
|
|
230
|
+
|
|
231
|
+
## Seat quantities and invoice billing
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const preview = await billing.previewQuantity(accountId, 12, { subscriptionId });
|
|
235
|
+
await billing.changeQuantity(accountId, 12, {
|
|
236
|
+
subscriptionId, prorationDate: preview.proration_date,
|
|
237
|
+
});
|
|
238
|
+
await billing.cancelScheduledChange(accountId, { subscriptionId });
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Quantity changes use the same explicit proration and scheduling options as plan changes.
|
|
242
|
+
Scheduled changes appear on `SubscriptionView.scheduled_change`. The application must
|
|
243
|
+
check that the signed-in user can manage the account before invoking these actions.
|
|
244
|
+
|
|
245
|
+
Business billing is opt-in through app settings or config-as-code: `automatic_tax`,
|
|
246
|
+
`collect_tax_id`, `collection_method` and `days_until_due`. For an app configured with
|
|
247
|
+
`collection_method: 'send_invoice'`, use `invoiceSubscription(accountId, plan, {email,
|
|
248
|
+
quantity, customerName})`; its result includes the hosted invoice URL and due date.
|
|
249
|
+
Automatic card collection remains the default. Configure the relevant Stripe tax settings
|
|
250
|
+
before enabling automatic tax.
|
|
251
|
+
|
|
252
|
+
Support integrations can list `admin.purchases(accountId)` and call
|
|
253
|
+
`admin.refundPurchase(accountId, purchaseId, {access: 'keep' | 'revoke', note})`. The
|
|
254
|
+
service computes the full remaining refundable amount. The explicit access policy controls
|
|
255
|
+
remaining credits and lifetime access; it does not reverse already consumed credits.
|
|
256
|
+
|
|
257
|
+
## Complete billing page
|
|
258
|
+
|
|
259
|
+
`BillingPanel` builds on the same `billingRoutes` authorization checks as `BillingCard`:
|
|
260
|
+
|
|
261
|
+
```tsx
|
|
262
|
+
import { BillingPanel } from '@hjam91/billing/react';
|
|
263
|
+
|
|
264
|
+
<BillingPanel
|
|
265
|
+
basePath="/api/billing"
|
|
266
|
+
locale="en-US"
|
|
267
|
+
onError={(error) => reportBillingError(error.code, error.status)}
|
|
268
|
+
/>
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
It includes plan and seat selection, a proration preview before confirmation, scheduled-change cancellation,
|
|
272
|
+
discount codes and eligible offers, credit balances and purchases, overage spending limits, and automatic top-up
|
|
273
|
+
settings. Automatic charges require the user's explicit checkbox consent. Plan changes use the subscription owned
|
|
274
|
+
by the current account; the app's `canManage` callback still guards every action. Multiple subscriptions get a
|
|
275
|
+
selector. `BillingCard` remains available for the compact status/portal experience.
|
|
276
|
+
|
|
277
|
+
Set `invoiceBilling` only for an app configured for invoice collection. This replaces the new-subscription Checkout
|
|
278
|
+
button with a billing-address form and **Request invoice**. Existing invoices show their due date and a hosted
|
|
279
|
+
payment link. Invoice collection, tax calculation and tax-ID collection are service policy; no Stripe secret belongs
|
|
280
|
+
in the browser.
|
|
281
|
+
|
|
282
|
+
For your own markup, `useBillingManagement()` exposes `previewPlan`, `previewQuantity`, `confirmChange`,
|
|
283
|
+
`cancelScheduledChange`, `checkDiscount`, `checkout`, `acceptOffer`, `purchaseCredits`, `saveUsageSettings`,
|
|
284
|
+
`requestInvoice`, and the current `plans`, `balances`, `offers`. Preserve the returned preview when confirming;
|
|
285
|
+
`confirmChange` sends its proration date and subscription selector. Errors retain `code`, `status` and `details`
|
|
286
|
+
through `BillingBrowserError` and the `onError` callback. All components are unstyled with `bk-` classes.
|
package/dist/admin.d.ts
CHANGED
|
@@ -121,6 +121,33 @@ export interface OfferAdminView {
|
|
|
121
121
|
created_at: string;
|
|
122
122
|
updated_at: string;
|
|
123
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* One redemption of a discount code (kind 'code') or an offer (kind 'offer'), as the owner sees it
|
|
126
|
+
* (GET /admin/apps/:app/redemptions; since 0.9.0).
|
|
127
|
+
*/
|
|
128
|
+
export interface RedemptionAdminView {
|
|
129
|
+
kind: 'code' | 'offer';
|
|
130
|
+
/** dsc_… (code) or ofr_… (offer). */
|
|
131
|
+
id: string;
|
|
132
|
+
/** The code (kind 'code'), else null. */
|
|
133
|
+
code: string | null;
|
|
134
|
+
/** The offer's name (kind 'offer'), else null. */
|
|
135
|
+
name: string | null;
|
|
136
|
+
/** The terms, as discountView shows them. */
|
|
137
|
+
discount: DiscountView;
|
|
138
|
+
account_id: string;
|
|
139
|
+
/** ISO. */
|
|
140
|
+
redeemed_at: string;
|
|
141
|
+
via: 'checkout' | 'accept';
|
|
142
|
+
stripe_subscription_id: string | null;
|
|
143
|
+
/** The subscription's status; null when the service has no subscription row for it. */
|
|
144
|
+
subscription_status: string | null;
|
|
145
|
+
plan: string | null;
|
|
146
|
+
/** The subscription is live and still carries a discount (percent / amount set, ends_at null or in the future). */
|
|
147
|
+
discount_active: boolean;
|
|
148
|
+
/** ISO; null = no end (or no discount). */
|
|
149
|
+
discount_ends_at: string | null;
|
|
150
|
+
}
|
|
124
151
|
/** The money of a code or an offer: percentOff XOR amountOff + currency (minor units). */
|
|
125
152
|
interface DiscountTermsParams {
|
|
126
153
|
percentOff?: number;
|
|
@@ -162,7 +189,23 @@ export interface OfferPatch {
|
|
|
162
189
|
afterDays?: number;
|
|
163
190
|
withinDays?: number | null;
|
|
164
191
|
}
|
|
192
|
+
export interface PurchaseRefundResult {
|
|
193
|
+
purchase_id: string;
|
|
194
|
+
refund_id: string | null;
|
|
195
|
+
status: string;
|
|
196
|
+
amount: number;
|
|
197
|
+
currency: string;
|
|
198
|
+
access: 'keep' | 'revoke';
|
|
199
|
+
account: AccountStatus;
|
|
200
|
+
}
|
|
165
201
|
export interface BillingAdmin {
|
|
202
|
+
purchases(accountId: string): Promise<{
|
|
203
|
+
purchases: Record<string, unknown>[];
|
|
204
|
+
}>;
|
|
205
|
+
refundPurchase(accountId: string, purchaseId: string, opts: {
|
|
206
|
+
access: 'keep' | 'revoke';
|
|
207
|
+
note?: string;
|
|
208
|
+
}): Promise<PurchaseRefundResult>;
|
|
166
209
|
/** The app's configuration (read). */
|
|
167
210
|
app(): Promise<Record<string, unknown>>;
|
|
168
211
|
/** Change policy (config scope): trial_days, grace_days, launched_at, prelaunch, trial_anchor, allow_promotion_codes, grace_on, refund_policy / revoke_on_refund, immediate_cancel_policy. */
|
|
@@ -272,6 +315,21 @@ export interface BillingAdmin {
|
|
|
272
315
|
createOffer(p: CreateOfferParams): Promise<OfferAdminView>;
|
|
273
316
|
/** Switch an offer on / off, reword it or move its window — never its money (config; since 0.8.0). */
|
|
274
317
|
updateOffer(id: string, patch: OfferPatch): Promise<OfferAdminView>;
|
|
318
|
+
/** Every code and offer redemption, newest first (at most 1000), or one account's (read; since 0.9.0). */
|
|
319
|
+
redemptions(opts?: {
|
|
320
|
+
accountId?: string;
|
|
321
|
+
}): Promise<{
|
|
322
|
+
redemptions: RedemptionAdminView[];
|
|
323
|
+
}>;
|
|
324
|
+
/**
|
|
325
|
+
* Ends the discount on the account's OWN live subscriptions that carry one (or the one named, by its sub_row_… or
|
|
326
|
+
* Stripe id), so the next invoice is full price; the code or offer itself is untouched (support scope, like cancel;
|
|
327
|
+
* since 0.9.0). 404 discount_not_found when there is nothing to remove; 409 operation_in_progress under a pending
|
|
328
|
+
* plan change.
|
|
329
|
+
*/
|
|
330
|
+
removeDiscount(accountId: string, params?: {
|
|
331
|
+
subscriptionId?: string;
|
|
332
|
+
}): Promise<AccountStatus>;
|
|
275
333
|
}
|
|
276
334
|
export declare function createBillingAdmin(opts: BillingAdminOptions): BillingAdmin;
|
|
277
335
|
export {};
|
package/dist/admin.js
CHANGED
|
@@ -110,6 +110,10 @@ export function createBillingAdmin(opts) {
|
|
|
110
110
|
...(x.afterDays !== undefined ? { after_days: x.afterDays } : {}),
|
|
111
111
|
...(x.withinDays !== undefined ? { within_days: x.withinDays } : {}),
|
|
112
112
|
})).offer,
|
|
113
|
+
redemptions: (o = {}) => call('GET', `/redemptions${o.accountId ? `?account=${enc(o.accountId)}` : ''}`),
|
|
114
|
+
removeDiscount: (accountId, p = {}) => call('POST', `/accounts/${enc(accountId)}/discount/remove`, p.subscriptionId ? { subscription_id: p.subscriptionId } : {}),
|
|
115
|
+
purchases: (accountId) => call('GET', `/accounts/${enc(accountId)}/purchases`),
|
|
116
|
+
refundPurchase: (accountId, purchaseId, o) => call('POST', `/accounts/${enc(accountId)}/purchases/${enc(purchaseId)}/refund`, o),
|
|
113
117
|
invoices: (accountId, o = {}) => call('GET', `/accounts/${enc(accountId)}/invoices${o.limit ? `?limit=${o.limit}` : ''}`),
|
|
114
118
|
refund: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/refunds`, {
|
|
115
119
|
invoice_id: p.invoiceId,
|
package/dist/config.d.ts
CHANGED
|
@@ -20,11 +20,20 @@
|
|
|
20
20
|
*/
|
|
21
21
|
export type FeatureType = 'boolean' | 'metered' | 'static' | 'credit_system';
|
|
22
22
|
export interface PriceSpec {
|
|
23
|
-
/** Minor units (1900 = $19.00). */
|
|
24
|
-
amount
|
|
23
|
+
/** Minor units (1900 = $19.00). Omitted when `tiers` prices the plan. */
|
|
24
|
+
amount?: number;
|
|
25
25
|
currency: string;
|
|
26
26
|
interval?: 'day' | 'week' | 'month' | 'year';
|
|
27
27
|
interval_count?: number;
|
|
28
|
+
/**
|
|
29
|
+
* 0.10: a ladder — the plan is priced by its quantity (a count the app reports: students, seats) in flat tiers.
|
|
30
|
+
* Ascending `up_to` boundaries (inclusive), a flat `amount` for the whole tier; the last `up_to` is the most the
|
|
31
|
+
* plan sells (above it: custom pricing). The service renders it as one volume-tiered price.
|
|
32
|
+
*/
|
|
33
|
+
tiers?: Array<{
|
|
34
|
+
up_to: number;
|
|
35
|
+
amount: number;
|
|
36
|
+
}>;
|
|
28
37
|
}
|
|
29
38
|
/** true / false for an on/off feature, or the allowance of a counted one. */
|
|
30
39
|
export type ItemSpec = boolean | {
|
|
@@ -58,8 +67,14 @@ export interface PlanSpec {
|
|
|
58
67
|
hidden?: true;
|
|
59
68
|
trial_days?: number;
|
|
60
69
|
items?: Record<string, ItemSpec>;
|
|
70
|
+
/** 0.10: what the quantity counts ("students"), shown on the pricing page. */
|
|
71
|
+
unit?: string;
|
|
61
72
|
}
|
|
62
73
|
export interface BillingConfig {
|
|
74
|
+
automatic_tax?: boolean;
|
|
75
|
+
collect_tax_id?: boolean;
|
|
76
|
+
collection_method?: 'charge_automatically' | 'send_invoice';
|
|
77
|
+
days_until_due?: number;
|
|
63
78
|
features?: Array<{
|
|
64
79
|
id: string;
|
|
65
80
|
name?: string;
|
package/dist/hono.js
CHANGED
|
@@ -183,15 +183,98 @@ export function billingRoutes(billing, opts) {
|
|
|
183
183
|
return asError(c, err);
|
|
184
184
|
}
|
|
185
185
|
});
|
|
186
|
+
for (const resource of ['plans', 'balances'])
|
|
187
|
+
r.get(`/${resource}`, async (c) => {
|
|
188
|
+
const accountId = await opts.getAccountId(c);
|
|
189
|
+
if (!accountId)
|
|
190
|
+
return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
|
|
191
|
+
try {
|
|
192
|
+
return c.json(resource === 'plans' ? await billing.plans() : await billing.balances(accountId));
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
return asError(c, err);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
186
198
|
r.post('/:action', async (c) => {
|
|
187
199
|
const accountId = await opts.getAccountId(c);
|
|
188
200
|
if (!accountId)
|
|
189
201
|
return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
|
|
190
202
|
if (!(await opts.canManage(c, accountId)))
|
|
191
203
|
return c.json({ error: 'forbidden', message: 'You cannot manage billing for this account' }, 403);
|
|
192
|
-
|
|
204
|
+
let body;
|
|
205
|
+
try {
|
|
206
|
+
const raw = await c.req.text();
|
|
207
|
+
const parsed = raw.trim() ? JSON.parse(raw) : {};
|
|
208
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
209
|
+
throw new Error('object required');
|
|
210
|
+
body = parsed;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return c.json({ error: 'invalid_json', message: 'A JSON object is required' }, 400);
|
|
214
|
+
}
|
|
215
|
+
if ((body.when !== undefined && body.when !== 'now' && body.when !== 'period_end')
|
|
216
|
+
|| (body.proration !== undefined && !['create_prorations', 'always_invoice', 'none'].includes(String(body.proration)))
|
|
217
|
+
|| (body.proration_date !== undefined && (!Number.isSafeInteger(body.proration_date) || Number(body.proration_date) < 0))
|
|
218
|
+
|| (body.subscription_id !== undefined && typeof body.subscription_id !== 'string')
|
|
219
|
+
|| (body.covers_account_id !== undefined && typeof body.covers_account_id !== 'string'))
|
|
220
|
+
return c.json({ error: 'invalid_field', message: 'Invalid subscription change options' }, 400);
|
|
221
|
+
const changeOptions = {
|
|
222
|
+
...(body.when === 'now' || body.when === 'period_end' ? { when: body.when } : {}),
|
|
223
|
+
...(body.proration === 'create_prorations' || body.proration === 'always_invoice' || body.proration === 'none' ? { proration: body.proration } : {}),
|
|
224
|
+
...(typeof body.proration_date === 'number' ? { prorationDate: body.proration_date } : {}),
|
|
225
|
+
...(typeof body.subscription_id === 'string' ? { subscriptionId: body.subscription_id } : {}),
|
|
226
|
+
...(typeof body.covers_account_id === 'string' ? { coversAccountId: body.covers_account_id } : {}),
|
|
227
|
+
};
|
|
193
228
|
try {
|
|
194
229
|
switch (c.req.param('action')) {
|
|
230
|
+
case 'invoice-subscription': {
|
|
231
|
+
if (typeof body.plan !== 'string' || !body.plan || (opts.plans && !opts.plans.includes(body.plan)))
|
|
232
|
+
return c.json({ error: 'unknown_plan' }, 400);
|
|
233
|
+
if (body.quantity !== undefined && (!Number.isSafeInteger(body.quantity) || Number(body.quantity) < 1))
|
|
234
|
+
return c.json({ error: 'invalid_field', message: 'quantity must be a positive integer' }, 400);
|
|
235
|
+
const address = body.billing_address;
|
|
236
|
+
if (address !== undefined && (!address || typeof address !== 'object' || Array.isArray(address) || !/^[A-Za-z]{2}$/.test(String(address.country ?? '')) || Object.entries(address).some(([key, value]) => !['country', 'line1', 'line2', 'city', 'state', 'postal_code'].includes(key) || typeof value !== 'string')))
|
|
237
|
+
return c.json({ error: 'invalid_field', message: 'billing_address needs a two-letter country and string address fields' }, 400);
|
|
238
|
+
return c.json({ ...(await billing.invoiceSubscription(accountId, body.plan, { quantity: body.quantity, email: (await opts.getEmail?.(c)) ?? undefined, ...(address ? { billingAddress: address } : {}) })), viewer_can_manage: true });
|
|
239
|
+
}
|
|
240
|
+
case 'preview-change':
|
|
241
|
+
case 'change-plan': {
|
|
242
|
+
if (typeof body.plan !== 'string' || !body.plan || (opts.plans && !opts.plans.includes(body.plan)))
|
|
243
|
+
return c.json({ error: 'unknown_plan' }, 400);
|
|
244
|
+
return c.json(c.req.param('action') === 'preview-change'
|
|
245
|
+
? await billing.previewChange(accountId, body.plan, changeOptions)
|
|
246
|
+
: { ...(await billing.changePlan(accountId, body.plan, changeOptions)), viewer_can_manage: true });
|
|
247
|
+
}
|
|
248
|
+
case 'preview-quantity':
|
|
249
|
+
case 'change-quantity': {
|
|
250
|
+
if (!Number.isSafeInteger(body.quantity) || Number(body.quantity) < 1)
|
|
251
|
+
return c.json({ error: 'invalid_field', message: 'quantity must be a positive integer' }, 400);
|
|
252
|
+
return c.json(c.req.param('action') === 'preview-quantity'
|
|
253
|
+
? await billing.previewQuantity(accountId, Number(body.quantity), changeOptions)
|
|
254
|
+
: { ...(await billing.changeQuantity(accountId, Number(body.quantity), changeOptions)), viewer_can_manage: true });
|
|
255
|
+
}
|
|
256
|
+
case 'cancel-schedule':
|
|
257
|
+
return c.json({ ...(await billing.cancelScheduledChange(accountId, changeOptions)), viewer_can_manage: true });
|
|
258
|
+
case 'topup': {
|
|
259
|
+
if (typeof body.product !== 'string' || !body.product)
|
|
260
|
+
return c.json({ error: 'invalid_field', message: 'product is required' }, 400);
|
|
261
|
+
if (body.quantity !== undefined && (!Number.isSafeInteger(body.quantity) || Number(body.quantity) < 1))
|
|
262
|
+
return c.json({ error: 'invalid_field', message: 'quantity must be a positive integer' }, 400);
|
|
263
|
+
const url = resolveReturn(c);
|
|
264
|
+
return c.json(await billing.topUp({ accountId, product: body.product, quantity: body.quantity, successUrl: url, cancelUrl: url, email: (await opts.getEmail?.(c)) ?? undefined }));
|
|
265
|
+
}
|
|
266
|
+
case 'usage-settings': {
|
|
267
|
+
const cap = body.spend_cap;
|
|
268
|
+
if (cap !== undefined && cap !== null && (typeof cap !== 'object' || Array.isArray(cap) || !Number.isSafeInteger(cap.amount) || Number(cap.amount) < 0 || typeof cap.currency !== 'string'))
|
|
269
|
+
return c.json({ error: 'invalid_field', message: 'spend_cap must contain amount and currency, or be null' }, 400);
|
|
270
|
+
const rules = body.auto_topups;
|
|
271
|
+
if (rules !== undefined && (!Array.isArray(rules) || rules.some((rule) => !rule || typeof rule !== 'object' || typeof rule.feature_id !== 'string' || typeof rule.product !== 'string' || typeof rule.auto !== 'boolean' || !Number.isFinite(rule.threshold) || rule.threshold < 0 || !Number.isSafeInteger(rule.max_per_month) || rule.max_per_month < 1)))
|
|
272
|
+
return c.json({ error: 'invalid_field', message: 'Each top-up rule needs a feature, product, threshold, explicit auto choice and monthly limit' }, 400);
|
|
273
|
+
return c.json(await billing.setUsageSettings(accountId, {
|
|
274
|
+
...(cap !== undefined ? { spendCap: cap } : {}),
|
|
275
|
+
...(Array.isArray(rules) ? { autoTopups: rules.map((r) => ({ featureId: r.feature_id, product: r.product, threshold: r.threshold, auto: r.auto, maxPerMonth: r.max_per_month })) } : {}),
|
|
276
|
+
}));
|
|
277
|
+
}
|
|
195
278
|
case 'checkout': {
|
|
196
279
|
const plan = typeof body.plan === 'string' ? body.plan : '';
|
|
197
280
|
if (!plan || (opts.plans && !opts.plans.includes(plan)))
|
package/dist/index.d.ts
CHANGED
|
@@ -27,11 +27,13 @@
|
|
|
27
27
|
* that in the app before calling checkout/portal/setAutoRenew.
|
|
28
28
|
*/
|
|
29
29
|
import { type CacheStore } from './cache.js';
|
|
30
|
+
import { type UsageRecord, type UsageStatus, type UsageStore } from './usage.js';
|
|
31
|
+
export { memoryUsageStore, d1UsageStore, USAGE_QUEUE_SCHEMA, type UsageRecord, type UsageStatus, type UsageStore, type UsageDatabase } from './usage.js';
|
|
30
32
|
import type { AccountInput, AccountStatus, Balances, ChangePreview, CheckResult, DiscountCheck, EntitlementResult, Lock, OfferView, PlanChange, PublicPlan, TrackResult, UpsertResult, UsageSettingsInput } from './types.js';
|
|
31
33
|
export * from './types.js';
|
|
32
34
|
export { BillingError, isOutage, killSignal } from './errors.js';
|
|
33
35
|
export { type BillingConfig, type ConfigChange, type ConfigPushResult, type PlanSpec, type PriceSpec, defineConfig, formatChanges } from './config.js';
|
|
34
|
-
export { type AppHealth, type BillingAdmin, type BillingAdminOptions, type CreateDiscountParams, type CreateOfferParams, type DiscountCodeAdminView, type InvoiceView, type OfferAdminView, type OfferPatch, type RefundParams, type RefundResult, createBillingAdmin } from './admin.js';
|
|
36
|
+
export { type AppHealth, type BillingAdmin, type BillingAdminOptions, type CreateDiscountParams, type CreateOfferParams, type DiscountCodeAdminView, type InvoiceView, type OfferAdminView, type OfferPatch, type RedemptionAdminView, type RefundParams, type RefundResult, type PurchaseRefundResult, createBillingAdmin } from './admin.js';
|
|
35
37
|
export { type CacheEntry, type CacheStore, memoryStore } from './cache.js';
|
|
36
38
|
export { BillingWebhookError, type BillingWebhookErrorCode, type VerifyOptions, verifyBillingEvent, verifyBillingWebhook } from './webhook.js';
|
|
37
39
|
/** What `onError` receives for every failed entitlement check. */
|
|
@@ -103,6 +105,8 @@ export interface BillingOptions {
|
|
|
103
105
|
usageBufferSize?: number;
|
|
104
106
|
/** A buffered track is dropped (and logged) after this many failed sends. Default 5. Since 0.5.0. */
|
|
105
107
|
usageMaxAttempts?: number;
|
|
108
|
+
/** Optional persistent delivery queue. Apply the adapter schema before use. */
|
|
109
|
+
usageStore?: UsageStore;
|
|
106
110
|
}
|
|
107
111
|
/** Options of `track()` (since 0.5.0). */
|
|
108
112
|
export interface TrackOptions {
|
|
@@ -126,6 +130,14 @@ export interface DeleteAccountResult {
|
|
|
126
130
|
/** What the service keeps after deletion (hashed trial marks, one audit entry). */
|
|
127
131
|
retained?: string[];
|
|
128
132
|
}
|
|
133
|
+
export interface BillingAddress {
|
|
134
|
+
country: string;
|
|
135
|
+
line1?: string;
|
|
136
|
+
line2?: string;
|
|
137
|
+
city?: string;
|
|
138
|
+
state?: string;
|
|
139
|
+
postal_code?: string;
|
|
140
|
+
}
|
|
129
141
|
export interface CheckoutParams {
|
|
130
142
|
accountId: string;
|
|
131
143
|
plan: string;
|
|
@@ -279,6 +291,10 @@ export interface Billing {
|
|
|
279
291
|
dropped: number;
|
|
280
292
|
pending: number;
|
|
281
293
|
}>;
|
|
294
|
+
usageStatus(): Promise<UsageStatus>;
|
|
295
|
+
rejectedUsage(limit?: number): Promise<UsageRecord[]>;
|
|
296
|
+
/** Retry selected rejected records after correcting their cause; original idempotency keys are kept. */
|
|
297
|
+
retryUsage(ids: string[]): Promise<number>;
|
|
282
298
|
/** Every balance of the account, its grants, held locks, auto top-ups and spend cap. Throws BillingError. Since 0.6.0. */
|
|
283
299
|
balances(accountId: string): Promise<Balances>;
|
|
284
300
|
/**
|
|
@@ -314,6 +330,34 @@ export interface Billing {
|
|
|
314
330
|
}>;
|
|
315
331
|
/** What changePlan would cost: amount due now, the next invoice, the lines. Since 0.7.0. */
|
|
316
332
|
previewChange(accountId: string, plan: string, opts?: PlanChangeOptions): Promise<ChangePreview>;
|
|
333
|
+
changeQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<AccountStatus & {
|
|
334
|
+
change: PlanChange;
|
|
335
|
+
}>;
|
|
336
|
+
/**
|
|
337
|
+
* 0.10: report the subscription's quantity (on a tiered plan, the count it is priced by: students, seats). Idempotent and
|
|
338
|
+
* cheap: call it on every change and in a daily reconcile. Up a tier: now, prorated; down a tier: at the period end;
|
|
339
|
+
* within a tier: quantity only, no proration; above the ladder: held at the top tier with `change.over_max`.
|
|
340
|
+
* The same as changeQuantity (its name since 0.9).
|
|
341
|
+
*/
|
|
342
|
+
setQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<AccountStatus & {
|
|
343
|
+
change: PlanChange;
|
|
344
|
+
}>;
|
|
345
|
+
previewQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<ChangePreview>;
|
|
346
|
+
cancelScheduledChange(accountId: string, select?: Omit<SubscriptionSelector, 'all'>): Promise<AccountStatus>;
|
|
347
|
+
/** Create a subscription billed by invoice, when enabled in the app's billing policy. */
|
|
348
|
+
invoiceSubscription(accountId: string, plan: string, opts?: {
|
|
349
|
+
quantity?: number;
|
|
350
|
+
email?: string;
|
|
351
|
+
customerName?: string;
|
|
352
|
+
billingAddress?: BillingAddress;
|
|
353
|
+
}): Promise<AccountStatus & {
|
|
354
|
+
invoice: {
|
|
355
|
+
id: string | null;
|
|
356
|
+
status: string | null;
|
|
357
|
+
hosted_invoice_url: string | null;
|
|
358
|
+
due_at: string | null;
|
|
359
|
+
};
|
|
360
|
+
}>;
|
|
317
361
|
/** Attaches an add-on plan (or sets its quantity) on the account's own subscription. Since 0.7.0. */
|
|
318
362
|
attachAddOn(accountId: string, plan: string, opts?: {
|
|
319
363
|
quantity?: number;
|
|
@@ -353,5 +397,7 @@ export interface PlanChangeOptions {
|
|
|
353
397
|
prorationDate?: number;
|
|
354
398
|
subscriptionId?: string;
|
|
355
399
|
coversAccountId?: string;
|
|
400
|
+
/** 0.10: set the quantity with the plan change (the count on a tiered plan), in one prorated step. Above the ladder: custom_pricing_required. */
|
|
401
|
+
quantity?: number;
|
|
356
402
|
}
|
|
357
403
|
export declare function createBilling(opts: BillingOptions): Billing;
|