@hjam91/billing 0.7.1 → 0.9.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 CHANGED
@@ -19,6 +19,42 @@ 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.8.0: discounts and offers
23
+
24
+ Needs a billing service with migration 0016. Owner-made discount codes customers type, and automatic offers.
25
+
26
+ ```ts
27
+ // Before Checkout: is the typed code good, and what does the first period cost?
28
+ const d = await billing.checkDiscount(orgId, typed, { plan: 'pro' });
29
+ if (!d.valid) showError(d.reason); // unknown | inactive | expired | used_up | not_first_time | plan_not_eligible
30
+ else show(`${d.discount.label}: ${d.plans[0].first_amount} instead of ${d.plans[0].amount}`);
31
+ const { url } = await billing.checkout({ accountId: orgId, plan: 'pro', successUrl, cancelUrl, discountCode: typed });
32
+
33
+ // Offers the account may take now: a comeback offer (lapsed), trial over (trial_ended), a save offer (canceling).
34
+ for (const o of await billing.offers(orgId)) {
35
+ if (o.audience === 'canceling') await billing.acceptOffer(orgId, o.id); // discount on, renewal back on
36
+ else await billing.checkout({ accountId: orgId, plan: o.plans[0].plan, successUrl, cancelUrl, offerId: o.id });
37
+ }
38
+ ```
39
+
40
+ - `checkDiscount` never throws for a code that cannot be used: it answers `{valid: false, reason}`. Checkout re-checks
41
+ and throws `BillingError` 409 `discount_invalid` (`details.reason`) or `offer_not_eligible`.
42
+ - Send at most one of `discountCode`, `offerId`, `promotionCode`; none with several `covers`.
43
+ - `acceptOffer` acts on the subscription the account OWNS: gate it with your `canManage`, like checkout.
44
+ - Admin (`createBillingAdmin`): `discounts()`, `createDiscount({code, percentOff | amountOff + currency, duration,
45
+ durationInMonths?, plans?, maxRedemptions?, firstTimeOnly?, expiresAt?, note?})`, `deactivateDiscount(id)`,
46
+ `offers()`, `createOffer({name, audience, …terms, afterDays?, withinDays?, headline?, active?})`,
47
+ `updateOffer(id, {active?, headline?, name?, afterDays?, withinDays?})` (never the money). Creating needs a key with
48
+ the `pricing` scope; on an app billed through the service owner's Stripe account only the owner creates them.
49
+ - Admin, since 0.9.0: `redemptions({accountId?})` answers `{redemptions: RedemptionAdminView[]}`, every code and offer
50
+ redemption newest first (at most 1000) with its subscription, `plan`, `subscription_status` and `discount_active`
51
+ (the subscription still carries a discount); `read` scope. `removeDiscount(accountId, {subscriptionId?})` ends the
52
+ discount on the account's own live discounted subscriptions so the next invoice is full price, and answers the
53
+ account status (`support` scope, like `cancel`; 404 `discount_not_found` when there is none, 409
54
+ `operation_in_progress` under a pending plan change). The code or offer itself is untouched.
55
+ - `billingRoutes` (Hono) adds `GET /offers`, `POST /discount {code, plan?}`, `POST /accept-offer {offer_id}`, and
56
+ `discount_code` / `offer_id` on `POST /checkout`; a refused code answers its `reason`.
57
+
22
58
  ## 0.7.1 fixes
23
59
 
24
60
  `plans()` can include the service's current `trial_days` and `trial_mode`, so apps
@@ -144,3 +180,91 @@ needs Node >= 22.18; `.json` / `.mjs` configs work on any supported Node.
144
180
 
145
181
  Full API documentation will be published at a public URL (placeholder: _API docs link_). Every export carries TSDoc in
146
182
  its `.d.ts`.
