@fantastic.dev/better-stripe 0.39.0 → 0.40.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  4. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  5. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  6. package/dist/client/costRecovery-invoices.js +3 -5
  7. package/dist/client/costRecovery-invoices.js.map +1 -1
  8. package/dist/client/index.d.ts +3 -2
  9. package/dist/client/index.d.ts.map +1 -1
  10. package/dist/client/index.js +2 -2
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/client/paymentSource/client.d.ts +21 -0
  13. package/dist/client/paymentSource/client.d.ts.map +1 -0
  14. package/dist/client/paymentSource/client.js +8 -0
  15. package/dist/client/paymentSource/client.js.map +1 -0
  16. package/dist/client/paymentSource/contracts.d.ts +30 -0
  17. package/dist/client/paymentSource/contracts.d.ts.map +1 -0
  18. package/dist/client/paymentSource/contracts.js +16 -0
  19. package/dist/client/paymentSource/contracts.js.map +1 -0
  20. package/dist/client/paymentSource/economics.d.ts +12 -0
  21. package/dist/client/paymentSource/economics.d.ts.map +1 -0
  22. package/dist/client/paymentSource/economics.js +13 -0
  23. package/dist/client/paymentSource/economics.js.map +1 -0
  24. package/dist/client/paymentSource/funding.d.ts +10 -0
  25. package/dist/client/paymentSource/funding.d.ts.map +1 -0
  26. package/dist/client/paymentSource/funding.js +12 -0
  27. package/dist/client/paymentSource/funding.js.map +1 -0
  28. package/dist/client/paymentSource/history.d.ts +13 -0
  29. package/dist/client/paymentSource/history.d.ts.map +1 -0
  30. package/dist/client/paymentSource/history.js +41 -0
  31. package/dist/client/paymentSource/history.js.map +1 -0
  32. package/dist/client/paymentSource/resolver.d.ts +6 -0
  33. package/dist/client/paymentSource/resolver.d.ts.map +1 -0
  34. package/dist/client/paymentSource/resolver.js +222 -0
  35. package/dist/client/paymentSource/resolver.js.map +1 -0
  36. package/dist/client/settlement/verifiedSale.d.ts.map +1 -1
  37. package/dist/client/settlement/verifiedSale.js +4 -6
  38. package/dist/client/settlement/verifiedSale.js.map +1 -1
  39. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  40. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  41. package/dist/component/earnings/triggers.d.ts +16 -16
  42. package/docs/settlement.md +48 -0
  43. package/package.json +1 -1
  44. package/src/client/costRecovery-invoices.ts +3 -7
  45. package/src/client/index.ts +6 -2
  46. package/src/client/paymentSource/client.ts +13 -0
  47. package/src/client/paymentSource/contracts.ts +33 -0
  48. package/src/client/paymentSource/economics.ts +20 -0
  49. package/src/client/paymentSource/funding.ts +23 -0
  50. package/src/client/paymentSource/history.ts +48 -0
  51. package/src/client/paymentSource/resolver.test.ts +582 -0
  52. package/src/client/paymentSource/resolver.ts +350 -0
  53. package/src/client/settlement/verifiedSale.ts +4 -10
