@yaks/stripe 0.0.0-stage → 0.2.36

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/shops.ts ADDED
@@ -0,0 +1,820 @@
1
+ // What Stripe lends a party selling on an account of its own, as @yaks/host's
2
+ // `Shops`: a Connect account opened once, finished through Stripe's hosted
3
+ // onboarding, Checkout Sessions on it that the platform takes an application
4
+ // fee from, in payment mode or in subscription mode, the subscriptions those
5
+ // start, read and cancelled at their period's end, and the events Stripe
6
+ // posts about it read into the host's words (`shopped`, which ./doors.ts
7
+ // hears them with).
8
+ //
9
+ // Direct charges throughout, the "charge merchants directly" model. The
10
+ // connected account is the merchant: the charge is on their books, Stripe's
11
+ // processing fee comes out of their money, the customer's statement says their
12
+ // name, and a refund or a dispute is theirs to answer and theirs to pay. The
13
+ // platform acts on their account with its own key, one `Stripe-Account` header
14
+ // (./mod.ts `ask`), and names an `application_fee_amount` Stripe moves to it
15
+ // out of the same payment.
16
+ //
17
+ // A seller who already has a Stripe account connects it instead, through
18
+ // Connect's OAuth for Standard accounts (docs.stripe.com/connect/oauth-standard-accounts):
19
+ // Stripe's page asks them to sign in and allow the platform, and hands them
20
+ // back with a code the platform trades for the account's id. Stripe calls
21
+ // OAuth not recommended for new platforms because Account Links onboard an
22
+ // account the platform makes; it remains the one way to connect an account
23
+ // that already exists. The account is theirs, not the platform's to
24
+ // control, so its details are changed in their own dashboard, and the same
25
+ // direct charges and application fee apply to it.
26
+ //
27
+ // The house sells on the platform's own account instead (@yaks/host/payments
28
+ // `Seller`), named '' wherever an account is: the same calls with no
29
+ // `Stripe-Account` header, so the charge is the platform's, Stripe's fees come
30
+ // out of the platform's balance (and its fee credit), and no application fee
31
+ // is named, since Stripe takes none from an account for itself. Managed
32
+ // Payments, on by default on the platform's account for its plans, is turned
33
+ // off for these: it sells digital goods as merchant of record, and the house
34
+ // sells printed books as itself. The card statement reads the platform's
35
+ // prefix and the seller's name after it (`YAKS.APP* PRINTBOUND`). Its events
36
+ // arrive at the platform's own endpoint, which `housed` tells from the
37
+ // platform's own plans.
38
+ //
39
+ // v1 throughout, deliberately: `POST /v1/accounts` with controller properties,
40
+ // and the v1 event names. There is a v2 Accounts API with its own thin
41
+ // `v2.core.*` events; mixing the two would mean a reader of one set of names
42
+ // and a dashboard ticking the other, which is a webhook that silently does
43
+ // nothing.
44
+ import type {
45
+ Billed,
46
+ Costs,
47
+ Paid,
48
+ Sale,
49
+ Seller,
50
+ Settled,
51
+ Shopped,
52
+ Shops,
53
+ Tags,
54
+ } from 'jsr:@yaks/host@0.2.36/payments'
55
+ import { ask, found, idOf, type Keyed, minimum } from './mod.js'
56
+ import { refund, refundedOf } from './refunds.js'
57
+ import { shopPortal } from './shop-portal.js'
58
+ import { cancelTerm, termAt } from './shop-term.js'
59
+
60
+ /** The slice of a Stripe account read here. Optional throughout: the shape is
61
+ * Stripe's to move, and a field that went missing must leave a readable row
62
+ * rather than a throw in the middle of somebody's onboarding. */
63
+ export type Account = {
64
+ id?: string
65
+ charges_enabled?: boolean
66
+ details_submitted?: boolean
67
+ payouts_enabled?: boolean
68
+ /** `is_controller` true for an account the platform made; unset for one
69
+ * a seller connected */
70
+ controller?: { is_controller?: boolean }
71
+ }
72
+
73
+ /** Stripe's host for Connect's OAuth, and where a seller whose account the
74
+ * platform does not control changes its details: their own dashboard. */
75
+ export let CONNECT = 'https://connect.stripe.com'
76
+ export let DASHBOARD = 'https://dashboard.stripe.com/'
77
+
78
+ /** What the shops are lent: the key and clock, and the platform's Connect
79
+ * `client_id` (ca_…), which a seller connects an account they already have
80
+ * through; without one they can only open a new one. */
81
+ export type Options = Keyed & {
82
+ client?: string
83
+ publishableKey?: string
84
+ walletKey?: string
85
+ }
86
+
87
+ /// authorizeAt('ca_1', 's1', 'https://yaks.app/selling/callback') -> 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_1&scope=read_write&state=s1&redirect_uri=https%3A%2F%2Fyaks.app%2Fselling%2Fcallback'
88
+ /** The address of Stripe's page where a seller connects an account they
89
+ * already have. `read_write` is the only scope a platform may ask for, and
90
+ * `redirect_uri` must be one listed in the platform's OAuth settings. */
91
+ export let authorizeAt = (client: string, state: string, back: string) =>
92
+ `${CONNECT}/oauth/authorize?${new URLSearchParams({
93
+ response_type: 'code',
94
+ client_id: client,
95
+ scope: 'read_write',
96
+ state,
97
+ redirect_uri: back,
98
+ })}`
99
+
100
+ /** The slice of a completed Checkout Session read here. */
101
+ export type Session = {
102
+ id?: string
103
+ payment_intent?: string | { id?: string; status?: string } | null
104
+ payment_status?: string
105
+ status?: string
106
+ amount_total?: number
107
+ currency?: string
108
+ customer?: string | { id?: string } | null
109
+ customer_email?: string | null
110
+ customer_details?: { email?: string | null; name?: string | null }
111
+ metadata?: Record<string, string>
112
+ /** the one it started, in subscription mode */
113
+ subscription?: string | { id?: string } | null
114
+ }
115
+
116
+ /** The slice of a charge, or of a dispute about one, read here. */
117
+ export type Charge = {
118
+ id?: string
119
+ /** a dispute's charge */
120
+ charge?: string | { id?: string }
121
+ payment_intent?: string | { id?: string }
122
+ metadata?: Record<string, string>
123
+ refunded?: boolean
124
+ amount?: number
125
+ amount_refunded?: number
126
+ application_fee?: string | { id?: string }
127
+ status?: string
128
+ }
129
+
130
+ /**
131
+ * The account asked for, as the form fields of `POST /v1/accounts`.
132
+ *
133
+ * The controller properties are the whole model. "Charge merchants directly"
134
+ * is these four answers, and each is a sentence about who is responsible for
135
+ * what. They are also, all four, Stripe's own defaults, the combination it
136
+ * documents as the Standard mapping
137
+ * (docs.stripe.com/connect/migrate-to-controller-properties). They are written
138
+ * out anyway, because a liability decision that four omitted parameters happen
139
+ * to make is a liability decision nobody can read, and a default Stripe moves
140
+ * one day would move it silently.
141
+ *
142
+ * `controller[fees][payer] = account`
143
+ * the connected account pays Stripe's processing fee, out of its own
144
+ * money, on its own charge. Not the platform: it is not reselling
145
+ * payments.
146
+ * `controller[losses][payments] = stripe`
147
+ * Stripe, not the platform, carries the negative balance when a dispute
148
+ * is lost. There is no `account` value here and the value is not a
149
+ * mistake: `stripe` is what "the platform is not liable" is called, and
150
+ * the merchant is still the one whose charge is reversed.
151
+ * `controller[stripe_dashboard][type] = full`
152
+ * the seller gets the whole Stripe Dashboard, their own account, where
153
+ * they read their payments, answer their disputes and manage their
154
+ * payouts. `express` is the cut-down one, and Stripe refuses it beside
155
+ * `fees.payer = account`: an Express dashboard is for a platform that
156
+ * pays the fees and carries the losses, which is the opposite of this.
157
+ * `controller[requirement_collection] = stripe`
158
+ * Stripe collects and re-collects the identity requirements, through the
159
+ * Account Link below. The platform never sees, stores or forwards a
160
+ * seller's identity documents, which is exactly the property that lets
161
+ * this integration exist without it becoming a KYC operator.
162
+ *
163
+ * No `capabilities`, deliberately. Stripe requires them only where the account
164
+ * has no Stripe-hosted dashboard; with `full` the payment capabilities are
165
+ * requested automatically for the account's country, and the seller manages
166
+ * them themselves. `transfers` in particular would be wrong: that is the
167
+ * capability a destination charge needs, and a direct charge never transfers.
168
+ *
169
+ * No `type` either. It is deprecated in favour of exactly these four
170
+ * properties, and the two ways of saying one thing are not passed together.
171
+ *
172
+ * `metadata` carries the tags, so an account read back out of Stripe's
173
+ * dashboard says whose it is without a lookup.
174
+ */
175
+ export let account = (who: { email?: string; tags: Tags }) => ({
176
+ controller: {
177
+ fees: { payer: 'account' },
178
+ losses: { payments: 'stripe' },
179
+ stripe_dashboard: { type: 'full' },
180
+ requirement_collection: 'stripe',
181
+ },
182
+ ...(who.email ? { email: who.email } : {}),
183
+ metadata: who.tags,
184
+ })
185
+
186
+ /** The onboarding link, as the form fields of `POST /v1/account_links`.
187
+ *
188
+ * `account_onboarding` and never `account_update`: Stripe refuses an update
189
+ * link for an account that has its own dashboard, and these all do. A seller
190
+ * changing their details later does it in their own Stripe Dashboard, which is
191
+ * the whole point of giving them one.
192
+ *
193
+ * `return_url` is where Stripe sends them when they finish, and `refresh_url`
194
+ * where it sends them when the link is spent: an Account Link is single-use
195
+ * and expires in about five minutes, since it is an authenticated door into
196
+ * somebody's identity form. Stripe's own instruction for `refresh_url` is
197
+ * "generate a new account link with the same parameters, then redirect", which
198
+ * is asking for onboarding again, so both are `back`. */
199
+ export let link = (account: string, back: string) => ({
200
+ account,
201
+ type: 'account_onboarding',
202
+ return_url: back,
203
+ refresh_url: back,
204
+ })
205
+
206
+ /** A Stripe account as a seller: `charges_enabled` is `ready` and
207
+ * `details_submitted` is `submitted`.
208
+ *
209
+ * A missing field reads false rather than "unchanged". Stripe sends the whole
210
+ * account object on every `account.updated`, so an absent flag is an absent
211
+ * capability, and a reader that treated it as unchanged would leave a seller
212
+ * marked ready after Stripe stopped them. */
213
+ export let sellerOf = (a: Account): Seller => ({
214
+ account: String(a.id ?? ''),
215
+ ready: !!a.charges_enabled,
216
+ submitted: !!a.details_submitted,
217
+ })
218
+
219
+ /** What Stripe charges a seller in the United States, from its pricing page
220
+ * (stripe.com/pricing) and help pages, read 2026-11-23: 2.9% + 30¢ a
221
+ * domestic card payment, 1.5% more for an international card, a $15 dispute
222
+ * fee returned on a won dispute, processing fees kept on a refund
223
+ * (support.stripe.com/questions/understanding-fees-for-refunded-payments),
224
+ * and payouts on a two-day rolling schedule after a first payout about seven
225
+ * days after the first payment
226
+ * (support.stripe.com/questions/delay-for-first-payout-for-connected-accounts).
227
+ * The account pays them itself (`fees.payer = account`, {@link account}),
228
+ * so these are the seller's costs, as published, and change when Stripe's
229
+ * pricing does. */
230
+ export let COSTS: Costs = {
231
+ card: { bps: 290, cents: 30 },
232
+ bankDebit: { bps: 80, cap: 500 },
233
+ recurring: 70,
234
+ abroad: 150,
235
+ dispute: 1500,
236
+ refunded: false,
237
+ payout: { days: 2, first: 7 },
238
+ country: 'US',
239
+ pricing: 'https://stripe.com/pricing',
240
+ }
241
+
242
+ /** The longest metadata value Stripe keeps, in characters: the most one
243
+ * tag carries ({@link Shops.tag}). */
244
+ export let TAG = 500
245
+
246
+ /** A return address as Stripe reads it. `{CHECKOUT_SESSION_ID}` is a literal
247
+ * Stripe substitutes the session id for on the way back, and the host hands
248
+ * over an address `URL` wrote, which percent-encodes braces in a query:
249
+ * `%7BCHECKOUT_SESSION_ID%7D` is a string Stripe does not recognise, so the
250
+ * buyer would land on a page that never learns which order it is about. The
251
+ * braces come back, and only those two characters. */
252
+ export let back = (url: string): string =>
253
+ url.replaceAll('%7B', '{').replaceAll('%7D', '}')
254
+
255
+ /// cut({ lines: [{ name: 'Tee', cents: 999, qty: 1 }], bps: 250 }) -> 24
256
+ /// cut({ lines: [{ name: 'Tee', cents: 100, qty: 1 }], bps: 20_000 }) -> 100
257
+ /** The platform's cut of a sale paid once, in its smallest unit: the rate of
258
+ * its whole total, shipping included, rounded down, and never more than the
259
+ * sale. */
260
+ export let cut = (sale: Pick<Sale, 'lines' | 'shipping' | 'bps'>): number => {
261
+ let total = sale.lines.reduce((n, l) => n + l.cents * l.qty, 0) +
262
+ (sale.shipping?.cents ?? 0)
263
+ return Math.min(
264
+ total,
265
+ Math.max(0, Math.floor(total * (sale.bps || 0) / 10_000)),
266
+ )
267
+ }
268
+
269
+ // The payment a sale paid once makes. `application_fee_amount` is the
270
+ // platform's cut, and this is the only place Stripe takes one for a payment
271
+ // Checkout Session: there is no top-level parameter. It is left out entirely
272
+ // when it is zero, since Stripe requires a positive amount, so a fee of
273
+ // nothing has to be no fee rather than a fee of 0.
274
+ //
275
+ // The tags are copied onto it, which is not redundancy: a refund arrives as a
276
+ // `charge.refunded`, whose object inherits the PaymentIntent's metadata and
277
+ // knows nothing of the session, so without them the refund of a sale could
278
+ // not be told whose it was.
279
+ let once = (sale: Sale, house: boolean) => {
280
+ let fee = house ? 0 : cut(sale)
281
+ let suffix = descriptor(
282
+ sale.statementSuffix ?? (house ? sale.descriptor ?? '' : ''),
283
+ )
284
+ return {
285
+ ...(house ? { managed_payments: { enabled: false } } : {}),
286
+ ...(sale.shipping
287
+ ? {
288
+ shipping_options: [{
289
+ shipping_rate_data: {
290
+ type: 'fixed_amount',
291
+ display_name: sale.shipping.name,
292
+ fixed_amount: {
293
+ amount: sale.shipping.cents,
294
+ currency: sale.currency,
295
+ },
296
+ },
297
+ }],
298
+ }
299
+ : {}),
300
+ payment_intent_data: {
301
+ ...(fee > 0 ? { application_fee_amount: fee } : {}),
302
+ ...(suffix ? { statement_descriptor_suffix: suffix } : {}),
303
+ ...(sale.description ? { description: sale.description } : {}),
304
+ metadata: house ? marked(sale.tags) : sale.tags,
305
+ ...(sale.destination ? { shipping: sale.destination } : {}),
306
+ },
307
+ }
308
+ }
309
+
310
+ // The subscription a renewing sale makes. Its fee is a percent of every
311
+ // invoice, since an amount would be taken from the first payment alone, and a
312
+ // rate in whole basis points is a percent with the two decimal places Stripe
313
+ // takes. The tags ride the subscription, which every `customer.subscription.*`
314
+ // event carries back, and which an invoice's payment does not inherit.
315
+ let renewing = (sale: Sale) => ({
316
+ subscription_data: {
317
+ ...(sale.bps > 0
318
+ ? { application_fee_percent: Math.min(100, sale.bps / 100) }
319
+ : {}),
320
+ ...(sale.description ? { description: sale.description } : {}),
321
+ metadata: sale.tags,
322
+ },
323
+ })
324
+
325
+ /// descriptor('PrintBound') -> 'PRINTBOUND'
326
+ /// descriptor('Crayon "Bloom" <Books>') -> 'CRAYON BLOOM BOOKS'
327
+ /// descriptor('1234') -> ''
328
+ /** A seller's name as a statement descriptor suffix: upper case, without the
329
+ * characters Stripe refuses there (`<>\'"*`), at most 22 characters, and ''
330
+ * where no letter is left, which Stripe requires one of. Stripe itself cuts
331
+ * the suffix to what fits after the account's prefix. */
332
+ export let descriptor = (name: string): string => {
333
+ let out = name.toUpperCase().replace(/[<>\\'"*]/g, '').replace(/\s+/g, ' ')
334
+ .trim().slice(0, 22).trim()
335
+ return /\p{L}/u.test(out) ? out : ''
336
+ }
337
+
338
+ /** The metadata key a house sale's objects carry, which tells its events on
339
+ * the platform's own account from the platform's plans (`housed`). */
340
+ export let HOUSE = 'house'
341
+
342
+ let marked = (tags: Tags): Tags => ({ ...tags, [HOUSE]: 'true' })
343
+
344
+ /**
345
+ * The Checkout Session, as the form fields of `POST /v1/checkout/sessions`,
346
+ * made on the seller's account (the `Stripe-Account` header `checkout` adds),
347
+ * or on the platform's own for the house: in payment mode for a sale paid
348
+ * once, and in subscription mode for one that says how often it renews, where
349
+ * every line recurs at that interval.
350
+ *
351
+ * The tags ride `metadata`, and the payment or the subscription it makes as
352
+ * well, with the house's mark on a house sale. Lines go out as inline
353
+ * `price_data`, numbered as Stripe's form encoding numbers a list.
354
+ */
355
+ export let session = (
356
+ sale: Sale,
357
+ house = false,
358
+ embedded = false,
359
+ ): Record<string, unknown> => ({
360
+ mode: sale.per ? 'subscription' : 'payment',
361
+ ...(sale.bankDebit && embedded && !house
362
+ ? {
363
+ payment_method_types: ['card', 'link', 'us_bank_account'],
364
+ payment_method_options: {
365
+ us_bank_account: { verification_method: 'instant' },
366
+ },
367
+ adaptive_pricing: { enabled: false },
368
+ }
369
+ : sale.cardOnly
370
+ ? { payment_method_types: ['card'], adaptive_pricing: { enabled: false } }
371
+ : {}),
372
+ ...(sale.expires
373
+ ? { expires_at: Math.floor(Date.parse(sale.expires) / 1000) }
374
+ : {}),
375
+ line_items: Object.fromEntries(sale.lines.map((l, i) => [i, {
376
+ price_data: {
377
+ currency: sale.currency,
378
+ product_data: {
379
+ name: l.name,
380
+ ...(l.description ? { description: l.description } : {}),
381
+ },
382
+ unit_amount: l.cents,
383
+ ...(sale.per ? { recurring: { interval: sale.per } } : {}),
384
+ },
385
+ quantity: l.qty,
386
+ }])),
387
+ ...(embedded
388
+ ? {
389
+ ui_mode: 'elements',
390
+ return_url: back(sale.done),
391
+ name_collection: { individual: { enabled: true } },
392
+ }
393
+ : { success_url: back(sale.done), cancel_url: back(sale.cancel) }),
394
+ ...(sale.email ? { customer_email: sale.email } : {}),
395
+ metadata: house ? marked(sale.tags) : sale.tags,
396
+ ...(sale.per ? renewing(sale) : once(sale, house)),
397
+ })
398
+
399
+ /** A completed session as the sale it made. The buyer's address is
400
+ * `customer_details.email` and only falls back to `customer_email`: the
401
+ * second is the prefill the checkout started with, and the person may have
402
+ * typed a different one on Stripe's page. `payment_status` is the gate and
403
+ * `status` is not: a session can be `complete` with a payment still
404
+ * processing (a bank debit, say), and `paid` is the word Stripe documents as
405
+ * "the funds are available". */
406
+ export let paidOf = (o: Session): Paid => ({
407
+ ...(o.currency ? { currency: o.currency } : {}),
408
+ paid: o.payment_status == 'paid',
409
+ ...(o.status == 'expired' ? { expired: true } : {}),
410
+ ...(o.status == 'complete' && o.payment_status == 'unpaid'
411
+ ? (typeof o.payment_intent == 'object' &&
412
+ ['requires_payment_method', 'canceled'].includes(
413
+ o.payment_intent?.status ?? '',
414
+ ))
415
+ ? { failed: true }
416
+ : { processing: true }
417
+ : {}),
418
+ status: String(o.payment_status ?? ''),
419
+ checkout: String(o.id ?? ''),
420
+ payment: idOf(o.payment_intent),
421
+ ...(idOf(o.subscription) ? { subscription: idOf(o.subscription) } : {}),
422
+ ...(idOf(o.subscription) && idOf(o.customer)
423
+ ? { payer: idOf(o.customer) }
424
+ : {}),
425
+ total: Math.max(0, Math.floor(Number(o.amount_total ?? 0))),
426
+ email: String(o.customer_details?.email || o.customer_email || ''),
427
+ ...(o.customer_details?.name ? { name: o.customer_details.name } : {}),
428
+ tags: { ...o.metadata },
429
+ })
430
+
431
+ // Where an event moves a payment. A refund is whole only once the whole charge
432
+ // is (Stripe's `refunded`). A dispute is open until it closes: `lost` means
433
+ // the buyer's bank took the money back, and `won` or an inquiry closed without
434
+ // one (`warning_closed`) restores it. A dispute's other events (updated, funds
435
+ // withdrawn or reinstated) move nothing.
436
+ let settledBy = (type: string, o: Charge): Settled | null =>
437
+ type == 'charge.refunded'
438
+ ? o.refunded ? 'refunded' : 'partially_refunded'
439
+ : type == 'charge.dispute.created'
440
+ ? 'disputed'
441
+ : type == 'charge.dispute.closed'
442
+ ? o.status == 'lost' ? 'lost' : 'restored'
443
+ : null
444
+
445
+ type Event = {
446
+ type?: string
447
+ created?: number
448
+ livemode?: boolean
449
+ account?: string
450
+ data?: { object?: Record<string, unknown> }
451
+ }
452
+
453
+ /** Stripe's shops, every call made with `options` as they read at the
454
+ * time. */
455
+ export let shops = (options: Options): Shops => {
456
+ let mode = () =>
457
+ /^(?:sk|rk)_test_/.test(options.key ?? '')
458
+ ? 'test'
459
+ : /^(?:sk|rk)_live_/.test(options.key ?? '')
460
+ ? 'live'
461
+ : undefined
462
+ let elements = (account: string, row: Record<string, unknown>) => {
463
+ let clientSecret = row.client_secret
464
+ if (typeof clientSecret != 'string' || !clientSecret) return null
465
+ return {
466
+ clientSecret,
467
+ publishableKey: options.publishableKey!,
468
+ ...(row.id ? { id: String(row.id) } : {}),
469
+ ...(account ? { account } : {}),
470
+ }
471
+ }
472
+ let embedded = () =>
473
+ !!mode() &&
474
+ options.publishableKey?.startsWith(`pk_${mode()}_`) === true
475
+ let domains = new Map<string, Promise<void>>()
476
+ let walletDomain = async (on: string, domain: string, key: string) => {
477
+ let credentials = { key, clock: options.clock }
478
+ let path = '/v1/payment_method_domains'
479
+ let listed = await ask(
480
+ credentials,
481
+ `${path}?${new URLSearchParams({ domain_name: domain })}`,
482
+ undefined,
483
+ on,
484
+ )
485
+ let [held] = listed.data as { id: string; enabled: boolean }[]
486
+ if (!held) {
487
+ await ask(
488
+ credentials,
489
+ path,
490
+ { domain_name: domain },
491
+ on,
492
+ 'POST',
493
+ `wallet|${on}|${domain}`,
494
+ )
495
+ }
496
+ }
497
+ // The address of what one POST made, which Stripe always answers with.
498
+ let made = async (
499
+ what: string,
500
+ path: string,
501
+ fields: Record<string, unknown>,
502
+ on?: string,
503
+ key?: string,
504
+ ) => {
505
+ let url = String(
506
+ (await ask(options, path, fields, on, 'POST', key)).url ?? '',
507
+ )
508
+ if (!url) throw new Error(`stripe made ${what} with no url`)
509
+ return url
510
+ }
511
+ return {
512
+ on: () => !!options.key,
513
+ costs: COSTS,
514
+ minimum,
515
+ mode,
516
+ tag: TAG,
517
+ open: async (who) => {
518
+ let a = await ask(options, '/v1/accounts', account(who)) as Account
519
+ if (!a.id) throw new Error('stripe made an account with no id')
520
+ return sellerOf(a)
521
+ },
522
+ // An account the seller brought is not ours to onboard: Stripe makes no
523
+ // Account Link for it, and its owner finishes in their own dashboard.
524
+ onboarding: async (id, back) => {
525
+ let a = await ask(options, `/v1/accounts/${encodeURIComponent(id)}`)
526
+ return (a as Account).controller?.is_controller
527
+ ? await made('an account link', '/v1/account_links', link(id, back))
528
+ : DASHBOARD
529
+ },
530
+ authorize: (state, back) =>
531
+ options.client ? authorizeAt(options.client, state, back) : null,
532
+ // The code is good once, so the trade is never retried under a new key.
533
+ authorized: async (code) => {
534
+ let token = await ask(
535
+ options,
536
+ `${CONNECT}/oauth/token`,
537
+ { grant_type: 'authorization_code', code },
538
+ undefined,
539
+ 'POST',
540
+ `oauth:${code}`,
541
+ )
542
+ let id = String(token.stripe_user_id ?? '')
543
+ if (!id) throw new Error('stripe connected an account with no id')
544
+ return sellerOf(
545
+ await ask(options, `/v1/accounts/${encodeURIComponent(id)}`) as Account,
546
+ )
547
+ },
548
+ // On the seller's account: that one header is the whole of what makes it
549
+ // their charge rather than the platform's. The house's has none, and
550
+ // sells nothing that renews: a subscription's events on the platform's
551
+ // own account are read as the platform's plans.
552
+ checkout: (on, sale) => {
553
+ if (!on && sale.per) {
554
+ throw new Error('the house sells nothing that renews')
555
+ }
556
+ return made(
557
+ 'a checkout session',
558
+ '/v1/checkout/sessions',
559
+ session(sale, !on),
560
+ on,
561
+ sale.key,
562
+ )
563
+ },
564
+ embedded: {
565
+ on: embedded,
566
+ checkout: async (on, sale) => {
567
+ if (!embedded()) {
568
+ throw new Error('stripe checkout publishable key unavailable')
569
+ }
570
+ if (!on && sale.per) {
571
+ throw new Error('the house sells nothing that renews')
572
+ }
573
+ let made = await ask(
574
+ options,
575
+ '/v1/checkout/sessions',
576
+ session(sale, !on, true),
577
+ on,
578
+ 'POST',
579
+ sale.key ? `elements|${sale.key}` : undefined,
580
+ )
581
+ let payment = elements(on, made)
582
+ if (!payment) {
583
+ throw new Error(
584
+ 'stripe made an in-page checkout without a client secret',
585
+ )
586
+ }
587
+ return payment
588
+ },
589
+ resume: async (on, id) => {
590
+ if (!embedded()) return null
591
+ let held = await found(
592
+ options,
593
+ `/v1/checkout/sessions/${encodeURIComponent(id)}`,
594
+ on,
595
+ )
596
+ return held?.status == 'open' ? elements(on, held) : null
597
+ },
598
+ walletDomain: (on, domain) => {
599
+ let credential = options.walletKey
600
+ if (!credential) return Promise.resolve()
601
+ let key = JSON.stringify([mode(), on, domain])
602
+ let held = domains.get(key)
603
+ if (held) return held
604
+ if (domains.size >= 256) domains.delete(domains.keys().next().value!)
605
+ let registered = walletDomain(on, domain, credential).catch((error) => {
606
+ domains.delete(key)
607
+ throw error
608
+ })
609
+ domains.set(key, registered)
610
+ return registered
611
+ },
612
+ },
613
+ paid: async (on, checkout) => {
614
+ let o = await found(
615
+ options,
616
+ `/v1/checkout/sessions/${
617
+ encodeURIComponent(checkout)
618
+ }?expand[]=payment_intent`,
619
+ on,
620
+ )
621
+ return o && paidOf(o as Session)
622
+ },
623
+ term: (on, id) => termAt(options, on, id),
624
+ // `cancel_at_period_end` and not a delete: the buyer keeps what they paid
625
+ // for, and Stripe ends it when the period does. Setting it twice is one
626
+ // setting, so no request key holds it: one would replay a stale answer
627
+ // to a cancel asked again after the seller undid the first.
628
+ cancel: (on, id) => cancelTerm(options, on, id),
629
+ refund: (on, request) => refund(options, on, request),
630
+ portal: (on, payer, subscription, back, purpose) =>
631
+ shopPortal(options, on, payer, subscription, back, purpose),
632
+ refundFee: async (id, refunded, total) => {
633
+ if (!total || !refunded) return
634
+ let fee = await ask(
635
+ options,
636
+ `/v1/application_fees/${encodeURIComponent(id)}`,
637
+ )
638
+ let target = Math.floor(
639
+ Number(fee.amount ?? 0) * Math.min(refunded, total) / total,
640
+ )
641
+ let amount = target - Number(fee.amount_refunded ?? 0)
642
+ if (amount <= 0) return
643
+ await ask(
644
+ options,
645
+ `/v1/application_fees/${encodeURIComponent(id)}/refunds`,
646
+ { amount },
647
+ undefined,
648
+ 'POST',
649
+ `fee:${id}:${refunded}:${total}`,
650
+ )
651
+ },
652
+ }
653
+ }
654
+
655
+ // A charge's payment and what it carries: a charge inherits its intent's
656
+ // metadata, and is read back on the seller's own account for a dispute, which
657
+ // carries none of its own.
658
+ let payment = (o: Charge) => {
659
+ let id = idOf(o.payment_intent)
660
+ return id
661
+ ? {
662
+ id,
663
+ tags: { ...o.metadata },
664
+ ...(o.amount != null ? { total: o.amount } : {}),
665
+ ...(o.amount_refunded != null ? { refunded: o.amount_refunded } : {}),
666
+ ...(idOf(o.application_fee) ? { fee: idOf(o.application_fee) } : {}),
667
+ }
668
+ : null
669
+ }
670
+
671
+ // The subscription an event moves the term of, '' where it names none, and
672
+ // null for an event about no subscription's term. A subscription's own events
673
+ // say it was made, renewed, cancelled or ended; an invoice paid is a period
674
+ // paid for, and names its subscription under `parent` since API
675
+ // 2025-03-31.basil and at its top level before (as ./plans.ts `changed`
676
+ // reads it). Every one is read again from Stripe when it is applied, so the
677
+ // order they arrive in leaves the latest word.
678
+ let subscribedBy = (type: string, o: Record<string, unknown>) => {
679
+ if (type.startsWith('customer.subscription.')) {
680
+ return idOf(o.id as string | undefined)
681
+ }
682
+ if (type != 'invoice.paid' && type != 'invoice.payment_failed') return null
683
+ let parent = o.parent as
684
+ | { subscription_details?: { subscription?: string | { id?: string } } }
685
+ | undefined
686
+ return idOf(
687
+ (o.subscription as string | { id?: string } | undefined) ??
688
+ parent?.subscription_details?.subscription,
689
+ )
690
+ }
691
+
692
+ /** The slice of a paid invoice read here. */
693
+ export type Invoice = {
694
+ id?: string
695
+ customer?: string | { id?: string }
696
+ customer_email?: string | null
697
+ customer_name?: string | null
698
+ amount_paid?: number
699
+ created?: number
700
+ status_transitions?: { paid_at?: number | null }
701
+ parent?: { subscription_details?: { metadata?: Tags | null } }
702
+ subscription_details?: { metadata?: Tags | null }
703
+ }
704
+
705
+ let invoiceTags = (o: Invoice): Tags =>
706
+ o.parent?.subscription_details?.metadata ??
707
+ o.subscription_details?.metadata ?? {}
708
+
709
+ /// billedOf({ id: 'in_1', customer: 'cus_1', amount_paid: 2500, created: 0, parent: { subscription_details: { metadata: { a: 'b' } } } }, 'sub_1') -> { id: 'in_1', subscription: 'sub_1', payer: 'cus_1', total: 2500, at: '1970-01-01T00:00:00.000Z', email: '', tags: { a: 'b' } }
710
+ /** A paid invoice as the period it paid. The subscription's metadata rides
711
+ * the invoice under `parent` since API 2025-03-31.basil, and at its top
712
+ * level before; the time is when it was paid, else when it was made. */
713
+ export let billedOf = (o: Invoice, subscription: string): Billed => ({
714
+ id: String(o.id ?? ''),
715
+ subscription,
716
+ payer: idOf(o.customer),
717
+ total: Number(o.amount_paid ?? 0),
718
+ at: new Date(
719
+ (o.status_transitions?.paid_at ?? o.created ?? 0) * 1000,
720
+ ).toISOString(),
721
+ email: o.customer_email ?? '',
722
+ ...(o.customer_name ? { name: o.customer_name } : {}),
723
+ tags: { ...invoiceTags(o) },
724
+ })
725
+
726
+ /** Whether a verified event Stripe posted about the platform's own account is
727
+ * about a house sale, which `shopped` reads, rather than about the platform's
728
+ * plans, which ./plans.ts `changed` reads: a checkout carrying the house's
729
+ * mark, or a payment refunded or disputed. The platform's plans read neither
730
+ * of the second, and a refund or dispute of one of theirs reads as a payment
731
+ * the shops know nothing of. */
732
+ export let housed = (event: unknown): boolean => {
733
+ let e = (event ?? {}) as Event
734
+ let type = e.type ?? ''
735
+ return type == 'checkout.session.completed'
736
+ ? (e.data?.object?.metadata as Tags | undefined)?.[HOUSE] == 'true'
737
+ : type == 'charge.refunded' || type.startsWith('charge.dispute.') ||
738
+ type.startsWith('refund.')
739
+ }
740
+
741
+ /** A verified event Stripe posted to the Connect endpoint, read, with the
742
+ * account it happened on: '' for one about a house sale, posted to the
743
+ * platform's own endpoint. */
744
+ export let shopped = (options: Keyed) => (event: unknown): Shopped => {
745
+ let e = (event ?? {}) as Event
746
+ let type = e.type ?? ''
747
+ let account = e.account ?? ''
748
+ let o = e.data?.object ?? {}
749
+ if (type == 'account.updated') {
750
+ return { account, about: 'seller', seller: sellerOf(o as Account) }
751
+ }
752
+ if (type == 'account.application.deauthorized') {
753
+ return { account, about: 'revoked' }
754
+ }
755
+ if (
756
+ type == 'checkout.session.completed' ||
757
+ type == 'checkout.session.async_payment_succeeded' ||
758
+ type == 'checkout.session.async_payment_failed' ||
759
+ type == 'checkout.session.expired' &&
760
+ (o.metadata as Tags | undefined)?.fundraiser
761
+ ) {
762
+ let sale = paidOf(o as Session)
763
+ if (type == 'checkout.session.async_payment_failed') {
764
+ sale.failed = true
765
+ delete sale.processing
766
+ }
767
+ if (sale.tags.fund && e.created && typeof e.livemode == 'boolean') {
768
+ sale.gift = {
769
+ at: new Date(e.created * 1000).toISOString(),
770
+ live: e.livemode,
771
+ }
772
+ }
773
+ return { account, about: 'sale', sale }
774
+ }
775
+ let renewed = subscribedBy(type, o)
776
+ if (renewed != null) {
777
+ let invoice =
778
+ type == 'invoice.paid' && renewed && o.paid_out_of_band !== true
779
+ ? { ...billedOf(o as Invoice, renewed), live: e.livemode }
780
+ : undefined
781
+ return {
782
+ account,
783
+ about: 'term',
784
+ subscription: renewed,
785
+ tags: type.startsWith('customer.subscription.')
786
+ ? (o.metadata as Tags | undefined) ?? {}
787
+ : invoiceTags(o as Invoice),
788
+ term: async () =>
789
+ renewed ? await termAt(options, account, renewed) : null,
790
+ ...(invoice ? { invoice } : {}),
791
+ }
792
+ }
793
+ if (
794
+ type == 'refund.created' || type == 'refund.updated' ||
795
+ type == 'refund.failed'
796
+ ) {
797
+ return { account, about: 'refund', refund: refundedOf(o) }
798
+ }
799
+ let c = o as Charge
800
+ let to = settledBy(type, c)
801
+ if (!to) return { account, about: 'other' }
802
+ return {
803
+ account,
804
+ about: 'payment',
805
+ to,
806
+ payment: async () => {
807
+ if (type == 'charge.refunded') return payment(c)
808
+ let charge = idOf(c.charge)
809
+ if (!charge) return null
810
+ return payment(
811
+ await ask(
812
+ options,
813
+ `/v1/charges/${encodeURIComponent(charge)}`,
814
+ undefined,
815
+ account,
816
+ ) as Charge,
817
+ )
818
+ },
819
+ }
820
+ }