183
+
184
+ ## Durable usage delivery
185
+
186
+ `flushUsage()` checks each event's result. Applied and replayed events are acknowledged;
187
+ permanent refusals are retained as rejected records, and transient failures retain their
188
+ original idempotency key for retry. An HTTP 200 with missing results does not acknowledge
189
+ usage. Inspect `usageStatus()` and `rejectedUsage()`, correct the cause, then call
190
+ `retryUsage(recordIds)` and `flushUsage()`.
191
+
192
+ The default queue is bounded and process-local. For Cloudflare D1, apply
193
+ `USAGE_QUEUE_SCHEMA` to your app database once and configure the adapter:
194
+
195
+ ```ts
196
+ import { createBilling, d1UsageStore } from '@hjam91/billing';
197
+ const billing = createBilling({ baseUrl, appId, secret, usageStore: d1UsageStore(env.DB) });
198
+ await billing.track(accountId, 'credits', 1, { idempotencyKey: jobId });
199
+ ctx.waitUntil(billing.flushUsage());
200
+ const { pending, rejected, oldestPendingAt } = await billing.usageStatus();
201
+ ```
202
+
203
+ A configured persistent queue writes the event before attempting its first request.
204
+ Schedule `flushUsage()` in a background job as well, so idle apps recover after an outage.
205
+ Storage failures are logged and never reported as successful persistence. Queue scope
206
+ includes service URL and app ID. Keep the database server-side: records may contain the
207
+ usage properties supplied by your app. Delivery is at least once; service idempotency
208
+ prevents duplicate counting. The service retains deduplication keys for 90 days, so recover
209
+ or resolve rejected records within that window rather than replaying older records blindly.
210
+
211
+ Custom stores implement `UsageStore` from `@hjam91/billing/usage`: `put`, `remove`, `list`
212
+ and `status`. Resolve each operation only after durable storage succeeds. Operations may
213
+ be called concurrently; the application owns retention and access control.
214
+
215
+ ## Seat quantities and invoice billing
216
+
217
+ ```ts
218
+ const preview = await billing.previewQuantity(accountId, 12, { subscriptionId });
219
+ await billing.changeQuantity(accountId, 12, {
220
+ subscriptionId, prorationDate: preview.proration_date,
221
+ });
222
+ await billing.cancelScheduledChange(accountId, { subscriptionId });
223
+ ```
224
+
225
+ Quantity changes use the same explicit proration and scheduling options as plan changes.
226
+ Scheduled changes appear on `SubscriptionView.scheduled_change`. The application must
227
+ check that the signed-in user can manage the account before invoking these actions.
228
+
229
+ Business billing is opt-in through app settings or config-as-code: `automatic_tax`,
230
+ `collect_tax_id`, `collection_method` and `days_until_due`. For an app configured with
231
+ `collection_method: 'send_invoice'`, use `invoiceSubscription(accountId, plan, {email,
232
+ quantity, customerName})`; its result includes the hosted invoice URL and due date.
233
+ Automatic card collection remains the default. Configure the relevant Stripe tax settings
234
+ before enabling automatic tax.
235
+
236
+ Support integrations can list `admin.purchases(accountId)` and call
237
+ `admin.refundPurchase(accountId, purchaseId, {access: 'keep' | 'revoke', note})`. The
238
+ service computes the full remaining refundable amount. The explicit access policy controls
239
+ remaining credits and lifetime access; it does not reverse already consumed credits.
240
+
241
+ ## Complete billing page
242
+
243
+ `BillingPanel` builds on the same `billingRoutes` authorization checks as `BillingCard`:
244
+
245
+ ```tsx
246
+ import { BillingPanel } from '@hjam91/billing/react';
247
+
248
+ <BillingPanel
249
+ basePath="/api/billing"
250
+ locale="en-US"
251
+ onError={(error) => reportBillingError(error.code, error.status)}
252
+ />
253
+ ```
254
+
255
+ It includes plan and seat selection, a proration preview before confirmation, scheduled-change cancellation,
256
+ discount codes and eligible offers, credit balances and purchases, overage spending limits, and automatic top-up
257
+ settings. Automatic charges require the user's explicit checkbox consent. Plan changes use the subscription owned
258
+ by the current account; the app's `canManage` callback still guards every action. Multiple subscriptions get a
259
+ selector. `BillingCard` remains available for the compact status/portal experience.
260
+
261
+ Set `invoiceBilling` only for an app configured for invoice collection. This replaces the new-subscription Checkout
262
+ button with a billing-address form and **Request invoice**. Existing invoices show their due date and a hosted
263
+ payment link. Invoice collection, tax calculation and tax-ID collection are service policy; no Stripe secret belongs
264
+ in the browser.
265
+
266
+ For your own markup, `useBillingManagement()` exposes `previewPlan`, `previewQuantity`, `confirmChange`,
267
+ `cancelScheduledChange`, `checkDiscount`, `checkout`, `acceptOffer`, `purchaseCredits`, `saveUsageSettings`,
268
+ `requestInvoice`, and the current `plans`, `balances`, `offers`. Preserve the returned preview when confirming;
269
+ `confirmChange` sends its proration date and subscription selector. Errors retain `code`, `status` and `details`
270
+ through `BillingBrowserError` and the `onError` callback. All components are unstyled with `bk-` classes.
package/dist/admin.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * Every method throws BillingError on failure (nothing here fails open: these
14
14
  * are actions and owner reads, not entitlement checks).
