@ultimabase/stripe 0.0.0-first.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 +7 -0
- package/dist/accounts.d.ts +9 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +20 -0
- package/dist/apply.d.ts +26 -0
- package/dist/apply.d.ts.map +1 -0
- package/dist/apply.js +73 -0
- package/dist/audit.d.ts +3 -0
- package/dist/audit.d.ts.map +1 -0
- package/dist/audit.js +123 -0
- package/dist/billing-gateway.d.ts +158 -0
- package/dist/billing-gateway.d.ts.map +1 -0
- package/dist/billing-gateway.js +23 -0
- package/dist/billing.d.ts +130 -0
- package/dist/billing.d.ts.map +1 -0
- package/dist/billing.js +128 -0
- package/dist/calls.d.ts +61 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/calls.js +172 -0
- package/dist/catalog.d.ts +54 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +182 -0
- package/dist/credit.d.ts +16 -0
- package/dist/credit.d.ts.map +1 -0
- package/dist/credit.js +18 -0
- package/dist/credits.d.ts +38 -0
- package/dist/credits.d.ts.map +1 -0
- package/dist/credits.js +138 -0
- package/dist/customer.d.ts +25 -0
- package/dist/customer.d.ts.map +1 -0
- package/dist/customer.js +88 -0
- package/dist/describe.d.ts +4 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +56 -0
- package/dist/duplicates.d.ts +12 -0
- package/dist/duplicates.d.ts.map +1 -0
- package/dist/duplicates.js +24 -0
- package/dist/fake-billing.d.ts +72 -0
- package/dist/fake-billing.d.ts.map +1 -0
- package/dist/fake-billing.js +290 -0
- package/dist/gateway.d.ts +108 -0
- package/dist/gateway.d.ts.map +1 -0
- package/dist/gateway.js +196 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/job-input.d.ts +6 -0
- package/dist/job-input.d.ts.map +1 -0
- package/dist/job-input.js +20 -0
- package/dist/jobs.d.ts +16 -0
- package/dist/jobs.d.ts.map +1 -0
- package/dist/jobs.js +189 -0
- package/dist/keys.d.ts +10 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +30 -0
- package/dist/kinds.d.ts +11 -0
- package/dist/kinds.d.ts.map +1 -0
- package/dist/kinds.js +4 -0
- package/dist/models.d.ts +71 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +41 -0
- package/dist/plugin.d.ts +41 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +229 -0
- package/dist/portal.d.ts +23 -0
- package/dist/portal.d.ts.map +1 -0
- package/dist/portal.js +66 -0
- package/dist/product.d.ts +57 -0
- package/dist/product.d.ts.map +1 -0
- package/dist/product.js +113 -0
- package/dist/running.d.ts +61 -0
- package/dist/running.d.ts.map +1 -0
- package/dist/running.js +35 -0
- package/dist/sdk-billing.d.ts +8 -0
- package/dist/sdk-billing.d.ts.map +1 -0
- package/dist/sdk-billing.js +200 -0
- package/dist/sdk-common.d.ts +13 -0
- package/dist/sdk-common.d.ts.map +1 -0
- package/dist/sdk-common.js +41 -0
- package/dist/sdk-customer.d.ts +9 -0
- package/dist/sdk-customer.d.ts.map +1 -0
- package/dist/sdk-customer.js +149 -0
- package/dist/sdk-invoices.d.ts +10 -0
- package/dist/sdk-invoices.d.ts.map +1 -0
- package/dist/sdk-invoices.js +53 -0
- package/dist/sdk-recovery.d.ts +5 -0
- package/dist/sdk-recovery.d.ts.map +1 -0
- package/dist/sdk-recovery.js +81 -0
- package/dist/sync.d.ts +8 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/sync.js +196 -0
- package/dist/testing.d.ts +24 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +100 -0
- package/dist/webhook.d.ts +4 -0
- package/dist/webhook.d.ts.map +1 -0
- package/dist/webhook.js +73 -0
- package/package.json +51 -0
- package/src/accounts.ts +30 -0
- package/src/apply.ts +99 -0
- package/src/audit.ts +171 -0
- package/src/billing-gateway.ts +188 -0
- package/src/billing.ts +361 -0
- package/src/calls.ts +280 -0
- package/src/catalog.ts +327 -0
- package/src/credit.ts +36 -0
- package/src/credits.ts +206 -0
- package/src/customer.ts +113 -0
- package/src/describe.ts +76 -0
- package/src/duplicates.ts +45 -0
- package/src/fake-billing.ts +388 -0
- package/src/gateway.ts +333 -0
- package/src/index.ts +35 -0
- package/src/job-input.ts +24 -0
- package/src/jobs.ts +230 -0
- package/src/keys.ts +40 -0
- package/src/kinds.ts +15 -0
- package/src/models.ts +107 -0
- package/src/plugin.ts +307 -0
- package/src/portal.ts +95 -0
- package/src/product.ts +203 -0
- package/src/running.ts +104 -0
- package/src/sdk-billing.ts +220 -0
- package/src/sdk-common.ts +57 -0
- package/src/sdk-customer.ts +203 -0
- package/src/sdk-invoices.ts +81 -0
- package/src/sdk-recovery.ts +93 -0
- package/src/sync.ts +246 -0
- package/src/testing.ts +135 -0
- package/src/webhook.ts +100 -0
package/src/product.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// `defineProduct` (D-372): what an application sells, either a subscription
|
|
2
|
+
// with its recurring prices or a one-time product with the credits it gives.
|
|
3
|
+
// The catalog writes it to Stripe; the product's key never changes.
|
|
4
|
+
import { Refused } from 'ultimabase'
|
|
5
|
+
import type { CreditAmount } from './credit.ts'
|
|
6
|
+
import { checkKey, ownKeys, whereOf } from './keys.ts'
|
|
7
|
+
|
|
8
|
+
/** How often a recurring price bills. */
|
|
9
|
+
export type Every = 'day' | 'week' | 'month' | 'year'
|
|
10
|
+
|
|
11
|
+
/** A subscription's price, billed every `everyCount` (1 by default) `every`. */
|
|
12
|
+
export interface RecurringPrice {
|
|
13
|
+
/** In the currency's smallest unit: `9_90` is 9.90 €. */
|
|
14
|
+
readonly amount: number
|
|
15
|
+
readonly every: Every
|
|
16
|
+
readonly everyCount?: number
|
|
17
|
+
/** The credits each paid period gives (D-377 point 4). */
|
|
18
|
+
readonly gives?: readonly CreditAmount[]
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A one-time product's price. */
|
|
22
|
+
export interface OneTimePrice {
|
|
23
|
+
/** In the currency's smallest unit. */
|
|
24
|
+
readonly amount: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A subscription, with its recurring prices by name. */
|
|
28
|
+
export interface SubscriptionProduct<
|
|
29
|
+
K extends string = string,
|
|
30
|
+
P extends string = string,
|
|
31
|
+
> {
|
|
32
|
+
/** The product's name in the application, never changed. */
|
|
33
|
+
readonly key: K
|
|
34
|
+
/** What Checkout and the invoices show. */
|
|
35
|
+
readonly name: string
|
|
36
|
+
/** Its Stripe Tax code, `txcd_…`. */
|
|
37
|
+
readonly taxCode?: string
|
|
38
|
+
readonly prices: { readonly [N in P]: RecurringPrice }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A product paid once, and the credits it gives. */
|
|
42
|
+
export interface OneTimeProduct<K extends string = string> {
|
|
43
|
+
readonly key: K
|
|
44
|
+
readonly name: string
|
|
45
|
+
readonly taxCode?: string
|
|
46
|
+
readonly price: OneTimePrice
|
|
47
|
+
readonly gives: readonly CreditAmount[]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A product of the catalog. */
|
|
51
|
+
export type Product = SubscriptionProduct | OneTimeProduct
|
|
52
|
+
|
|
53
|
+
/** Stripe bills at most every three years. */
|
|
54
|
+
const longest: Readonly<Record<Every, number>> = {
|
|
55
|
+
day: 1095,
|
|
56
|
+
week: 156,
|
|
57
|
+
month: 36,
|
|
58
|
+
year: 3,
|
|
59
|
+
}
|
|
60
|
+
const productKeys = ['key', 'name', 'taxCode', 'prices', 'price', 'gives']
|
|
61
|
+
|
|
62
|
+
/** Refuses an amount that is not a positive integer. */
|
|
63
|
+
function checkAmount(where: string, amount: unknown): void {
|
|
64
|
+
if (!Number.isSafeInteger(amount) || Number(amount) <= 0) {
|
|
65
|
+
throw new Refused(
|
|
66
|
+
`${where}: the amount ${String(amount)} is not a positive integer, in the currency's smallest unit.`,
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Refuses a recurring price Stripe would refuse; returns its interval. */
|
|
72
|
+
function checkRecurring(where: string, price: unknown): string {
|
|
73
|
+
ownKeys(where, price, ['amount', 'every', 'everyCount', 'gives'])
|
|
74
|
+
checkAmount(where, Reflect.get(price, 'amount'))
|
|
75
|
+
checkGives(where, Reflect.get(price, 'gives') ?? [])
|
|
76
|
+
const every: unknown = Reflect.get(price, 'every')
|
|
77
|
+
const most = Object.entries(longest).find(([name]) => name === every)?.[1]
|
|
78
|
+
if (most === undefined) {
|
|
79
|
+
throw new Refused(`${where}: every is 'day', 'week', 'month' or 'year'.`)
|
|
80
|
+
}
|
|
81
|
+
const count: unknown = Reflect.get(price, 'everyCount') ?? 1
|
|
82
|
+
if (
|
|
83
|
+
!Number.isSafeInteger(count) ||
|
|
84
|
+
Number(count) < 1 ||
|
|
85
|
+
Number(count) > most
|
|
86
|
+
) {
|
|
87
|
+
throw new Refused(
|
|
88
|
+
`${where}: everyCount is an integer from 1 to ${String(most)}.`,
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
return `${String(count)} ${String(every)}`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Refuses a subscription's prices: none, a bad one, or two of one interval. */
|
|
95
|
+
function checkPrices(where: string, prices: unknown): void {
|
|
96
|
+
if (typeof prices !== 'object' || prices === null) {
|
|
97
|
+
throw new Refused(`${where}: prices holds the recurring prices by name.`)
|
|
98
|
+
}
|
|
99
|
+
const names = Object.keys(prices)
|
|
100
|
+
if (names.length === 0) {
|
|
101
|
+
throw new Refused(`${where}: prices holds at least one price.`)
|
|
102
|
+
}
|
|
103
|
+
// The customer portal takes one price per interval of a product.
|
|
104
|
+
const intervals = new Map<string, string>()
|
|
105
|
+
for (const name of names) {
|
|
106
|
+
checkKey(where, name)
|
|
107
|
+
const price: unknown = Reflect.get(prices, name)
|
|
108
|
+
const interval = checkRecurring(`${where}.${name}`, price)
|
|
109
|
+
const other = intervals.get(interval)
|
|
110
|
+
if (other !== undefined) {
|
|
111
|
+
throw new Refused(
|
|
112
|
+
`${where}: ${other} and ${name} both bill every ${interval}; a product has one price per interval.`,
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
intervals.set(interval, name)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Refuses what a one-time product gives: one credit twice, or a bad one. */
|
|
120
|
+
function checkGives(where: string, gives: unknown): void {
|
|
121
|
+
if (!Array.isArray(gives)) {
|
|
122
|
+
throw new Refused(`${where}: gives lists credits, as [blueGems(500)].`)
|
|
123
|
+
}
|
|
124
|
+
const given = new Set<unknown>()
|
|
125
|
+
for (const item of gives) {
|
|
126
|
+
const credit: unknown =
|
|
127
|
+
typeof item === 'object' && item !== null
|
|
128
|
+
? Reflect.get(item, 'credit')
|
|
129
|
+
: undefined
|
|
130
|
+
if (typeof credit !== 'string') {
|
|
131
|
+
throw new Refused(`${where}: gives lists credits, as [blueGems(500)].`)
|
|
132
|
+
}
|
|
133
|
+
checkAmount(`${where} gives ${credit}`, Reflect.get(Object(item), 'amount'))
|
|
134
|
+
if (given.has(credit)) {
|
|
135
|
+
throw new Refused(`${where}: gives ${credit} twice.`)
|
|
136
|
+
}
|
|
137
|
+
given.add(credit)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** A subscription and its recurring prices (D-372). */
|
|
142
|
+
export function defineProduct<
|
|
143
|
+
const K extends string,
|
|
144
|
+
const P extends string,
|
|
145
|
+
>(definition: {
|
|
146
|
+
readonly key: K
|
|
147
|
+
readonly name: string
|
|
148
|
+
readonly taxCode?: string
|
|
149
|
+
readonly prices: { readonly [N in P]: RecurringPrice }
|
|
150
|
+
}): SubscriptionProduct<K, P>
|
|
151
|
+
/** A product paid once, and the credits it gives (D-372). */
|
|
152
|
+
export function defineProduct<const K extends string>(definition: {
|
|
153
|
+
readonly key: K
|
|
154
|
+
readonly name: string
|
|
155
|
+
readonly taxCode?: string
|
|
156
|
+
readonly price: OneTimePrice
|
|
157
|
+
readonly gives?: readonly CreditAmount[]
|
|
158
|
+
}): OneTimeProduct<K>
|
|
159
|
+
export function defineProduct(definition: {
|
|
160
|
+
readonly key: string
|
|
161
|
+
readonly name: string
|
|
162
|
+
readonly taxCode?: string
|
|
163
|
+
readonly prices?: Readonly<Record<string, RecurringPrice>>
|
|
164
|
+
readonly price?: OneTimePrice
|
|
165
|
+
readonly gives?: readonly CreditAmount[]
|
|
166
|
+
}): Product {
|
|
167
|
+
ownKeys('defineProduct', definition, productKeys)
|
|
168
|
+
checkKey('defineProduct', definition.key)
|
|
169
|
+
const where = whereOf('defineProduct', definition)
|
|
170
|
+
const { key, name, taxCode, prices, price } = definition
|
|
171
|
+
if (typeof name !== 'string' || name.trim() === '') {
|
|
172
|
+
throw new Refused(`${where}: name is what Checkout and the invoices show.`)
|
|
173
|
+
}
|
|
174
|
+
if (taxCode !== undefined && typeof taxCode !== 'string') {
|
|
175
|
+
throw new Refused(
|
|
176
|
+
`${where}: taxCode is a Stripe Tax code, as txcd_10000000.`,
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
const tax = taxCode === undefined ? {} : { taxCode }
|
|
180
|
+
if ((prices === undefined) === (price === undefined)) {
|
|
181
|
+
throw new Refused(
|
|
182
|
+
`${where}: a product has either prices, recurring, or one price, paid once.`,
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
if (price === undefined) {
|
|
186
|
+
if (definition.gives !== undefined) {
|
|
187
|
+
throw new Refused(`${where}: gives goes with a one-time price.`)
|
|
188
|
+
}
|
|
189
|
+
checkPrices(where, prices)
|
|
190
|
+
return Object.freeze({ key, name, ...tax, prices: { ...prices } })
|
|
191
|
+
}
|
|
192
|
+
ownKeys(where, price, ['amount'])
|
|
193
|
+
checkAmount(where, price.amount)
|
|
194
|
+
const gives = definition.gives ?? []
|
|
195
|
+
checkGives(where, gives)
|
|
196
|
+
return Object.freeze({
|
|
197
|
+
key,
|
|
198
|
+
name,
|
|
199
|
+
...tax,
|
|
200
|
+
price: { amount: price.amount },
|
|
201
|
+
gives: [...gives],
|
|
202
|
+
})
|
|
203
|
+
}
|
package/src/running.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// The running plugin's state, which its server calls and jobs read: one
|
|
2
|
+
// application runs at a time in a realm.
|
|
3
|
+
import type { Stripe } from 'stripe'
|
|
4
|
+
import type { Logger, QueryOptions } from 'ultimabase'
|
|
5
|
+
import type { Gateway } from './accounts.ts'
|
|
6
|
+
import type { CustomerProfile } from './billing-gateway.ts'
|
|
7
|
+
import { unavailable } from './billing-gateway.ts'
|
|
8
|
+
import type { Catalog } from './catalog.ts'
|
|
9
|
+
import type { Product } from './product.ts'
|
|
10
|
+
|
|
11
|
+
/** A row as the plugin reads it, from a model it does not type. */
|
|
12
|
+
export type Row = { readonly id: string; readonly [field: string]: unknown }
|
|
13
|
+
|
|
14
|
+
/** The queries the plugin sends to the application's models. */
|
|
15
|
+
export interface Rows {
|
|
16
|
+
findUnique(args: object, options: QueryOptions): Promise<Row | null>
|
|
17
|
+
findMany(args: object, options: QueryOptions): Promise<readonly Row[]>
|
|
18
|
+
create(args: object, options: QueryOptions): Promise<Row>
|
|
19
|
+
update(args: object, options: QueryOptions): Promise<Row>
|
|
20
|
+
upsert(args: object, options: QueryOptions): Promise<Row>
|
|
21
|
+
updateManyAndReturn(
|
|
22
|
+
args: object,
|
|
23
|
+
options: QueryOptions,
|
|
24
|
+
): Promise<readonly Row[]>
|
|
25
|
+
groupBy(
|
|
26
|
+
args: object,
|
|
27
|
+
options: QueryOptions,
|
|
28
|
+
): Promise<readonly Readonly<Record<string, unknown>>[]>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const methods = [
|
|
32
|
+
'findUnique',
|
|
33
|
+
'findMany',
|
|
34
|
+
'create',
|
|
35
|
+
'update',
|
|
36
|
+
'upsert',
|
|
37
|
+
'updateManyAndReturn',
|
|
38
|
+
'groupBy',
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
const isRows = (queries: object): queries is Rows =>
|
|
42
|
+
methods.every((name) => typeof Reflect.get(queries, name) === 'function')
|
|
43
|
+
|
|
44
|
+
/** A model's queries, as the plugin sends them. */
|
|
45
|
+
export function rowsOf(queries: object): Rows {
|
|
46
|
+
if (isRows(queries)) return queries
|
|
47
|
+
throw new TypeError('A model’s queries were expected.')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A model the plugin writes, with its payer's model. */
|
|
51
|
+
export interface Billing {
|
|
52
|
+
readonly name: string
|
|
53
|
+
readonly queries: Rows
|
|
54
|
+
/** The payer's or owner's model: its name and queries. */
|
|
55
|
+
readonly payer: { readonly name: string; readonly queries: Rows }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** What the plugin holds while the application runs. */
|
|
59
|
+
export interface Running {
|
|
60
|
+
/** `undefined` without keys: every call throws `PAYMENT_UNAVAILABLE`. */
|
|
61
|
+
readonly stripe:
|
|
62
|
+
| {
|
|
63
|
+
readonly gateway: Gateway
|
|
64
|
+
/** Verifies the webhook's events; it reaches no network. */
|
|
65
|
+
readonly client: Stripe
|
|
66
|
+
readonly webhook: string
|
|
67
|
+
readonly live: boolean
|
|
68
|
+
}
|
|
69
|
+
| undefined
|
|
70
|
+
readonly catalog: Catalog
|
|
71
|
+
readonly products: ReadonlyMap<string, Product>
|
|
72
|
+
readonly customer: ((payer: never) => CustomerProfile) | undefined
|
|
73
|
+
readonly oneSubscription: boolean
|
|
74
|
+
readonly subscription: Billing | undefined
|
|
75
|
+
readonly purchase: Billing | undefined
|
|
76
|
+
readonly balance: Billing | undefined
|
|
77
|
+
readonly history: Billing | undefined
|
|
78
|
+
readonly logger: Logger
|
|
79
|
+
/** The managed portal configuration's id, once read. */
|
|
80
|
+
portal: string | null | undefined
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let running: Running | undefined
|
|
84
|
+
|
|
85
|
+
export const useRunning = (state: Running | undefined): void => {
|
|
86
|
+
running = state
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The running plugin; a call before the application starts is a bug. */
|
|
90
|
+
export function runningOf(entry: string): Running {
|
|
91
|
+
if (running === undefined) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`${entry} runs while an application with stripePlugin() runs.`,
|
|
94
|
+
)
|
|
95
|
+
}
|
|
96
|
+
return running
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The gateway, or `PAYMENT_UNAVAILABLE` without keys (D-371). */
|
|
100
|
+
export function stripeOf(entry: string): NonNullable<Running['stripe']> {
|
|
101
|
+
const { stripe } = runningOf(entry)
|
|
102
|
+
if (stripe === undefined) throw unavailable()
|
|
103
|
+
return stripe
|
|
104
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// The billing gateway over Stripe's API: what `gatewayOf` gives a real
|
|
2
|
+
// secret key. Stripe's errors become the plugin's: `PAYMENT_UNAVAILABLE`
|
|
3
|
+
// when Stripe cannot answer, `Missing` for an object it does not hold.
|
|
4
|
+
import type { Stripe } from 'stripe'
|
|
5
|
+
import type {
|
|
6
|
+
BillingGateway,
|
|
7
|
+
CustomerProfile,
|
|
8
|
+
PortalFlow,
|
|
9
|
+
} from './billing-gateway.ts'
|
|
10
|
+
import { Missing } from './billing-gateway.ts'
|
|
11
|
+
import { managedBy } from './gateway.ts'
|
|
12
|
+
import type { Ref } from './sdk-common.ts'
|
|
13
|
+
import { all, guarded, refOf } from './sdk-common.ts'
|
|
14
|
+
import { gone, stateOf } from './sdk-customer.ts'
|
|
15
|
+
const profileParams = (profile: CustomerProfile) => ({
|
|
16
|
+
...(profile.email != null && { email: profile.email }),
|
|
17
|
+
...(profile.name != null && { name: profile.name }),
|
|
18
|
+
...(profile.locale != null && { preferred_locales: [profile.locale] }),
|
|
19
|
+
})
|
|
20
|
+
/** The customer an object belongs to, read from Stripe. */
|
|
21
|
+
export async function ownerOf(
|
|
22
|
+
client: Stripe,
|
|
23
|
+
type: string,
|
|
24
|
+
id: string,
|
|
25
|
+
): Promise<Ref> {
|
|
26
|
+
switch (type) {
|
|
27
|
+
case 'customer':
|
|
28
|
+
return id
|
|
29
|
+
case 'checkout.session':
|
|
30
|
+
return (await client.checkout.sessions.retrieve(id)).customer
|
|
31
|
+
case 'subscription':
|
|
32
|
+
return (await client.subscriptions.retrieve(id)).customer
|
|
33
|
+
case 'subscription_schedule':
|
|
34
|
+
return (await client.subscriptionSchedules.retrieve(id)).customer
|
|
35
|
+
case 'invoice':
|
|
36
|
+
return (await client.invoices.retrieve(id)).customer
|
|
37
|
+
case 'payment_intent':
|
|
38
|
+
return (await client.paymentIntents.retrieve(id)).customer
|
|
39
|
+
case 'charge':
|
|
40
|
+
return (await client.charges.retrieve(id)).customer
|
|
41
|
+
case 'dispute': {
|
|
42
|
+
const { charge } = await client.disputes.retrieve(id)
|
|
43
|
+
const chargeId = refOf(charge)
|
|
44
|
+
return chargeId === null
|
|
45
|
+
? null
|
|
46
|
+
: (await client.charges.retrieve(chargeId)).customer
|
|
47
|
+
}
|
|
48
|
+
default:
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The active price of a lookup key, or a bug: the catalog was not applied. */
|
|
54
|
+
async function priceId(client: Stripe, lookupKey: string): Promise<string> {
|
|
55
|
+
const listed = await client.prices.list({
|
|
56
|
+
lookup_keys: [lookupKey],
|
|
57
|
+
active: true,
|
|
58
|
+
limit: 1,
|
|
59
|
+
})
|
|
60
|
+
const [price] = listed.data
|
|
61
|
+
if (price === undefined) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`Stripe holds no active price ${lookupKey}: apply the catalog.`,
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
return price.id
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function flowOf(
|
|
70
|
+
client: Stripe,
|
|
71
|
+
flow: PortalFlow,
|
|
72
|
+
returnUrl: string,
|
|
73
|
+
): Promise<Stripe.BillingPortal.SessionCreateParams.FlowData | undefined> {
|
|
74
|
+
const after = {
|
|
75
|
+
type: 'redirect' as const,
|
|
76
|
+
redirect: { return_url: returnUrl },
|
|
77
|
+
}
|
|
78
|
+
if (flow.kind === 'cancel') {
|
|
79
|
+
return {
|
|
80
|
+
type: 'subscription_cancel',
|
|
81
|
+
subscription_cancel: { subscription: flow.subscriptionId },
|
|
82
|
+
after_completion: after,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (flow.kind === 'home') return undefined
|
|
86
|
+
const subscription = await client.subscriptions.retrieve(flow.subscriptionId)
|
|
87
|
+
const [item] = subscription.items.data
|
|
88
|
+
if (item === undefined) throw new Error('The subscription has no item.')
|
|
89
|
+
// The quantity is kept (D-373 point 8).
|
|
90
|
+
const price = await priceId(client, flow.lookupKey)
|
|
91
|
+
return {
|
|
92
|
+
type: 'subscription_update_confirm',
|
|
93
|
+
subscription_update_confirm: {
|
|
94
|
+
subscription: flow.subscriptionId,
|
|
95
|
+
items: [{ id: item.id, price, quantity: item.quantity ?? 1 }],
|
|
96
|
+
},
|
|
97
|
+
after_completion: after,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** The billing gateway over Stripe's API. */
|
|
101
|
+
export const sdkBilling = (client: Stripe): BillingGateway => ({
|
|
102
|
+
createCustomer: async (profile, idempotencyKey) =>
|
|
103
|
+
guarded('customer', async () => {
|
|
104
|
+
const params = { ...profileParams(profile), metadata: { managedBy } }
|
|
105
|
+
const created = await client.customers.create(params, {
|
|
106
|
+
idempotencyKey,
|
|
107
|
+
})
|
|
108
|
+
return created.id
|
|
109
|
+
}),
|
|
110
|
+
updateCustomer: async (id, profile) =>
|
|
111
|
+
guarded(id, async () => {
|
|
112
|
+
await client.customers.update(id, profileParams(profile))
|
|
113
|
+
}),
|
|
114
|
+
deleteCustomer: async (id) => {
|
|
115
|
+
try {
|
|
116
|
+
await guarded(id, async () => client.customers.del(id))
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (!(error instanceof Missing)) throw error
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
readCustomer: async (id, options) => {
|
|
122
|
+
try {
|
|
123
|
+
const asked = {
|
|
124
|
+
invoices: options?.invoices ?? false,
|
|
125
|
+
free: options?.free ?? false,
|
|
126
|
+
}
|
|
127
|
+
return await guarded(id, async () => stateOf(client, id, asked))
|
|
128
|
+
} catch (error) {
|
|
129
|
+
if (error instanceof Missing) return gone
|
|
130
|
+
throw error
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
customerOf: async (type, id) => {
|
|
134
|
+
try {
|
|
135
|
+
return refOf(await guarded(id, async () => ownerOf(client, type, id)))
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (error instanceof Missing) return null
|
|
138
|
+
throw error
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
openCheckout: async (checkout) =>
|
|
142
|
+
guarded(checkout.customerId, async () => {
|
|
143
|
+
const price = await priceId(client, checkout.lookupKey)
|
|
144
|
+
const metadata = {
|
|
145
|
+
...checkout.metadata,
|
|
146
|
+
managedBy,
|
|
147
|
+
product: checkout.product,
|
|
148
|
+
// A purchase keeps its quantity: its credits are so many times.
|
|
149
|
+
...(checkout.mode === 'payment' && {
|
|
150
|
+
quantity: String(checkout.quantity),
|
|
151
|
+
}),
|
|
152
|
+
}
|
|
153
|
+
const session = await client.checkout.sessions.create({
|
|
154
|
+
mode: checkout.mode,
|
|
155
|
+
customer: checkout.customerId,
|
|
156
|
+
client_reference_id: checkout.reference,
|
|
157
|
+
line_items: [{ price, quantity: checkout.quantity }],
|
|
158
|
+
success_url: checkout.successUrl,
|
|
159
|
+
cancel_url: checkout.cancelUrl,
|
|
160
|
+
metadata,
|
|
161
|
+
...(checkout.terms && {
|
|
162
|
+
consent_collection: { terms_of_service: 'required' },
|
|
163
|
+
}),
|
|
164
|
+
...(checkout.promotionCodes && { allow_promotion_codes: true }),
|
|
165
|
+
...(checkout.mode === 'subscription'
|
|
166
|
+
? {
|
|
167
|
+
subscription_data: {
|
|
168
|
+
metadata,
|
|
169
|
+
...(checkout.trialDays !== null && {
|
|
170
|
+
trial_period_days: checkout.trialDays,
|
|
171
|
+
}),
|
|
172
|
+
},
|
|
173
|
+
}
|
|
174
|
+
: { payment_intent_data: { metadata } }),
|
|
175
|
+
})
|
|
176
|
+
if (session.url === null) throw new Error('Checkout gave no URL.')
|
|
177
|
+
return session.url
|
|
178
|
+
}),
|
|
179
|
+
expireCheckouts: async (customerId) =>
|
|
180
|
+
guarded(customerId, async () => {
|
|
181
|
+
const open = await all(
|
|
182
|
+
client.checkout.sessions.list({
|
|
183
|
+
customer: customerId,
|
|
184
|
+
status: 'open',
|
|
185
|
+
limit: 100,
|
|
186
|
+
}),
|
|
187
|
+
)
|
|
188
|
+
for (const { id } of open) await client.checkout.sessions.expire(id)
|
|
189
|
+
}),
|
|
190
|
+
checkoutCustomer: async (id) => {
|
|
191
|
+
try {
|
|
192
|
+
const session = await guarded(id, async () =>
|
|
193
|
+
client.checkout.sessions.retrieve(id),
|
|
194
|
+
)
|
|
195
|
+
return refOf(session.customer)
|
|
196
|
+
} catch (error) {
|
|
197
|
+
if (error instanceof Missing) return null
|
|
198
|
+
throw error
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
openPortal: async ({ customerId, configuration, returnUrl, flow }) =>
|
|
202
|
+
guarded(customerId, async () => {
|
|
203
|
+
const flowData = await flowOf(client, flow, returnUrl)
|
|
204
|
+
const session = await client.billingPortal.sessions.create({
|
|
205
|
+
customer: customerId,
|
|
206
|
+
return_url: returnUrl,
|
|
207
|
+
...(configuration !== null && { configuration }),
|
|
208
|
+
...(flowData !== undefined && { flow_data: flowData }),
|
|
209
|
+
})
|
|
210
|
+
return session.url
|
|
211
|
+
}),
|
|
212
|
+
// The customer first: a failure between the two leaves both cards set.
|
|
213
|
+
moveCard: async ({ id, customerId, card }) =>
|
|
214
|
+
guarded(id, async () => {
|
|
215
|
+
await client.customers.update(customerId, {
|
|
216
|
+
invoice_settings: { default_payment_method: card },
|
|
217
|
+
})
|
|
218
|
+
await client.subscriptions.update(id, { default_payment_method: '' })
|
|
219
|
+
}),
|
|
220
|
+
})
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// What the gateways over Stripe's API share: Stripe's errors as the
|
|
2
|
+
// plugin's, lists read whole, and the keys a price's metadata holds.
|
|
3
|
+
import { Stripe } from 'stripe'
|
|
4
|
+
import type { PriceKeys } from './billing-gateway.ts'
|
|
5
|
+
import { Missing, unavailable } from './billing-gateway.ts'
|
|
6
|
+
|
|
7
|
+
/** Stripe's errors, as the plugin's: unavailable, missing, or a bug. */
|
|
8
|
+
const translated = (error: unknown, id: string): unknown => {
|
|
9
|
+
if (
|
|
10
|
+
error instanceof Stripe.errors.StripeConnectionError ||
|
|
11
|
+
error instanceof Stripe.errors.StripeAPIError ||
|
|
12
|
+
error instanceof Stripe.errors.StripeRateLimitError
|
|
13
|
+
) {
|
|
14
|
+
return unavailable(error)
|
|
15
|
+
}
|
|
16
|
+
if (
|
|
17
|
+
error instanceof Stripe.errors.StripeInvalidRequestError &&
|
|
18
|
+
error.code === 'resource_missing'
|
|
19
|
+
) {
|
|
20
|
+
return new Missing(id)
|
|
21
|
+
}
|
|
22
|
+
return error
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const guarded = async <T>(
|
|
26
|
+
id: string,
|
|
27
|
+
run: () => Promise<T>,
|
|
28
|
+
): Promise<T> => {
|
|
29
|
+
try {
|
|
30
|
+
return await run()
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw translated(error, id)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Every item of a list, past its pages: no cap drops one. */
|
|
37
|
+
export const all = async <T>(list: AsyncIterable<T>): Promise<T[]> => {
|
|
38
|
+
const items: T[] = []
|
|
39
|
+
for await (const item of list) items.push(item)
|
|
40
|
+
return items
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type Ref = string | { readonly id: string } | null
|
|
44
|
+
export const refOf = (value: Ref): string | null =>
|
|
45
|
+
value === null || typeof value === 'string' ? value : value.id
|
|
46
|
+
|
|
47
|
+
export const dateOf = (seconds: number): Date => new Date(seconds * 1000)
|
|
48
|
+
export const maybeDate = (seconds: number | null): Date | null =>
|
|
49
|
+
seconds === null ? null : dateOf(seconds)
|
|
50
|
+
|
|
51
|
+
export const keysOf = (price: Stripe.Price | Stripe.DeletedPrice): PriceKeys =>
|
|
52
|
+
'metadata' in price
|
|
53
|
+
? {
|
|
54
|
+
product: price.metadata['product'] ?? null,
|
|
55
|
+
price: price.metadata['price'] ?? null,
|
|
56
|
+
}
|
|
57
|
+
: { product: null, price: null }
|