@@ -0,0 +1,350 @@
1
+ import type Stripe from "stripe";
2
+ import type {
3
+ FinancialOutcome,
4
+ FinancialUnavailable,
5
+ } from "../financialOutcomes/contracts.js";
6
+ import {
7
+ paymentSourceOptions,
8
+ type VerifiedPaymentSource,
9
+ type VerifiedPaymentSourceOptions,
10
+ } from "./contracts.js";
11
+ import { completeHistory } from "./history.js";
12
+ import { saleAmountFailure } from "./economics.js";
13
+ import { singleInvoiceFunding } from "./funding.js";
14
+
15
+ const reject = (
16
+ reason: Extract<FinancialUnavailable, { status: "rejected" }>["reason"],
17
+ ): FinancialUnavailable => ({ status: "rejected", reason, retryable: false });
18
+ const identity = (): FinancialUnavailable => ({
19
+ status: "conflict",
20
+ reason: "identity_changed",
21
+ retryable: false,
22
+ });
23
+ const incomplete = (): FinancialUnavailable => ({
24
+ status: "unknown",
25
+ reason: "history_incomplete",
26
+ retryable: false,
27
+ });
28
+ class SourceUnavailable extends Error {
29
+ constructor(readonly outcome: FinancialUnavailable) {
30
+ super(outcome.reason);
31
+ }
32
+ }
33
+ function requireSource(
34
+ condition: unknown,
35
+ outcome: FinancialUnavailable,
36
+ ): asserts condition {
37
+ if (!condition) throw new SourceUnavailable(outcome);
38
+ }
39
+ const objectId = (value: string | { id: string } | null | undefined) => {
40
+ const candidate = typeof value === "string" ? value : value?.id;
41
+ return typeof candidate === "string" && candidate.length > 0
42
+ ? candidate
43
+ : undefined;
44
+ };
45
+ const integer = (value: number) => Number.isSafeInteger(value) && value >= 0;
46
+
47
+ /** Read-only provenance. Current subscription items and application metadata never prove original price/funding. */
48
+ export async function resolveVerifiedPaymentSource(
49
+ stripe: Stripe,
50
+ input: VerifiedPaymentSourceOptions,
51
+ ): Promise<FinancialOutcome<VerifiedPaymentSource>> {
52
+ const parsed = paymentSourceOptions.safeParse(input);
53
+ if (!parsed.success) return reject("invalid_scope");
54
+ const opts = parsed.data;
55
+ const requestOptions = opts.stripeAccountId
56
+ ? { stripeAccount: opts.stripeAccountId }
57
+ : undefined;
58
+ try {
59
+ const payment = await stripe.paymentIntents.retrieve(
60
+ opts.paymentIntentId,
61
+ { expand: ["latest_charge.balance_transaction"] },
62
+ requestOptions,
63
+ );
64
+ requireSource(
65
+ payment.object === "payment_intent" &&
66
+ payment.id === opts.paymentIntentId,
67
+ identity(),
68
+ );
69
+ if (payment.status === "processing")
70
+ return {
71
+ status: "not_ready",
72
+ reason: "provider_pending",
73
+ retryable: true,
74
+ };
75
+ if (payment.status !== "succeeded") return reject("payment_not_payable");
76
+ const charge = payment.latest_charge;
77
+ if (!charge || typeof charge === "string")
78
+ return {
79
+ status: "not_ready",
80
+ reason: "provider_pending",
81
+ retryable: true,
82
+ };
83
+ requireSource(
84
+ charge.object === "charge" &&
85
+ typeof charge.id === "string" &&
86
+ !!charge.id &&
87
+ objectId(charge.payment_intent) === payment.id,
88
+ identity(),
89
+ );
90
+ requireSource(
91
+ payment.currency === opts.currency,
92
+ reject("currency_mismatch"),
93
+ );
94
+ requireSource(
95
+ integer(payment.amount_received) &&
96
+ payment.amount_received === opts.gross &&
97
+ payment.amount === opts.gross,
98
+ reject("unsupported_source"),
99
+ );
100
+ requireSource(
101
+ charge.paid &&
102
+ charge.captured &&
103
+ charge.status === "succeeded" &&
104
+ charge.amount_captured === opts.gross,
105
+ reject("unsupported_source"),
106
+ );
107
+ requireSource(
108
+ typeof payment.livemode === "boolean" &&
109
+ charge.livemode === payment.livemode,
110
+ identity(),
111
+ );
112
+ requireSource(
113
+ typeof payment.customer_account === "string" &&
114
+ !!payment.customer_account,
115
+ reject("unsupported_source"),
116
+ );
117
+ if (opts.customerAccountId)
118
+ requireSource(
119
+ payment.customer_account === opts.customerAccountId,
120
+ identity(),
121
+ );
122
+ const customerAccountId = payment.customer_account!;
123
+ const balanceRef = charge.balance_transaction;
124
+ if (!balanceRef)
125
+ return { status: "not_ready", reason: "fee_pending", retryable: true };
126
+ const balance =
127
+ typeof balanceRef === "string"
128
+ ? await stripe.balanceTransactions.retrieve(
129
+ balanceRef,
130
+ {},
131
+ requestOptions,
132
+ )
133
+ : balanceRef;
134
+ if (typeof balanceRef === "string")
135
+ requireSource(balance.id === balanceRef, identity());
136
+ requireSource(
137
+ balance.object === "balance_transaction" &&
138
+ typeof balance.id === "string" &&
139
+ !!balance.id &&
140
+ objectId(balance.source) === charge.id,
141
+ identity(),
142
+ );
143
+ const amountFailure = saleAmountFailure(payment, charge, balance);
144
+ requireSource(amountFailure !== "currency", reject("currency_mismatch"));
145
+ requireSource(
146
+ !amountFailure &&
147
+ integer(balance.amount) &&
148
+ integer(balance.net) &&
149
+ balance.amount === opts.gross &&
150
+ balance.amount - balance.fee === balance.net,
151
+ reject("unsupported_source"),
152
+ );
153
+ const read = <T extends { id: string }>(
154
+ fetch: (
155
+ cursor: string | undefined,
156
+ limit: number,
157
+ ) => Promise<Stripe.ApiList<T>>,
158
+ ) => completeHistory(fetch, opts.maxHistoryPages, opts.maxHistoryItems);
159
+ const inverse = await read((cursor, limit) =>
160
+ stripe.invoicePayments.list(
161
+ {
162
+ payment: { type: "payment_intent", payment_intent: payment.id },
163
+ limit,
164
+ ...(cursor ? { starting_after: cursor } : {}),
165
+ },
166
+ requestOptions,
167
+ ),
168
+ );
169
+ if (inverse.status !== "complete") return inverse;
170
+ for (const row of inverse.data) {
171
+ requireSource(
172
+ row.object === "invoice_payment" &&
173
+ ["paid", "open", "canceled"].includes(row.status),
174
+ incomplete(),
175
+ );
176
+ requireSource(
177
+ row.payment.type === "payment_intent" &&
178
+ objectId(row.payment.payment_intent) === payment.id &&
179
+ row.livemode === payment.livemode,
180
+ identity(),
181
+ );
182
+ requireSource(
183
+ row.currency === opts.currency,
184
+ reject("currency_mismatch"),
185
+ );
186
+ }
187
+ const original = singleInvoiceFunding(inverse.data, opts.gross);
188
+ requireSource(original, reject("unsupported_source"));
189
+ const invoiceId = objectId(original!.invoice);
190
+ requireSource(invoiceId, identity());
191
+ if (opts.invoiceId) requireSource(invoiceId === opts.invoiceId, identity());
192
+ const invoice = await stripe.invoices.retrieve(
193
+ invoiceId!,
194
+ {},
195
+ requestOptions,
196
+ );
197
+ requireSource(
198
+ invoice.object === "invoice" &&
199
+ invoice.id === invoiceId &&
200
+ invoice.customer_account === customerAccountId &&
201
+ invoice.livemode === payment.livemode,
202
+ identity(),
203
+ );
204
+ requireSource(
205
+ invoice.currency === opts.currency,
206
+ reject("currency_mismatch"),
207
+ );
208
+ if (invoice.status !== "paid")
209
+ return {
210
+ status: "not_ready",
211
+ reason: "provider_pending",
212
+ retryable: true,
213
+ };
214
+ requireSource(
215
+ [invoice.amount_paid, invoice.amount_due, invoice.total].every(
216
+ (value) => integer(value) && value === opts.gross,
217
+ ) &&
218
+ invoice.amount_remaining === 0 &&
219
+ invoice.amount_overpaid === 0,
220
+ reject("unsupported_source"),
221
+ );
222
+ const funding = await read((cursor, limit) =>
223
+ stripe.invoicePayments.list(
224
+ {
225
+ invoice: invoice.id,
226
+ limit,
227
+ ...(cursor ? { starting_after: cursor } : {}),
228
+ },
229
+ requestOptions,
230
+ ),
231
+ );
232
+ if (funding.status !== "complete") return funding;
233
+ for (const row of funding.data) {
234
+ requireSource(
235
+ row.object === "invoice_payment" &&
236
+ ["paid", "open", "canceled"].includes(row.status),
237
+ incomplete(),
238
+ );
239
+ requireSource(
240
+ objectId(row.invoice) === invoice.id &&
241
+ row.livemode === payment.livemode,
242
+ identity(),
243
+ );
244
+ requireSource(
245
+ row.currency === opts.currency,
246
+ reject("currency_mismatch"),
247
+ );
248
+ }
249
+ const funded = singleInvoiceFunding(funding.data, invoice.amount_paid);
250
+ requireSource(funded, reject("unsupported_source"));
251
+ requireSource(
252
+ funded!.id === original!.id &&
253
+ objectId(funded!.payment.payment_intent) === payment.id,
254
+ identity(),
255
+ );
256
+ requireSource(
257
+ original!.amount_requested === opts.gross &&
258
+ funded!.amount_requested === opts.gross,
259
+ reject("unsupported_source"),
260
+ );
261
+ const subscriptionId = objectId(
262
+ invoice.parent?.subscription_details?.subscription,
263
+ );
264
+ if (opts.subscriptionId)
265
+ requireSource(subscriptionId === opts.subscriptionId, identity());
266
+ if (subscriptionId) {
267
+ const subscription = await stripe.subscriptions.retrieve(
268
+ subscriptionId,
269
+ {},
270
+ requestOptions,
271
+ );
272
+ requireSource(
273
+ subscription.object === "subscription" &&
274
+ subscription.id === subscriptionId &&
275
+ subscription.customer_account === customerAccountId &&
276
+ subscription.livemode === payment.livemode,
277
+ identity(),
278
+ );
279
+ }
280
+ const lines = await read((cursor, limit) =>
281
+ stripe.invoices.listLineItems(
282
+ invoice.id,
283
+ { limit, ...(cursor ? { starting_after: cursor } : {}) },
284
+ requestOptions,
285
+ ),
286
+ );
287
+ if (lines.status !== "complete") return lines;
288
+ requireSource(lines.data.length === 1, reject("unsupported_source"));
289
+ const line = lines.data[0]!;
290
+ requireSource(
291
+ line.object === "line_item" &&
292
+ line.invoice === invoice.id &&
293
+ line.livemode === payment.livemode,
294
+ identity(),
295
+ );
296
+ requireSource(line.currency === opts.currency, reject("currency_mismatch"));
297
+ requireSource(
298
+ integer(line.amount) &&
299
+ line.amount > 0 &&
300
+ Number.isSafeInteger(line.quantity) &&
301
+ line.quantity! > 0,
302
+ reject("unsupported_source"),
303
+ );
304
+ const parent = line.parent;
305
+ const lineSubscription =
306
+ parent?.subscription_item_details?.subscription ??
307
+ parent?.invoice_item_details?.subscription ??
308
+ undefined;
309
+ requireSource(lineSubscription === subscriptionId, identity());
310
+ requireSource(
311
+ !parent?.subscription_item_details?.proration &&
312
+ !parent?.invoice_item_details?.proration,
313
+ reject("unsupported_source"),
314
+ );
315
+ const price = line.pricing?.price_details;
316
+ const priceId = objectId(price?.price);
317
+ const productId = objectId(price?.product);
318
+ requireSource(
319
+ line.pricing?.type === "price_details" && priceId && productId,
320
+ reject("unsupported_source"),
321
+ );
322
+ return {
323
+ status: "ready",
324
+ value: {
325
+ paymentIntentId: payment.id,
326
+ chargeId: charge.id,
327
+ invoiceId: invoice.id,
328
+ invoicePaymentId: funded!.id,
329
+ ...(subscriptionId ? { subscriptionId } : {}),
330
+ customerAccountId,
331
+ ...(opts.stripeAccountId
332
+ ? { stripeAccountId: opts.stripeAccountId }
333
+ : {}),
334
+ stripePriceId: priceId,
335
+ stripeProductId: productId,
336
+ gross: opts.gross,
337
+ processingFee: balance.fee,
338
+ currency: opts.currency,
339
+ livemode: payment.livemode,
340
+ },
341
+ };
342
+ } catch (error) {
343
+ if (error instanceof SourceUnavailable) return error.outcome;
344
+ return {
345
+ status: "unknown",
346
+ reason: "provider_outcome_unknown",
347
+ retryable: false,
348
+ };
349
+ }
350
+ }
@@ -1,4 +1,5 @@
1
1
  import type Stripe from "stripe";
2
+ import { saleAmountFailure } from "../paymentSource/economics.js";
2
3
  import { isBetterStripeError, throwStripeError } from "../errors.js";
3
4
  export type VerifiedSaleOptions = {
4
5
  paymentIntentId: string;
@@ -62,20 +63,13 @@ export async function getVerifiedSale(
62
63
  reason: "processing_fee_unavailable",
63
64
  retryable: true,
64
65
  };
65
- if (
66
- balance.currency !== payment.currency ||
67
- charge.currency !== payment.currency
68
- )
66
+ const amountFailure = saleAmountFailure(payment, charge, balance);
67
+ if (amountFailure === "currency")
69
68
  throwStripeError(
70
69
  "INVALID_CONFIGURATION",
71
70
  "Settlement currency must match the payment and processing currency.",
72
71
  );
73
- if (
74
- ![payment.amount_received, balance.fee].every(Number.isSafeInteger) ||
75
- balance.fee < 0 ||
76
- balance.fee > payment.amount_received ||
77
- charge.amount !== payment.amount_received
78
- )
72
+ if (amountFailure === "amounts")
79
73
  throwStripeError(
80
74
  "INVALID_CONFIGURATION",
81
75
  "Unsupported payment or processing amounts.",