15
15
  */
16
- import type { AccountStatus } from './types.js';
16
+ import type { AccountStatus, DiscountView, OfferAudience } from './types.js';
17
17
  export interface BillingAdminOptions {
18
18
  baseUrl: string;
19
19
  appId: string;
@@ -87,7 +87,125 @@ export interface AppHealth {
87
87
  last_delivery_at: string | null;
88
88
  webhook_url_set: boolean;
89
89
  }
90
+ /** A discount code as the owner sees it (since 0.8.0). */
91
+ export interface DiscountCodeAdminView extends DiscountView {
92
+ code: string;
93
+ /** null = every plan the app sells. */
94
+ plans: string[] | null;
95
+ max_redemptions: number | null;
96
+ times_redeemed: number;
97
+ first_time_only: boolean;
98
+ expires_at: string | null;
99
+ active: boolean;
100
+ note: string | null;
101
+ stripe_coupon_id: string;
102
+ stripe_promotion_code_id: string;
103
+ created_by: string | null;
104
+ created_at: string;
105
+ deactivated_at: string | null;
106
+ }
107
+ /** An offer as the owner sees it (since 0.8.0). */
108
+ export interface OfferAdminView {
109
+ id: string;
110
+ name: string;
111
+ audience: OfferAudience;
112
+ headline: string | null;
113
+ discount: DiscountView;
114
+ plans: string[] | null;
115
+ after_days: number;
116
+ within_days: number | null;
117
+ active: boolean;
118
+ redemptions: number;
119
+ stripe_coupon_id: string;
120
+ created_by: string | null;
121
+ created_at: string;
122
+ updated_at: string;
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
+ }
151
+ /** The money of a code or an offer: percentOff XOR amountOff + currency (minor units). */
152
+ interface DiscountTermsParams {
153
+ percentOff?: number;
154
+ amountOff?: number;
155
+ currency?: string;
156
+ /** Default 'once'. */
157
+ duration?: 'once' | 'repeating' | 'forever';
158
+ /** 1–36, with duration 'repeating'. */
159
+ durationInMonths?: number;
160
+ /** Plan names it applies to (default every plan the app sells). */
161
+ plans?: string[];
162
+ }
163
+ export interface CreateDiscountParams extends DiscountTermsParams {
164
+ /** What customers type: 3–40 of A-Z, 0-9 and '-' (stored upper-case; matched case-insensitively). */
165
+ code: string;
166
+ maxRedemptions?: number;
167
+ /** Only accounts that never had a subscription (Stripe also checks the customer's first transaction). */
168
+ firstTimeOnly?: boolean;
169
+ expiresAt?: string | Date;
170
+ note?: string;
171
+ }
172
+ export interface CreateOfferParams extends DiscountTermsParams {
173
+ name: string;
174
+ audience: OfferAudience;
175
+ /** Whole days since the event before it shows (default 0). */
176
+ afterDays?: number;
177
+ /** Last whole day since the event it shows (default: no end); at least afterDays. */
178
+ withinDays?: number | null;
179
+ /** A short marketing line (≤ 120 characters). */
180
+ headline?: string | null;
181
+ /** Default true. */
182
+ active?: boolean;
183
+ }
184
+ /** What PATCH may change on an offer: never its money (make a new offer for that). */
185
+ export interface OfferPatch {
186
+ active?: boolean;
187
+ headline?: string | null;
188
+ name?: string;
189
+ afterDays?: number;
190
+ withinDays?: number | null;
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
+ }
90
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>;
91
209
  /** The app's configuration (read). */
92
210
  app(): Promise<Record<string, unknown>>;
93
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. */
@@ -182,5 +300,36 @@ export interface BillingAdmin {
182
300
  }>;
183
301
  /** Refund one paid invoice; the service computes the amount (refund scope). */
184
302
  refund(accountId: string, params: RefundParams): Promise<RefundResult>;
303
+ /** Every discount code with its redemptions (read; since 0.8.0). */
304
+ discounts(): Promise<DiscountCodeAdminView[]>;
305
+ /**
306
+ * A code customers type: a Stripe coupon + promotion code (pricing scope; on an app billed through the service's own
307
+ * Stripe account only the service owner may). 409 code_exists. Since 0.8.0.
308
+ */
309
+ createDiscount(p: CreateDiscountParams): Promise<DiscountCodeAdminView>;
310
+ /** Stops a code (in Stripe, then here); it is never reused (pricing; since 0.8.0). */
311
+ deactivateDiscount(id: string): Promise<DiscountCodeAdminView>;
312
+ /** Every offer with its redemptions (read; since 0.8.0). */
313
+ offers(): Promise<OfferAdminView[]>;
314
+ /** An automatic offer: a Stripe coupon shown to an audience in a window (pricing; since 0.8.0). */
315
+ createOffer(p: CreateOfferParams): Promise<OfferAdminView>;
316
+ /** Switch an offer on / off, reword it or move its window — never its money (config; since 0.8.0). */
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>;
185
333
  }
