@hjam91/billing 0.7.0 → 0.8.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 +42 -0
- package/dist/admin.d.ts +92 -1
- package/dist/admin.js +35 -0
- package/dist/hono.d.ts +3 -1
- package/dist/hono.js +30 -3
- package/dist/index.d.ts +27 -2
- package/dist/index.js +28 -2
- package/dist/types.d.ts +54 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,48 @@ 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
|
+
- `billingRoutes` (Hono) adds `GET /offers`, `POST /discount {code, plan?}`, `POST /accept-offer {offer_id}`, and
|
|
50
|
+
`discount_code` / `offer_id` on `POST /checkout`; a refused code answers its `reason`.
|
|
51
|
+
|
|
52
|
+
## 0.7.1 fixes
|
|
53
|
+
|
|
54
|
+
`plans()` can include the service's current `trial_days` and `trial_mode`, so apps
|
|
55
|
+
can display trial terms from their billing settings. These fields are optional
|
|
56
|
+
for compatibility with older services.
|
|
57
|
+
|
|
58
|
+
- Cached entitlement reads respect `maxStaleSeconds`, including ordinary reads without `fresh`.
|
|
59
|
+
- Feature checks clear cached access after authentication failures or a kill-switch denial, so later reads cannot restore the rejected access.
|
|
60
|
+
- Malformed successful entitlement/status responses become `BillingError(502, 'invalid_response')` and never replace a valid cached entitlement. Entitlement checks retain the configured outage policy.
|
|
61
|
+
|
|
62
|
+
No API migration is required. The default fail-open and kill-switch policies are unchanged.
|
|
63
|
+
|
|
22
64
|
## Quick start (server)
|
|
23
65
|
|
|
24
66
|
The client holds your app's secret: **server-side only**.
|
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,6 +87,81 @@ 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
|
+
/** The money of a code or an offer: percentOff XOR amountOff + currency (minor units). */
|
|
125
|
+
interface DiscountTermsParams {
|
|
126
|
+
percentOff?: number;
|
|
127
|
+
amountOff?: number;
|
|
128
|
+
currency?: string;
|
|
129
|
+
/** Default 'once'. */
|
|
130
|
+
duration?: 'once' | 'repeating' | 'forever';
|
|
131
|
+
/** 1–36, with duration 'repeating'. */
|
|
132
|
+
durationInMonths?: number;
|
|
133
|
+
/** Plan names it applies to (default every plan the app sells). */
|
|
134
|
+
plans?: string[];
|
|
135
|
+
}
|
|
136
|
+
export interface CreateDiscountParams extends DiscountTermsParams {
|
|
137
|
+
/** What customers type: 3–40 of A-Z, 0-9 and '-' (stored upper-case; matched case-insensitively). */
|
|
138
|
+
code: string;
|
|
139
|
+
maxRedemptions?: number;
|
|
140
|
+
/** Only accounts that never had a subscription (Stripe also checks the customer's first transaction). */
|
|
141
|
+
firstTimeOnly?: boolean;
|
|
142
|
+
expiresAt?: string | Date;
|
|
143
|
+
note?: string;
|
|
144
|
+
}
|
|
145
|
+
export interface CreateOfferParams extends DiscountTermsParams {
|
|
146
|
+
name: string;
|
|
147
|
+
audience: OfferAudience;
|
|
148
|
+
/** Whole days since the event before it shows (default 0). */
|
|
149
|
+
afterDays?: number;
|
|
150
|
+
/** Last whole day since the event it shows (default: no end); at least afterDays. */
|
|
151
|
+
withinDays?: number | null;
|
|
152
|
+
/** A short marketing line (≤ 120 characters). */
|
|
153
|
+
headline?: string | null;
|
|
154
|
+
/** Default true. */
|
|
155
|
+
active?: boolean;
|
|
156
|
+
}
|
|
157
|
+
/** What PATCH may change on an offer: never its money (make a new offer for that). */
|
|
158
|
+
export interface OfferPatch {
|
|
159
|
+
active?: boolean;
|
|
160
|
+
headline?: string | null;
|
|
161
|
+
name?: string;
|
|
162
|
+
afterDays?: number;
|
|
163
|
+
withinDays?: number | null;
|
|
164
|
+
}
|
|
90
165
|
export interface BillingAdmin {
|
|
91
166
|
/** The app's configuration (read). */
|
|
92
167
|
app(): Promise<Record<string, unknown>>;
|
|
@@ -182,5 +257,21 @@ export interface BillingAdmin {
|
|
|
182
257
|
}>;
|
|
183
258
|
/** Refund one paid invoice; the service computes the amount (refund scope). */
|
|
184
259
|
refund(accountId: string, params: RefundParams): Promise<RefundResult>;
|
|
260
|
+
/** Every discount code with its redemptions (read; since 0.8.0). */
|
|
261
|
+
discounts(): Promise<DiscountCodeAdminView[]>;
|
|
262
|
+
/**
|
|
263
|
+
* A code customers type: a Stripe coupon + promotion code (pricing scope; on an app billed through the service's own
|
|
264
|
+
* Stripe account only the service owner may). 409 code_exists. Since 0.8.0.
|
|
265
|
+
*/
|
|
266
|
+
createDiscount(p: CreateDiscountParams): Promise<DiscountCodeAdminView>;
|
|
267
|
+
/** Stops a code (in Stripe, then here); it is never reused (pricing; since 0.8.0). */
|
|
268
|
+
deactivateDiscount(id: string): Promise<DiscountCodeAdminView>;
|
|
269
|
+
/** Every offer with its redemptions (read; since 0.8.0). */
|
|
270
|
+
offers(): Promise<OfferAdminView[]>;
|
|
271
|
+
/** An automatic offer: a Stripe coupon shown to an audience in a window (pricing; since 0.8.0). */
|
|
272
|
+
createOffer(p: CreateOfferParams): Promise<OfferAdminView>;
|
|
273
|
+
/** Switch an offer on / off, reword it or move its window — never its money (config; since 0.8.0). */
|
|
274
|
+
updateOffer(id: string, patch: OfferPatch): Promise<OfferAdminView>;
|
|
185
275
|
}
|
|
186
276
|
export declare function createBillingAdmin(opts: BillingAdminOptions): BillingAdmin;
|
|
277
|
+
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,33 @@ 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,
|
|
78
113
|
invoices: (accountId, o = {}) => call('GET', `/accounts/${enc(accountId)}/invoices${o.limit ? `?limit=${o.limit}` : ''}`),
|
|
79
114
|
refund: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/refunds`, {
|
|
80
115
|
invoice_id: p.invoiceId,
|
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
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
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,6 +171,18 @@ 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
|
+
});
|
|
170
186
|
r.post('/:action', async (c) => {
|
|
171
187
|
const accountId = await opts.getAccountId(c);
|
|
172
188
|
if (!accountId)
|
|
@@ -183,9 +199,20 @@ export function billingRoutes(billing, opts) {
|
|
|
183
199
|
const quantity = typeof body.quantity === 'number' ? body.quantity : undefined;
|
|
184
200
|
const url = resolveReturn(c);
|
|
185
201
|
const email = (await opts.getEmail?.(c)) ?? undefined;
|
|
186
|
-
const
|
|
202
|
+
const str = (v) => (typeof v === 'string' && v ? v : undefined);
|
|
203
|
+
const res = await billing.checkout({ accountId, plan, quantity, successUrl: url, cancelUrl: url, email, discountCode: str(body.discount_code), offerId: str(body.offer_id) });
|
|
187
204
|
return c.json({ url: res.url });
|
|
188
205
|
}
|
|
206
|
+
case 'discount': {
|
|
207
|
+
if (typeof body.code !== 'string' || !body.code.trim())
|
|
208
|
+
return c.json({ error: 'invalid_field', message: 'code is required' }, 400);
|
|
209
|
+
const plan = typeof body.plan === 'string' && body.plan ? body.plan : undefined;
|
|
210
|
+
return c.json(await billing.checkDiscount(accountId, body.code, plan ? { plan } : {}));
|
|
211
|
+
}
|
|
212
|
+
case 'accept-offer':
|
|
213
|
+
if (typeof body.offer_id !== 'string' || !body.offer_id)
|
|
214
|
+
return c.json({ error: 'invalid_field', message: 'offer_id is required' }, 400);
|
|
215
|
+
return c.json({ ...(await billing.acceptOffer(accountId, body.offer_id)), viewer_can_manage: true });
|
|
189
216
|
case 'portal':
|
|
190
217
|
return c.json(await billing.portal({ accountId, returnUrl: resolveReturn(c) }));
|
|
191
218
|
case 'trial': {
|
package/dist/index.d.ts
CHANGED
|
@@ -27,11 +27,11 @@
|
|
|
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 { AccountInput, AccountStatus, Balances, ChangePreview, CheckResult, DiscountCheck, EntitlementResult, Lock, OfferView, PlanChange, PublicPlan, TrackResult, UpsertResult, UsageSettingsInput } from './types.js';
|
|
31
31
|
export * from './types.js';
|
|
32
32
|
export { BillingError, isOutage, killSignal } from './errors.js';
|
|
33
33
|
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';
|
|
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';
|
|
35
35
|
export { type CacheEntry, type CacheStore, memoryStore } from './cache.js';
|
|
36
36
|
export { BillingWebhookError, type BillingWebhookErrorCode, type VerifyOptions, verifyBillingEvent, verifyBillingWebhook } from './webhook.js';
|
|
37
37
|
/** What `onError` receives for every failed entitlement check. */
|
|
@@ -142,6 +142,13 @@ export interface CheckoutParams {
|
|
|
142
142
|
covers?: string | string[];
|
|
143
143
|
/** A Stripe promotion code id (promo_…) to apply (since 0.4.0). */
|
|
144
144
|
promotionCode?: string;
|
|
145
|
+
/**
|
|
146
|
+
* A code the customer typed (since 0.8.0): re-checked like checkDiscount for this plan, then applied. Refused with
|
|
147
|
+
* BillingError 409 `discount_invalid` (`details.reason`). At most one of discountCode, offerId, promotionCode.
|
|
148
|
+
*/
|
|
149
|
+
discountCode?: string;
|
|
150
|
+
/** An offer from offers() (since 0.8.0), re-checked now; 409 `offer_not_eligible` otherwise. Not with `covers`. */
|
|
151
|
+
offerId?: string;
|
|
145
152
|
/** The name on the payer's Stripe customer, shown on invoices and receipts (since 0.4.0). */
|
|
146
153
|
customerName?: string;
|
|
147
154
|
}
|
|
@@ -318,7 +325,25 @@ export interface Billing {
|
|
|
318
325
|
plans(): Promise<{
|
|
319
326
|
plans: PublicPlan[];
|
|
320
327
|
default_plan: string | null;
|
|
328
|
+
trial_days?: number;
|
|
329
|
+
trial_mode?: 'explicit' | 'on_first_seen';
|
|
321
330
|
}>;
|
|
331
|
+
/**
|
|
332
|
+
* May the account use this code (for `plan`)? Since 0.8.0. Answers `{valid: true, discount, plans}` (each plan with
|
|
333
|
+
* its discounted first period) or `{valid: false, reason}`; matching is case-insensitive; nothing is stored. Throws
|
|
334
|
+
* BillingError only for a malformed request or an outage. Checkout re-checks the code (`discountCode`).
|
|
335
|
+
*/
|
|
336
|
+
checkDiscount(accountId: string, code: string, opts?: {
|
|
337
|
+
plan?: string;
|
|
338
|
+
}): Promise<DiscountCheck>;
|
|
339
|
+
/** The automatic offers the account may take now (comeback, trial over, stay), with previews. Since 0.8.0. */
|
|
340
|
+
offers(accountId: string): Promise<OfferView[]>;
|
|
341
|
+
/**
|
|
342
|
+
* Takes a save offer (audience 'canceling'): the discount goes on the subscription the account OWNS and renewal is
|
|
343
|
+
* turned back on. Answers the account status; 409 `offer_not_eligible` otherwise. Since 0.8.0. The app decides who
|
|
344
|
+
* may do this (canManage).
|
|
345
|
+
*/
|
|
346
|
+
acceptOffer(accountId: string, offerId: string): Promise<AccountStatus>;
|
|
322
347
|
}
|
|
323
348
|
/** Options of changePlan / previewChange (since 0.7.0). */
|
|
324
349
|
export interface PlanChangeOptions {
|
package/dist/index.js
CHANGED
|
@@ -100,11 +100,19 @@ export function createBilling(opts) {
|
|
|
100
100
|
throw new BillingError(0, 'network_error', `Billing service unreachable: ${err?.message ?? err}`);
|
|
101
101
|
}
|
|
102
102
|
const data = (await res.json().catch(() => null));
|
|
103
|
-
if (!res.ok
|
|
103
|
+
if (!res.ok) {
|
|
104
104
|
throw new BillingError(res.status, data?.error ?? 'internal', data?.message ?? `Billing service answered HTTP ${res.status}`, (data ?? {}));
|
|
105
105
|
}
|
|
106
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
107
|
+
throw new BillingError(502, 'invalid_response', 'Billing service returned an invalid JSON object');
|
|
108
|
+
}
|
|
106
109
|
return data;
|
|
107
110
|
}
|
|
111
|
+
function validateEntitlement(value) {
|
|
112
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || typeof value.active !== 'boolean' || typeof value.reason !== 'string') {
|
|
113
|
+
throw new BillingError(502, 'invalid_response', 'Billing service returned an invalid entitlement');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
108
116
|
const enc = encodeURIComponent;
|
|
109
117
|
/** One network fetch per account at a time; concurrent callers share it. */
|
|
110
118
|
function refresh(accountId) {
|
|
@@ -113,6 +121,7 @@ export function createBilling(opts) {
|
|
|
113
121
|
return existing;
|
|
114
122
|
const p = call('GET', `/v1/accounts/${enc(accountId)}/entitlement`)
|
|
115
123
|
.then(async (value) => {
|
|
124
|
+
validateEntitlement(value);
|
|
116
125
|
await cache.set(key(accountId), { value, fetchedAt: now() }).catch((e) => log.warn('[billing] cache write failed', e));
|
|
117
126
|
return value;
|
|
118
127
|
})
|
|
@@ -288,10 +297,12 @@ export function createBilling(opts) {
|
|
|
288
297
|
const code = String(err?.code ?? 'error');
|
|
289
298
|
const kill = killSignal(err);
|
|
290
299
|
if (kill && killDeny) {
|
|
300
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
291
301
|
reportFailure(accountId, err, `DENY feature ${featureId}`, 'deny');
|
|
292
302
|
return unverifiedCheck(accountId, featureId, false, 'error', code);
|
|
293
303
|
}
|
|
294
304
|
if (!kill && !isOutage(err) && !failOpenOnAuth) {
|
|
305
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
295
306
|
reportFailure(accountId, err, `DENY for feature ${featureId} (misconfigured: auth/app/feature error is not an outage)`, 'deny');
|
|
296
307
|
return unverifiedCheck(accountId, featureId, false, 'error', code);
|
|
297
308
|
}
|
|
@@ -351,7 +362,7 @@ export function createBilling(opts) {
|
|
|
351
362
|
log.warn('[billing] cache read failed', e);
|
|
352
363
|
return undefined;
|
|
353
364
|
});
|
|
354
|
-
if (entry && !callOpts.fresh) {
|
|
365
|
+
if (entry && !callOpts.fresh && now() - entry.fetchedAt < maxStaleMs) {
|
|
355
366
|
if (now() - entry.fetchedAt < ttlMs)
|
|
356
367
|
return { ...entry.value, source: 'cache' };
|
|
357
368
|
// Stale-while-revalidate: answer now from the last known value, refresh behind it.
|
|
@@ -386,6 +397,8 @@ export function createBilling(opts) {
|
|
|
386
397
|
email: p.email,
|
|
387
398
|
covers: p.covers,
|
|
388
399
|
promotion_code: p.promotionCode,
|
|
400
|
+
discount_code: p.discountCode,
|
|
401
|
+
offer_id: p.offerId,
|
|
389
402
|
customer_name: p.customerName,
|
|
390
403
|
});
|
|
391
404
|
return {
|
|
@@ -434,6 +447,18 @@ export function createBilling(opts) {
|
|
|
434
447
|
return r;
|
|
435
448
|
},
|
|
436
449
|
plans: () => call('GET', '/v1/plans'),
|
|
450
|
+
checkDiscount: (accountId, code, o = {}) => call('POST', '/v1/discounts/check', { account_id: accountId, code, ...(o.plan ? { plan: o.plan } : {}) }),
|
|
451
|
+
async offers(accountId) {
|
|
452
|
+
const r = await call('GET', `/v1/accounts/${enc(accountId)}/offers`);
|
|
453
|
+
if (!Array.isArray(r.offers))
|
|
454
|
+
throw new BillingError(502, 'invalid_response', 'Billing service returned an invalid offer list');
|
|
455
|
+
return r.offers;
|
|
456
|
+
},
|
|
457
|
+
async acceptOffer(accountId, offerId) {
|
|
458
|
+
const s = await call('POST', `/v1/accounts/${enc(accountId)}/offers/${enc(offerId)}/accept`, {});
|
|
459
|
+
await cache.set(key(accountId), { value: { account_id: accountId, ...s.entitlement }, fetchedAt: now() }).catch(() => undefined);
|
|
460
|
+
return s;
|
|
461
|
+
},
|
|
437
462
|
async setUsageSettings(accountId, st) {
|
|
438
463
|
const body = {};
|
|
439
464
|
if (st.spendCap !== undefined)
|
|
@@ -538,6 +563,7 @@ export function createBilling(opts) {
|
|
|
538
563
|
},
|
|
539
564
|
async status(accountId, o = {}) {
|
|
540
565
|
const s = await call('GET', `/v1/accounts/${enc(accountId)}`, undefined, o.email ? { 'X-Billing-Email': o.email } : {});
|
|
566
|
+
validateEntitlement(s.entitlement);
|
|
541
567
|
await cache.set(key(accountId), { value: { account_id: accountId, ...s.entitlement }, fetchedAt: now() }).catch(() => undefined);
|
|
542
568
|
return s;
|
|
543
569
|
},
|
package/dist/types.d.ts
CHANGED
|
@@ -252,6 +252,57 @@ export interface PublicPlan {
|
|
|
252
252
|
expires_in_days?: number;
|
|
253
253
|
}>;
|
|
254
254
|
}
|
|
255
|
+
/** A discount as an app shows it (since 0.8.0). Amounts in minor units. */
|
|
256
|
+
export interface DiscountView {
|
|
257
|
+
id: string;
|
|
258
|
+
/** The code (discount codes only; an offer has none). */
|
|
259
|
+
code?: string;
|
|
260
|
+
percent_off: number | null;
|
|
261
|
+
amount_off: number | null;
|
|
262
|
+
currency: string | null;
|
|
263
|
+
duration: 'once' | 'repeating' | 'forever';
|
|
264
|
+
duration_in_months: number | null;
|
|
265
|
+
/** Ready to show: "50% off for 3 months", "$5.00 off once", "20% off forever". */
|
|
266
|
+
label: string;
|
|
267
|
+
}
|
|
268
|
+
/** One plan a discount applies to, with the discounted first paid period (since 0.8.0). Minor units. */
|
|
269
|
+
export interface DiscountPlanPreview {
|
|
270
|
+
plan: string;
|
|
271
|
+
amount: number;
|
|
272
|
+
currency: string;
|
|
273
|
+
interval: string | null;
|
|
274
|
+
interval_count: number | null;
|
|
275
|
+
/** The first paid period with the discount; never below 0. */
|
|
276
|
+
first_amount: number;
|
|
277
|
+
}
|
|
278
|
+
/** Why a code cannot be used (checkDiscount, and `details.reason` of a 409 discount_invalid at checkout). Since 0.8.0. */
|
|
279
|
+
export type DiscountReason = 'unknown' | 'inactive' | 'expired' | 'used_up' | 'not_first_time' | 'plan_not_eligible';
|
|
280
|
+
/** POST /v1/discounts/check (since 0.8.0). `code` is the normalized (upper-case) code. */
|
|
281
|
+
export type DiscountCheck = {
|
|
282
|
+
valid: true;
|
|
283
|
+
code: string;
|
|
284
|
+
discount: DiscountView;
|
|
285
|
+
plans: DiscountPlanPreview[];
|
|
286
|
+
} | {
|
|
287
|
+
valid: false;
|
|
288
|
+
code: string;
|
|
289
|
+
reason: DiscountReason;
|
|
290
|
+
};
|
|
291
|
+
/** Who an automatic offer is for (since 0.8.0). */
|
|
292
|
+
export type OfferAudience = 'trial_ended' | 'lapsed' | 'canceling';
|
|
293
|
+
/** An offer the account may take now (GET /v1/accounts/:id/offers, since 0.8.0). */
|
|
294
|
+
export interface OfferView {
|
|
295
|
+
id: string;
|
|
296
|
+
name: string;
|
|
297
|
+
audience: OfferAudience;
|
|
298
|
+
/** The owner's short marketing line (≤ 120 characters), or null. */
|
|
299
|
+
headline: string | null;
|
|
300
|
+
discount: DiscountView;
|
|
301
|
+
/** The plans it applies to with previews (a 'canceling' offer applies to the subscription the account has). */
|
|
302
|
+
plans: DiscountPlanPreview[];
|
|
303
|
+
/** When the offer stops being shown (ISO), null = no end. */
|
|
304
|
+
ends_at: string | null;
|
|
305
|
+
}
|
|
255
306
|
/**
|
|
256
307
|
* Where an answer came from:
|
|
257
308
|
* - live: fetched from the service just now
|
|
@@ -390,4 +441,6 @@ export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | '
|
|
|
390
441
|
/** 0.7 security: the service is locked down (only the owner key works). */
|
|
391
442
|
| 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
|
|
392
443
|
/** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
|
|
393
|
-
| 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type'
|
|
444
|
+
| 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type'
|
|
445
|
+
/** 0.8 discounts and offers. `discount_invalid` carries `details.reason` (a DiscountReason). */
|
|
446
|
+
| 'discount_invalid' | 'offer_not_eligible' | 'code_exists' | 'discount_not_found' | 'offer_not_found' | 'stripe_error' | 'internal' | 'network_error' | 'timeout' | (string & {});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hjam91/billing",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Zero-dependency client for a billing-kit service: cached, fail-open entitlement and feature checks, usage tracking, Stripe Checkout / portal, signed webhook verification, a Hono gate and an optional React billing card.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"billing",
|