186
334
  export declare function createBillingAdmin(opts: BillingAdminOptions): BillingAdmin;
335
+ export {};
package/dist/admin.js CHANGED
@@ -14,6 +14,14 @@
14
14
  * are actions and owner reads, not entitlement checks).
15
15
  */
16
16
  import { BillingError } from "./errors.js";
17
+ const termsBody = (p) => ({
18
+ ...(p.percentOff !== undefined ? { percent_off: p.percentOff } : {}),
19
+ ...(p.amountOff !== undefined ? { amount_off: p.amountOff } : {}),
20
+ ...(p.currency !== undefined ? { currency: p.currency } : {}),
21
+ ...(p.duration !== undefined ? { duration: p.duration } : {}),
22
+ ...(p.durationInMonths !== undefined ? { duration_in_months: p.durationInMonths } : {}),
23
+ ...(p.plans !== undefined ? { plans: p.plans } : {}),
24
+ });
17
25
  export function createBillingAdmin(opts) {
18
26
  const base = `${opts.baseUrl.replace(/\/+$/, '')}/admin/apps/${encodeURIComponent(opts.appId)}`;
19
27
  const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
@@ -75,6 +83,37 @@ export function createBillingAdmin(opts) {
75
83
  ...(p.coversAccountId ? { covers_account_id: p.coversAccountId } : {}),
76
84
  ...(p.all ? { all: true } : {}),
77
85
  }),
86
+ discounts: async () => (await call('GET', '/discounts')).discounts,
87
+ createDiscount: async (p) => (await call('POST', '/discounts', {
88
+ code: p.code,
89
+ ...termsBody(p),
90
+ ...(p.maxRedemptions !== undefined ? { max_redemptions: p.maxRedemptions } : {}),
91
+ ...(p.firstTimeOnly !== undefined ? { first_time_only: p.firstTimeOnly } : {}),
92
+ ...(p.expiresAt !== undefined ? { expires_at: p.expiresAt instanceof Date ? p.expiresAt.toISOString() : p.expiresAt } : {}),
93
+ ...(p.note !== undefined ? { note: p.note } : {}),
94
+ })).discount,
95
+ deactivateDiscount: async (id) => (await call('POST', `/discounts/${enc(id)}/deactivate`, {})).discount,
96
+ offers: async () => (await call('GET', '/offers')).offers,
97
+ createOffer: async (p) => (await call('POST', '/offers', {
98
+ name: p.name,
99
+ audience: p.audience,
100
+ ...termsBody(p),
101
+ ...(p.afterDays !== undefined ? { after_days: p.afterDays } : {}),
102
+ ...(p.withinDays !== undefined ? { within_days: p.withinDays } : {}),
103
+ ...(p.headline !== undefined ? { headline: p.headline } : {}),
104
+ ...(p.active !== undefined ? { active: p.active } : {}),
105
+ })).offer,
106
+ updateOffer: async (id, x) => (await call('PATCH', `/offers/${enc(id)}`, {
107
+ ...(x.active !== undefined ? { active: x.active } : {}),
108
+ ...(x.headline !== undefined ? { headline: x.headline } : {}),
109
+ ...(x.name !== undefined ? { name: x.name } : {}),
110
+ ...(x.afterDays !== undefined ? { after_days: x.afterDays } : {}),
111
+ ...(x.withinDays !== undefined ? { within_days: x.withinDays } : {}),
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),
78
117
  invoices: (accountId, o = {}) => call('GET', `/accounts/${enc(accountId)}/invoices${o.limit ? `?limit=${o.limit}` : ''}`),
79
118
  refund: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/refunds`, {
80
119
  invoice_id: p.invoiceId,
package/dist/config.d.ts CHANGED
@@ -60,6 +60,10 @@ export interface PlanSpec {
60
60
  items?: Record<string, ItemSpec>;
61
61
  }
62
62
  export interface BillingConfig {
63
+ automatic_tax?: boolean;
64
+ collect_tax_id?: boolean;
65
+ collection_method?: 'charge_automatically' | 'send_invoice';
66
+ days_until_due?: number;
63
67
  features?: Array<{
64
68
  id: string;
65
69
  name?: string;
package/dist/hono.d.ts CHANGED
@@ -76,7 +76,9 @@ export interface BillingRoutesOptions {
76
76
  *
77
77
  * GET / billing status for the signed-in user's account
78
78
  * GET /check?feature_id=…&required_balance=… may the signed-in user's account use a feature (0.5.0; read-only)
79
- * POST /:action checkout {plan, quantity?} | portal | autorenew {auto_renew} | trial
79
+ * GET /offers the offers the signed-in user's account may take now (0.8.0; read-only)
80
+ * POST /:action checkout {plan, quantity?, discount_code?, offer_id?} | portal | autorenew {auto_renew} | trial
81
+ * | discount {code, plan?} (check a typed code, 0.8.0) | accept-offer {offer_id} (a save offer, 0.8.0)
80
82
  * POST /webhook entitlement.changed from the billing service (signature-checked)
81
83
  *
82
84
  * The browser (sdk/react) calls these; the secret never leaves the server.
package/dist/hono.js CHANGED
@@ -92,7 +92,9 @@ export function requireFeature(billing, featureId, getAccountId, opts = {}) {
92
92
  *
93
93
  * GET / billing status for the signed-in user's account
94
94
  * GET /check?feature_id=…&required_balance=… may the signed-in user's account use a feature (0.5.0; read-only)
95
- * POST /:action checkout {plan, quantity?} | portal | autorenew {auto_renew} | trial
95
+ * GET /offers the offers the signed-in user's account may take now (0.8.0; read-only)
96
+ * POST /:action checkout {plan, quantity?, discount_code?, offer_id?} | portal | autorenew {auto_renew} | trial
97
+ * | discount {code, plan?} (check a typed code, 0.8.0) | accept-offer {offer_id} (a save offer, 0.8.0)
96
98
  * POST /webhook entitlement.changed from the billing service (signature-checked)
97
99
  *
98
100
  * The browser (sdk/react) calls these; the secret never leaves the server.
@@ -105,7 +107,9 @@ export function billingRoutes(billing, opts) {
105
107
  // Pass through the user-meaningful ones; anything else (incl. a 401 about
106
108
  // OUR app secret) is the backend's problem, not the browser's.
107
109
  const status = e.status === 400 || e.status === 404 || e.status === 409 ? e.status : 502;
108
- return c.json({ error: e.code ?? 'billing_error', message: e.message ?? 'Billing request failed' }, status);
110
+ // 0.8: a refused code says why (details.reason), so the page can tell the customer.
111
+ const reason = e.details?.reason;
112
+ return c.json({ error: e.code ?? 'billing_error', message: e.message ?? 'Billing request failed', ...(typeof reason === 'string' ? { reason } : {}) }, status);
109
113
  };
110
114
  // Registered before /:action so "webhook" is never treated as an action.
111
115
  r.post('/webhook', async (c) => {
@@ -167,15 +171,110 @@ export function billingRoutes(billing, opts) {
167
171
  ...(r.credit_feature_id ? { credit_feature_id: r.credit_feature_id, credit_rate: r.credit_rate } : {}),
168
172
  });
169
173
  });
174
+ // 0.8.0: the offers for the viewer's own account (read-only, like GET /).
175
+ r.get('/offers', async (c) => {
176
+ const accountId = await opts.getAccountId(c);
177
+ if (!accountId)
178
+ return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
179
+ try {
180
+ return c.json({ offers: await billing.offers(accountId) });
181
+ }
182
+ catch (err) {
183
+ return asError(c, err);
184
+ }
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
+ });
170
198
  r.post('/:action', async (c) => {
171
199
  const accountId = await opts.getAccountId(c);
172
200
  if (!accountId)
173
201
  return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
174
202
  if (!(await opts.canManage(c, accountId)))
175
203
  return c.json({ error: 'forbidden', message: 'You cannot manage billing for this account' }, 403);
176
- const body = (await c.req.json().catch(() => ({})));
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
+ };
177
228
  try {
178
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
+ }
179
278
  case 'checkout': {
180
279
  const plan = typeof body.plan === 'string' ? body.plan : '';
181
280
  if (!plan || (opts.plans && !opts.plans.includes(plan)))
@@ -183,9 +282,20 @@ export function billingRoutes(billing, opts) {
183
282
  const quantity = typeof body.quantity === 'number' ? body.quantity : undefined;
184
283
  const url = resolveReturn(c);
185
284
  const email = (await opts.getEmail?.(c)) ?? undefined;
186
- const res = await billing.checkout({ accountId, plan, quantity, successUrl: url, cancelUrl: url, email });
285
+ const str = (v) => (typeof v === 'string' && v ? v : undefined);
286
+ const res = await billing.checkout({ accountId, plan, quantity, successUrl: url, cancelUrl: url, email, discountCode: str(body.discount_code), offerId: str(body.offer_id) });
187
287
  return c.json({ url: res.url });
188
288
  }
289
+ case 'discount': {
290
+ if (typeof body.code !== 'string' || !body.code.trim())
291
+ return c.json({ error: 'invalid_field', message: 'code is required' }, 400);
292
+ const plan = typeof body.plan === 'string' && body.plan ? body.plan : undefined;
293
+ return c.json(await billing.checkDiscount(accountId, body.code, plan ? { plan } : {}));
294
+ }
295
+ case 'accept-offer':
296
+ if (typeof body.offer_id !== 'string' || !body.offer_id)
297
+ return c.json({ error: 'invalid_field', message: 'offer_id is required' }, 400);
298
+ return c.json({ ...(await billing.acceptOffer(accountId, body.offer_id)), viewer_can_manage: true });
189
299
  case 'portal':
190
300
  return c.json(await billing.portal({ accountId, returnUrl: resolveReturn(c) }));
191
301
  case 'trial': {
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 { AccountInput, AccountStatus, Balances, ChangePreview, CheckResult, EntitlementResult, Lock, PlanChange, PublicPlan, TrackResult, UpsertResult, UsageSettingsInput } from './types.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';
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 InvoiceView, 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;
@@ -142,6 +154,13 @@ export interface CheckoutParams {
142
154
  covers?: string | string[];
143
155
  /** A Stripe promotion code id (promo_…) to apply (since 0.4.0). */
144
156
  promotionCode?: string;
157
+ /**
158
+ * A code the customer typed (since 0.8.0): re-checked like checkDiscount for this plan, then applied. Refused with
159
+ * BillingError 409 `discount_invalid` (`details.reason`). At most one of discountCode, offerId, promotionCode.
160
+ */
161
+ discountCode?: string;
162
+ /** An offer from offers() (since 0.8.0), re-checked now; 409 `offer_not_eligible` otherwise. Not with `covers`. */
163
+ offerId?: string;
145
164
  /** The name on the payer's Stripe customer, shown on invoices and receipts (since 0.4.0). */
146
165
  customerName?: string;
147
166
  }
@@ -272,6 +291,10 @@ export interface Billing {
272
291
  dropped: number;
273
292
  pending: number;
274
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>;
275
298
  /** Every balance of the account, its grants, held locks, auto top-ups and spend cap. Throws BillingError. Since 0.6.0. */
276
299
  balances(accountId: string): Promise<Balances>;
277
300
  /**
@@ -307,6 +330,25 @@ export interface Billing {
307
330
  }>;
308
331
  /** What changePlan would cost: amount due now, the next invoice, the lines. Since 0.7.0. */
309
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
+ previewQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<ChangePreview>;
337
+ cancelScheduledChange(accountId: string, select?: Omit<SubscriptionSelector, 'all'>): Promise<AccountStatus>;
338
+ /** Create a subscription billed by invoice, when enabled in the app's billing policy. */
339
+ invoiceSubscription(accountId: string, plan: string, opts?: {
340
+ quantity?: number;
341
+ email?: string;
342
+ customerName?: string;
343
+ billingAddress?: BillingAddress;
344
+ }): Promise<AccountStatus & {
345
+ invoice: {
346
+ id: string | null;
347
+ status: string | null;
348
+ hosted_invoice_url: string | null;
349
+ due_at: string | null;
350
+ };
351
+ }>;
310
352
  /** Attaches an add-on plan (or sets its quantity) on the account's own subscription. Since 0.7.0. */
311
353
  attachAddOn(accountId: string, plan: string, opts?: {
312
354
  quantity?: number;
@@ -321,6 +363,22 @@ export interface Billing {
321
363
  trial_days?: number;
322
364
  trial_mode?: 'explicit' | 'on_first_seen';
323
365
  }>;
366
+ /**
367
+ * May the account use this code (for `plan`)? Since 0.8.0. Answers `{valid: true, discount, plans}` (each plan with
368
+ * its discounted first period) or `{valid: false, reason}`; matching is case-insensitive; nothing is stored. Throws
369
+ * BillingError only for a malformed request or an outage. Checkout re-checks the code (`discountCode`).
370
+ */
371
+ checkDiscount(accountId: string, code: string, opts?: {
372
+ plan?: string;
373
+ }): Promise<DiscountCheck>;
374
+ /** The automatic offers the account may take now (comeback, trial over, stay), with previews. Since 0.8.0. */
375
+ offers(accountId: string): Promise<OfferView[]>;
376
+ /**
377
+ * Takes a save offer (audience 'canceling'): the discount goes on the subscription the account OWNS and renewal is
378
+ * turned back on. Answers the account status; 409 `offer_not_eligible` otherwise. Since 0.8.0. The app decides who
379
+ * may do this (canManage).
380
+ */
381
+ acceptOffer(accountId: string, offerId: string): Promise<AccountStatus>;
324
382
  }
325
383
  /** Options of changePlan / previewChange (since 0.7.0). */
326
384
  export interface PlanChangeOptions {