@appweaver/stripe 0.0.0-stage → 3.1.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/LICENSE +21 -0
- package/README.md +104 -2
- package/index.d.ts +1 -0
- package/index.js +17 -0
- package/module.d.ts +3 -0
- package/module.js +50 -0
- package/package.json +57 -3
- package/stripe-gateway.d.ts +42 -0
- package/stripe-gateway.js +710 -0
- package/tsconfig.build.tsbuildinfo +1 -0
|
@@ -0,0 +1,710 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.StripeGateway = void 0;
|
|
7
|
+
const stripe_1 = __importDefault(require("stripe"));
|
|
8
|
+
const common_1 = require("@appweaver/common");
|
|
9
|
+
const payments_1 = require("@appweaver/payments");
|
|
10
|
+
const logger = (0, common_1.createLogger)('payments');
|
|
11
|
+
/** What is read with a payment: its charge with the fee, and the payment method paying. */
|
|
12
|
+
const PAYMENT_EXPAND = ['latest_charge.balance_transaction', 'payment_method'];
|
|
13
|
+
/** What is read with a subscription: the secret confirming the payment of its first invoice. */
|
|
14
|
+
const SUBSCRIPTION_EXPAND = ['latest_invoice.confirmation_secret'];
|
|
15
|
+
const PAYMENT_STATUSES = {
|
|
16
|
+
requires_payment_method: 'pending',
|
|
17
|
+
requires_confirmation: 'pending',
|
|
18
|
+
requires_action: 'requiresAction',
|
|
19
|
+
processing: 'processing',
|
|
20
|
+
requires_capture: 'authorized',
|
|
21
|
+
succeeded: 'succeeded',
|
|
22
|
+
canceled: 'canceled'
|
|
23
|
+
};
|
|
24
|
+
const SUBSCRIPTION_STATUSES = {
|
|
25
|
+
incomplete: 'incomplete',
|
|
26
|
+
incomplete_expired: 'canceled',
|
|
27
|
+
trialing: 'trialing',
|
|
28
|
+
active: 'active',
|
|
29
|
+
past_due: 'pastDue',
|
|
30
|
+
unpaid: 'unpaid',
|
|
31
|
+
paused: 'paused',
|
|
32
|
+
canceled: 'canceled'
|
|
33
|
+
};
|
|
34
|
+
const REFUND_STATUSES = {
|
|
35
|
+
succeeded: 'succeeded',
|
|
36
|
+
failed: 'failed',
|
|
37
|
+
canceled: 'canceled'
|
|
38
|
+
};
|
|
39
|
+
// An inquiry closed or prevented takes no money, like a dispute that is won
|
|
40
|
+
const DISPUTE_STATUSES = {
|
|
41
|
+
won: 'won',
|
|
42
|
+
warning_closed: 'won',
|
|
43
|
+
prevented: 'won',
|
|
44
|
+
lost: 'lost'
|
|
45
|
+
};
|
|
46
|
+
const PLAN_INTERVALS = {
|
|
47
|
+
day: 'day',
|
|
48
|
+
week: 'week',
|
|
49
|
+
month: 'month',
|
|
50
|
+
year: 'year'
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* The gateway of a Stripe account, on the official Stripe SDK: PaymentIntents confirmed by Stripe.js or charged to a
|
|
54
|
+
* saved payment method, Checkout Sessions, SetupIntents, refunds, Billing subscriptions and invoices, the customer
|
|
55
|
+
* portal, and the signed webhooks. A gateway of the `payments.gateways` config with the `stripe` driver, i.e.
|
|
56
|
+
* `{ "stripe": { "secretKey": "sk_...", "webhookSecret": "whsec_...", "publicKey": "pk_..." } }`; several accounts
|
|
57
|
+
* are several gateways, each with its `driver: 'stripe'`.
|
|
58
|
+
*/
|
|
59
|
+
class StripeGateway extends payments_1.PaymentGateway {
|
|
60
|
+
capabilities = [
|
|
61
|
+
'checkout',
|
|
62
|
+
'manualCapture',
|
|
63
|
+
'savedMethods',
|
|
64
|
+
'subscriptions',
|
|
65
|
+
'portal',
|
|
66
|
+
'prices'
|
|
67
|
+
];
|
|
68
|
+
/** The client of the Stripe SDK, for the calls the gateway does not wrap. */
|
|
69
|
+
client;
|
|
70
|
+
constructor(config) {
|
|
71
|
+
super(config);
|
|
72
|
+
if (!config.secretKey) {
|
|
73
|
+
throw new common_1.ConfigurationError(common_1.ErrorCode.ConfigurationInvalid, `The Stripe gateway '${config.name}' needs its secret key, set ${(0, payments_1.gatewayConfigKey)(config.name, 'secretKey')}`);
|
|
74
|
+
}
|
|
75
|
+
const url = config.apiUrl ? new URL(config.apiUrl) : undefined;
|
|
76
|
+
this.client = new stripe_1.default(config.secretKey, {
|
|
77
|
+
...(config.apiVersion
|
|
78
|
+
? { apiVersion: config.apiVersion }
|
|
79
|
+
: {}),
|
|
80
|
+
timeout: config.timeout,
|
|
81
|
+
maxNetworkRetries: config.maxRetries,
|
|
82
|
+
// The fetch of the runtime, traced by the telemetry and replaced by the tests
|
|
83
|
+
httpClient: stripe_1.default.createFetchHttpClient(((input, init) => globalThis.fetch(input, init))),
|
|
84
|
+
...(url
|
|
85
|
+
? {
|
|
86
|
+
host: url.hostname,
|
|
87
|
+
port: url.port || (url.protocol === 'https:' ? 443 : 80),
|
|
88
|
+
protocol: url.protocol.replace(':', '')
|
|
89
|
+
}
|
|
90
|
+
: {}),
|
|
91
|
+
appInfo: {
|
|
92
|
+
name: 'Appweaver',
|
|
93
|
+
url: 'https://github.com/lmatosevic/appweaver'
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
createCustomer(input) {
|
|
98
|
+
return this.run('createCustomer', async () => toCustomer(await this.client.customers.create({
|
|
99
|
+
email: input.email,
|
|
100
|
+
name: input.name,
|
|
101
|
+
preferred_locales: input.locale ? [input.locale] : undefined,
|
|
102
|
+
metadata: input.metadata
|
|
103
|
+
})));
|
|
104
|
+
}
|
|
105
|
+
updateCustomer(customerId, input) {
|
|
106
|
+
return this.run('updateCustomer', async () => toCustomer(await this.client.customers.update(customerId, {
|
|
107
|
+
email: input.email,
|
|
108
|
+
name: input.name,
|
|
109
|
+
preferred_locales: input.locale ? [input.locale] : undefined,
|
|
110
|
+
metadata: input.metadata
|
|
111
|
+
})));
|
|
112
|
+
}
|
|
113
|
+
deleteCustomer(customerId) {
|
|
114
|
+
return this.run('deleteCustomer', async () => {
|
|
115
|
+
await this.client.customers.del(customerId);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
createPayment(input) {
|
|
119
|
+
return this.run('createPayment', async () => {
|
|
120
|
+
const saved = !!input.paymentMethodId;
|
|
121
|
+
try {
|
|
122
|
+
return await this.toPayment(await this.client.paymentIntents.create({
|
|
123
|
+
amount: input.amount,
|
|
124
|
+
currency: input.currency.toLowerCase(),
|
|
125
|
+
capture_method: input.captureMethod,
|
|
126
|
+
customer: input.customerId,
|
|
127
|
+
description: input.description,
|
|
128
|
+
// A card statement only takes a suffix of the descriptor of the account
|
|
129
|
+
statement_descriptor_suffix: input.statementDescriptor,
|
|
130
|
+
receipt_email: input.receiptEmail,
|
|
131
|
+
metadata: input.metadata,
|
|
132
|
+
setup_future_usage: input.savePaymentMethod
|
|
133
|
+
? 'off_session'
|
|
134
|
+
: undefined,
|
|
135
|
+
automatic_payment_methods: {
|
|
136
|
+
enabled: true,
|
|
137
|
+
// Nobody is there to follow a redirect of a payment made while the customer is away
|
|
138
|
+
...(input.offSession ? { allow_redirects: 'never' } : {})
|
|
139
|
+
},
|
|
140
|
+
...(saved
|
|
141
|
+
? {
|
|
142
|
+
payment_method: input.paymentMethodId,
|
|
143
|
+
confirm: true,
|
|
144
|
+
...(input.offSession
|
|
145
|
+
? { off_session: true }
|
|
146
|
+
: { return_url: input.returnUrl })
|
|
147
|
+
}
|
|
148
|
+
: {}),
|
|
149
|
+
expand: PAYMENT_EXPAND
|
|
150
|
+
}, { idempotencyKey: input.idempotencyKey }));
|
|
151
|
+
}
|
|
152
|
+
catch (e) {
|
|
153
|
+
// A declined confirmation still created the payment: it is returned as failed, with its ID
|
|
154
|
+
const declined = e
|
|
155
|
+
.payment_intent;
|
|
156
|
+
if (e instanceof stripe_1.default.errors.StripeCardError && declined?.id) {
|
|
157
|
+
return this.toPayment(declined);
|
|
158
|
+
}
|
|
159
|
+
throw e;
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
getPayment(paymentId) {
|
|
164
|
+
return this.run('getPayment', async () => this.toPayment(await this.client.paymentIntents.retrieve(paymentId, {
|
|
165
|
+
expand: PAYMENT_EXPAND
|
|
166
|
+
}), true));
|
|
167
|
+
}
|
|
168
|
+
capturePayment(paymentId, amount, idempotencyKey) {
|
|
169
|
+
return this.run('capturePayment', async () => this.toPayment(await this.client.paymentIntents.capture(paymentId, { amount_to_capture: amount, expand: PAYMENT_EXPAND }, { idempotencyKey })));
|
|
170
|
+
}
|
|
171
|
+
cancelPayment(paymentId) {
|
|
172
|
+
return this.run('cancelPayment', async () => this.toPayment(await this.client.paymentIntents.cancel(paymentId, {
|
|
173
|
+
expand: PAYMENT_EXPAND
|
|
174
|
+
})));
|
|
175
|
+
}
|
|
176
|
+
refundPayment(input) {
|
|
177
|
+
return this.run('refundPayment', async () => toRefund(await this.client.refunds.create({
|
|
178
|
+
payment_intent: input.paymentId,
|
|
179
|
+
amount: input.amount,
|
|
180
|
+
metadata: {
|
|
181
|
+
...input.metadata,
|
|
182
|
+
...(input.reason ? { reason: input.reason.slice(0, 500) } : {})
|
|
183
|
+
}
|
|
184
|
+
}, { idempotencyKey: input.idempotencyKey }), input.paymentId));
|
|
185
|
+
}
|
|
186
|
+
createCheckout(input) {
|
|
187
|
+
return this.run('createCheckout', async () => {
|
|
188
|
+
const subscription = input.mode === 'subscription';
|
|
189
|
+
return toCheckout(await this.client.checkout.sessions.create({
|
|
190
|
+
mode: input.mode,
|
|
191
|
+
success_url: input.successUrl,
|
|
192
|
+
cancel_url: input.cancelUrl,
|
|
193
|
+
customer: input.customerId,
|
|
194
|
+
metadata: input.metadata,
|
|
195
|
+
line_items: [
|
|
196
|
+
subscription
|
|
197
|
+
? { price: input.priceId, quantity: input.quantity ?? 1 }
|
|
198
|
+
: {
|
|
199
|
+
quantity: 1,
|
|
200
|
+
price_data: {
|
|
201
|
+
currency: (input.currency ?? 'usd').toLowerCase(),
|
|
202
|
+
unit_amount: input.amount,
|
|
203
|
+
product_data: { name: input.description ?? 'Payment' }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
],
|
|
207
|
+
...(subscription
|
|
208
|
+
? {
|
|
209
|
+
subscription_data: {
|
|
210
|
+
metadata: input.metadata,
|
|
211
|
+
trial_period_days: input.trialDays || undefined
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
: {
|
|
215
|
+
payment_intent_data: {
|
|
216
|
+
capture_method: input.captureMethod,
|
|
217
|
+
description: input.description,
|
|
218
|
+
metadata: input.metadata
|
|
219
|
+
}
|
|
220
|
+
})
|
|
221
|
+
}, { idempotencyKey: input.idempotencyKey }));
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
getCheckout(checkoutId) {
|
|
225
|
+
return this.run('getCheckout', async () => toCheckout(await this.client.checkout.sessions.retrieve(checkoutId)));
|
|
226
|
+
}
|
|
227
|
+
expireCheckout(checkoutId) {
|
|
228
|
+
return this.run('expireCheckout', async () => {
|
|
229
|
+
// Only an open session can be expired, a paid or expired one is returned as it is
|
|
230
|
+
const session = await this.client.checkout.sessions.retrieve(checkoutId);
|
|
231
|
+
return toCheckout(session.status === 'open'
|
|
232
|
+
? await this.client.checkout.sessions.expire(checkoutId)
|
|
233
|
+
: session);
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
createSetup(customerId, idempotencyKey) {
|
|
237
|
+
return this.run('createSetup', async () => {
|
|
238
|
+
const setup = await this.client.setupIntents.create({
|
|
239
|
+
customer: customerId,
|
|
240
|
+
usage: 'off_session',
|
|
241
|
+
automatic_payment_methods: { enabled: true }
|
|
242
|
+
}, { idempotencyKey });
|
|
243
|
+
return {
|
|
244
|
+
id: setup.id,
|
|
245
|
+
status: setup.status === 'succeeded'
|
|
246
|
+
? 'succeeded'
|
|
247
|
+
: setup.status === 'canceled'
|
|
248
|
+
? 'canceled'
|
|
249
|
+
: 'pending',
|
|
250
|
+
nextAction: confirmAction(setup.client_secret),
|
|
251
|
+
paymentMethodId: idOf(setup.payment_method)
|
|
252
|
+
};
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
listPaymentMethods(customerId) {
|
|
256
|
+
return this.run('listPaymentMethods', async () => {
|
|
257
|
+
const methods = [];
|
|
258
|
+
for await (const method of this.client.paymentMethods.list({
|
|
259
|
+
customer: customerId,
|
|
260
|
+
limit: 100
|
|
261
|
+
})) {
|
|
262
|
+
methods.push(toPaymentMethod(method));
|
|
263
|
+
}
|
|
264
|
+
return methods;
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
detachPaymentMethod(paymentMethodId) {
|
|
268
|
+
return this.run('detachPaymentMethod', async () => {
|
|
269
|
+
await this.client.paymentMethods.detach(paymentMethodId);
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
setDefaultPaymentMethod(customerId, paymentMethodId) {
|
|
273
|
+
return this.run('setDefaultPaymentMethod', async () => {
|
|
274
|
+
await this.client.customers.update(customerId, {
|
|
275
|
+
invoice_settings: { default_payment_method: paymentMethodId }
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
createSubscription(input) {
|
|
280
|
+
return this.run('createSubscription', async () => toSubscription(await this.client.subscriptions.create({
|
|
281
|
+
customer: input.customerId,
|
|
282
|
+
items: [{ price: input.priceId, quantity: input.quantity ?? 1 }],
|
|
283
|
+
trial_period_days: input.trialDays || undefined,
|
|
284
|
+
default_payment_method: input.paymentMethodId,
|
|
285
|
+
// The first invoice is charged at once: a refused or unconfirmed payment leaves it incomplete
|
|
286
|
+
payment_behavior: 'allow_incomplete',
|
|
287
|
+
payment_settings: {
|
|
288
|
+
save_default_payment_method: 'on_subscription'
|
|
289
|
+
},
|
|
290
|
+
metadata: input.metadata,
|
|
291
|
+
expand: SUBSCRIPTION_EXPAND
|
|
292
|
+
}, { idempotencyKey: input.idempotencyKey })));
|
|
293
|
+
}
|
|
294
|
+
getSubscription(subscriptionId) {
|
|
295
|
+
return this.run('getSubscription', async () => toSubscription(await this.client.subscriptions.retrieve(subscriptionId, {
|
|
296
|
+
expand: SUBSCRIPTION_EXPAND
|
|
297
|
+
})));
|
|
298
|
+
}
|
|
299
|
+
updateSubscription(subscriptionId, update) {
|
|
300
|
+
return this.run('updateSubscription', async () => {
|
|
301
|
+
const changesItem = update.priceId !== undefined || update.quantity !== undefined;
|
|
302
|
+
const item = changesItem
|
|
303
|
+
? (await this.client.subscriptions.retrieve(subscriptionId)).items
|
|
304
|
+
.data[0]
|
|
305
|
+
: undefined;
|
|
306
|
+
return toSubscription(await this.client.subscriptions.update(subscriptionId, {
|
|
307
|
+
...(item
|
|
308
|
+
? {
|
|
309
|
+
items: [
|
|
310
|
+
{
|
|
311
|
+
id: item.id,
|
|
312
|
+
price: update.priceId,
|
|
313
|
+
quantity: update.quantity
|
|
314
|
+
}
|
|
315
|
+
],
|
|
316
|
+
proration_behavior: update.prorate === false ? 'none' : 'create_prorations'
|
|
317
|
+
}
|
|
318
|
+
: {}),
|
|
319
|
+
cancel_at_period_end: update.cancelAtPeriodEnd,
|
|
320
|
+
default_payment_method: update.paymentMethodId,
|
|
321
|
+
metadata: update.metadata,
|
|
322
|
+
expand: SUBSCRIPTION_EXPAND
|
|
323
|
+
}));
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
cancelSubscription(subscriptionId) {
|
|
327
|
+
return this.run('cancelSubscription', async () => toSubscription(await this.client.subscriptions.cancel(subscriptionId)));
|
|
328
|
+
}
|
|
329
|
+
getInvoice(invoiceId) {
|
|
330
|
+
return this.run('getInvoice', async () => toInvoice(await this.client.invoices.retrieve(invoiceId, {
|
|
331
|
+
expand: ['payments']
|
|
332
|
+
})));
|
|
333
|
+
}
|
|
334
|
+
listPrices() {
|
|
335
|
+
return this.run('listPrices', async () => {
|
|
336
|
+
const prices = [];
|
|
337
|
+
for await (const price of this.client.prices.list({
|
|
338
|
+
type: 'recurring',
|
|
339
|
+
limit: 100,
|
|
340
|
+
expand: ['data.product']
|
|
341
|
+
})) {
|
|
342
|
+
const { recurring, product } = price;
|
|
343
|
+
const interval = PLAN_INTERVALS[recurring?.interval ?? ''];
|
|
344
|
+
if (price.unit_amount === null || !recurring || !interval) {
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
prices.push({
|
|
348
|
+
id: price.id,
|
|
349
|
+
amount: price.unit_amount,
|
|
350
|
+
currency: price.currency.toUpperCase(),
|
|
351
|
+
interval,
|
|
352
|
+
intervalCount: recurring.interval_count,
|
|
353
|
+
active: price.active,
|
|
354
|
+
key: price.lookup_key ?? undefined,
|
|
355
|
+
name: price.nickname ??
|
|
356
|
+
(typeof product === 'object' && 'name' in product
|
|
357
|
+
? product.name
|
|
358
|
+
: undefined),
|
|
359
|
+
trialDays: recurring.trial_period_days ?? undefined
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
return prices;
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
createPortalSession(customerId, returnUrl) {
|
|
366
|
+
return this.run('createPortalSession', async () => {
|
|
367
|
+
const session = await this.client.billingPortal.sessions.create({
|
|
368
|
+
customer: customerId,
|
|
369
|
+
return_url: returnUrl
|
|
370
|
+
});
|
|
371
|
+
return { url: session.url };
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
async verifyWebhook(body, headers, tolerance) {
|
|
375
|
+
const { name, webhookSecret } = this.config;
|
|
376
|
+
const signature = [headers['stripe-signature']].flat()[0];
|
|
377
|
+
if (!webhookSecret) {
|
|
378
|
+
logger.error({ gateway: name }, `Webhook refused, set ${(0, payments_1.gatewayConfigKey)(name, 'webhookSecret')}`);
|
|
379
|
+
throw invalidWebhook(name, 'No webhook secret is configured');
|
|
380
|
+
}
|
|
381
|
+
if (!signature) {
|
|
382
|
+
throw invalidWebhook(name, 'The Stripe-Signature header is missing');
|
|
383
|
+
}
|
|
384
|
+
let event;
|
|
385
|
+
try {
|
|
386
|
+
event = await this.client.webhooks.constructEventAsync(body, signature, webhookSecret, Math.max(1, Math.round(tolerance / 1000)));
|
|
387
|
+
}
|
|
388
|
+
catch (e) {
|
|
389
|
+
throw invalidWebhook(name, e.message);
|
|
390
|
+
}
|
|
391
|
+
return {
|
|
392
|
+
id: event.id,
|
|
393
|
+
type: event.type,
|
|
394
|
+
occurredAt: new Date(event.created * 1000),
|
|
395
|
+
livemode: event.livemode,
|
|
396
|
+
data: await this.eventData(event)
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
async checkHealth() {
|
|
400
|
+
try {
|
|
401
|
+
await this.client.balance.retrieve();
|
|
402
|
+
return { success: true };
|
|
403
|
+
}
|
|
404
|
+
catch (e) {
|
|
405
|
+
return { success: false, message: e.message };
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
/** @internal */
|
|
409
|
+
async eventData(event) {
|
|
410
|
+
switch (event.type) {
|
|
411
|
+
case 'payment_intent.succeeded':
|
|
412
|
+
case 'payment_intent.payment_failed':
|
|
413
|
+
case 'payment_intent.canceled':
|
|
414
|
+
case 'payment_intent.processing':
|
|
415
|
+
case 'payment_intent.requires_action':
|
|
416
|
+
case 'payment_intent.amount_capturable_updated':
|
|
417
|
+
return {
|
|
418
|
+
kind: 'payment',
|
|
419
|
+
payment: await this.toPayment(event.data.object)
|
|
420
|
+
};
|
|
421
|
+
case 'refund.created':
|
|
422
|
+
case 'refund.updated':
|
|
423
|
+
case 'refund.failed': {
|
|
424
|
+
const paymentId = idOf(event.data.object.payment_intent);
|
|
425
|
+
return paymentId
|
|
426
|
+
? { kind: 'refund', refund: toRefund(event.data.object, paymentId) }
|
|
427
|
+
: { kind: 'ignored' };
|
|
428
|
+
}
|
|
429
|
+
case 'charge.dispute.created':
|
|
430
|
+
case 'charge.dispute.updated':
|
|
431
|
+
case 'charge.dispute.closed':
|
|
432
|
+
case 'charge.dispute.funds_withdrawn':
|
|
433
|
+
case 'charge.dispute.funds_reinstated': {
|
|
434
|
+
const dispute = toDispute(event.data.object);
|
|
435
|
+
return dispute ? { kind: 'dispute', dispute } : { kind: 'ignored' };
|
|
436
|
+
}
|
|
437
|
+
case 'payment_method.attached':
|
|
438
|
+
case 'payment_method.updated':
|
|
439
|
+
case 'payment_method.automatically_updated':
|
|
440
|
+
return {
|
|
441
|
+
kind: 'paymentMethod',
|
|
442
|
+
paymentMethod: toPaymentMethod(event.data.object)
|
|
443
|
+
};
|
|
444
|
+
case 'payment_method.detached':
|
|
445
|
+
return {
|
|
446
|
+
kind: 'paymentMethod',
|
|
447
|
+
paymentMethod: toPaymentMethod(event.data.object),
|
|
448
|
+
detached: true
|
|
449
|
+
};
|
|
450
|
+
case 'customer.subscription.created':
|
|
451
|
+
case 'customer.subscription.updated':
|
|
452
|
+
case 'customer.subscription.deleted':
|
|
453
|
+
case 'customer.subscription.paused':
|
|
454
|
+
case 'customer.subscription.resumed':
|
|
455
|
+
return {
|
|
456
|
+
kind: 'subscription',
|
|
457
|
+
subscription: toSubscription(event.data.object)
|
|
458
|
+
};
|
|
459
|
+
case 'customer.subscription.trial_will_end':
|
|
460
|
+
return {
|
|
461
|
+
kind: 'subscription',
|
|
462
|
+
subscription: toSubscription(event.data.object),
|
|
463
|
+
trialWillEnd: true
|
|
464
|
+
};
|
|
465
|
+
case 'invoice.finalized':
|
|
466
|
+
case 'invoice.paid':
|
|
467
|
+
case 'invoice.payment_failed':
|
|
468
|
+
case 'invoice.voided':
|
|
469
|
+
case 'invoice.marked_uncollectible': {
|
|
470
|
+
const invoice = toInvoice(event.data.object);
|
|
471
|
+
return invoice.customerId
|
|
472
|
+
? { kind: 'invoice', invoice }
|
|
473
|
+
: { kind: 'ignored' };
|
|
474
|
+
}
|
|
475
|
+
case 'checkout.session.completed':
|
|
476
|
+
case 'checkout.session.expired':
|
|
477
|
+
case 'checkout.session.async_payment_succeeded':
|
|
478
|
+
case 'checkout.session.async_payment_failed':
|
|
479
|
+
return { kind: 'checkout', checkout: toCheckout(event.data.object) };
|
|
480
|
+
case 'customer.deleted':
|
|
481
|
+
return {
|
|
482
|
+
kind: 'customer',
|
|
483
|
+
customerId: event.data.object.id,
|
|
484
|
+
deleted: true
|
|
485
|
+
};
|
|
486
|
+
default:
|
|
487
|
+
return { kind: 'ignored' };
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Normalizes a PaymentIntent. A payment the application did not create is the one of an invoice, whose
|
|
492
|
+
* subscription is read with it.
|
|
493
|
+
*
|
|
494
|
+
* @internal
|
|
495
|
+
*/
|
|
496
|
+
async toPayment(intent, withInvoice = false) {
|
|
497
|
+
const charge = typeof intent.latest_charge === 'object' ? intent.latest_charge : null;
|
|
498
|
+
const method = typeof intent.payment_method === 'object' ? intent.payment_method : null;
|
|
499
|
+
const error = intent.last_payment_error;
|
|
500
|
+
const failed = intent.status === 'requires_payment_method' && !!error;
|
|
501
|
+
const status = failed
|
|
502
|
+
? 'failed'
|
|
503
|
+
: (PAYMENT_STATUSES[intent.status] ?? 'pending');
|
|
504
|
+
const customerId = idOf(intent.customer);
|
|
505
|
+
const transaction = charge?.balance_transaction;
|
|
506
|
+
const payment = {
|
|
507
|
+
id: intent.id,
|
|
508
|
+
status,
|
|
509
|
+
amount: intent.amount,
|
|
510
|
+
currency: intent.currency.toUpperCase(),
|
|
511
|
+
amountCaptured: intent.amount_received,
|
|
512
|
+
amountRefunded: charge?.amount_refunded ?? 0,
|
|
513
|
+
livemode: intent.livemode,
|
|
514
|
+
nextAction: paymentAction(intent, status),
|
|
515
|
+
metadata: intent.metadata ?? {},
|
|
516
|
+
customerId,
|
|
517
|
+
paymentMethodId: idOf(intent.payment_method),
|
|
518
|
+
paymentMethod: method
|
|
519
|
+
? { ...toPaymentMethod(method), customerId: idOf(method.customer) }
|
|
520
|
+
: undefined,
|
|
521
|
+
chargeId: idOf(intent.latest_charge),
|
|
522
|
+
fee: transaction && typeof transaction === 'object'
|
|
523
|
+
? transaction.fee
|
|
524
|
+
: undefined,
|
|
525
|
+
failureCode: failed ? (error?.decline_code ?? error?.code) : undefined,
|
|
526
|
+
failureMessage: failed ? error?.message : undefined,
|
|
527
|
+
receiptUrl: charge?.receipt_url ?? undefined
|
|
528
|
+
};
|
|
529
|
+
if (withInvoice && customerId && !payment.metadata[payments_1.PAYMENT_METADATA_KEY]) {
|
|
530
|
+
const { data } = await this.client.invoicePayments.list({
|
|
531
|
+
payment: { type: 'payment_intent', payment_intent: intent.id },
|
|
532
|
+
limit: 1,
|
|
533
|
+
expand: ['data.invoice']
|
|
534
|
+
});
|
|
535
|
+
const invoice = data[0]?.invoice;
|
|
536
|
+
if (invoice && typeof invoice === 'object' && !invoice.deleted) {
|
|
537
|
+
payment.invoiceId = invoice.id;
|
|
538
|
+
payment.subscriptionId = idOf(invoice.parent?.subscription_details?.subscription);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return payment;
|
|
542
|
+
}
|
|
543
|
+
/** Runs a call of the SDK, its errors turned into the ones of the payments. @internal */
|
|
544
|
+
async run(operation, call) {
|
|
545
|
+
try {
|
|
546
|
+
return await call();
|
|
547
|
+
}
|
|
548
|
+
catch (e) {
|
|
549
|
+
throw this.toError(e, operation);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/** @internal */
|
|
553
|
+
toError(error, operation) {
|
|
554
|
+
const { errors } = stripe_1.default;
|
|
555
|
+
if (!(error instanceof errors.StripeError)) {
|
|
556
|
+
return error;
|
|
557
|
+
}
|
|
558
|
+
const details = {
|
|
559
|
+
gateway: this.config.name,
|
|
560
|
+
operation,
|
|
561
|
+
status: error.statusCode,
|
|
562
|
+
providerCode: error.code ?? error.type
|
|
563
|
+
};
|
|
564
|
+
const options = { cause: error };
|
|
565
|
+
if (error instanceof errors.StripeCardError) {
|
|
566
|
+
return new common_1.PaymentError(common_1.ErrorCode.PaymentDeclined, error.message, { ...details, declineCode: error.decline_code }, options);
|
|
567
|
+
}
|
|
568
|
+
if (error instanceof errors.StripeInvalidRequestError ||
|
|
569
|
+
error instanceof errors.StripeIdempotencyError) {
|
|
570
|
+
return new common_1.PaymentError(common_1.ErrorCode.PaymentRequestInvalid, `Stripe rejected the request: ${error.message}`, { ...details, param: error.param }, options);
|
|
571
|
+
}
|
|
572
|
+
const unavailable = error instanceof errors.StripeRateLimitError ||
|
|
573
|
+
error instanceof errors.StripeConnectionError ||
|
|
574
|
+
(error.statusCode ?? 0) >= 500;
|
|
575
|
+
return new common_1.PaymentError(unavailable
|
|
576
|
+
? common_1.ErrorCode.PaymentGatewayUnavailable
|
|
577
|
+
: common_1.ErrorCode.PaymentGatewayFailed, `Stripe ${operation} failed: ${error.message}`, details, options);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
exports.StripeGateway = StripeGateway;
|
|
581
|
+
function idOf(value) {
|
|
582
|
+
return typeof value === 'string' ? value : (value?.id ?? undefined);
|
|
583
|
+
}
|
|
584
|
+
function toDate(seconds) {
|
|
585
|
+
return seconds ? new Date(seconds * 1000) : undefined;
|
|
586
|
+
}
|
|
587
|
+
function confirmAction(secret) {
|
|
588
|
+
return secret ? { type: 'confirm', clientSecret: secret } : { type: 'none' };
|
|
589
|
+
}
|
|
590
|
+
/** What the client does with a PaymentIntent: follow the redirect of its bank, or confirm it with Stripe.js. */
|
|
591
|
+
function paymentAction(intent, status) {
|
|
592
|
+
const redirect = intent.next_action?.redirect_to_url?.url;
|
|
593
|
+
if (status === 'requiresAction' && redirect) {
|
|
594
|
+
return { type: 'redirect', url: redirect };
|
|
595
|
+
}
|
|
596
|
+
return ['pending', 'requiresAction', 'failed'].includes(status)
|
|
597
|
+
? confirmAction(intent.client_secret)
|
|
598
|
+
: { type: 'none' };
|
|
599
|
+
}
|
|
600
|
+
function invalidWebhook(gateway, reason) {
|
|
601
|
+
return new common_1.PaymentError(common_1.ErrorCode.PaymentWebhookInvalid, `Invalid Stripe webhook: ${reason}`, { gateway, reason });
|
|
602
|
+
}
|
|
603
|
+
function toCustomer(customer) {
|
|
604
|
+
return {
|
|
605
|
+
id: customer.id,
|
|
606
|
+
email: customer.email ?? undefined,
|
|
607
|
+
name: customer.name ?? undefined
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
function toPaymentMethod(method) {
|
|
611
|
+
const { card } = method;
|
|
612
|
+
return {
|
|
613
|
+
id: method.id,
|
|
614
|
+
type: method.type,
|
|
615
|
+
customerId: idOf(method.customer),
|
|
616
|
+
brand: card?.brand,
|
|
617
|
+
last4: card?.last4,
|
|
618
|
+
expMonth: card?.exp_month,
|
|
619
|
+
expYear: card?.exp_year,
|
|
620
|
+
fingerprint: card?.fingerprint ?? undefined,
|
|
621
|
+
country: card?.country ?? undefined
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
function toRefund(refund, paymentId) {
|
|
625
|
+
return {
|
|
626
|
+
id: refund.id,
|
|
627
|
+
paymentId,
|
|
628
|
+
amount: refund.amount,
|
|
629
|
+
currency: refund.currency.toUpperCase(),
|
|
630
|
+
status: REFUND_STATUSES[refund.status ?? ''] ?? 'pending',
|
|
631
|
+
reason: refund.metadata?.reason ?? refund.reason ?? undefined,
|
|
632
|
+
failureReason: refund.failure_reason
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
function toDispute(dispute) {
|
|
636
|
+
const paymentId = idOf(dispute.payment_intent);
|
|
637
|
+
return paymentId
|
|
638
|
+
? {
|
|
639
|
+
id: dispute.id,
|
|
640
|
+
paymentId,
|
|
641
|
+
amount: dispute.amount,
|
|
642
|
+
currency: dispute.currency.toUpperCase(),
|
|
643
|
+
status: DISPUTE_STATUSES[dispute.status] ?? 'pending',
|
|
644
|
+
reason: dispute.reason
|
|
645
|
+
}
|
|
646
|
+
: undefined;
|
|
647
|
+
}
|
|
648
|
+
function toCheckout(session) {
|
|
649
|
+
return {
|
|
650
|
+
id: session.id,
|
|
651
|
+
status: session.status === 'complete'
|
|
652
|
+
? 'complete'
|
|
653
|
+
: session.status === 'expired'
|
|
654
|
+
? 'expired'
|
|
655
|
+
: 'open',
|
|
656
|
+
url: session.url ?? undefined,
|
|
657
|
+
customerId: idOf(session.customer),
|
|
658
|
+
paymentId: idOf(session.payment_intent),
|
|
659
|
+
subscriptionId: idOf(session.subscription),
|
|
660
|
+
metadata: session.metadata ?? undefined
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
function toSubscription(subscription) {
|
|
664
|
+
const item = subscription.items.data[0];
|
|
665
|
+
const invoice = typeof subscription.latest_invoice === 'object'
|
|
666
|
+
? subscription.latest_invoice
|
|
667
|
+
: null;
|
|
668
|
+
const status = SUBSCRIPTION_STATUSES[subscription.status] ?? 'incomplete';
|
|
669
|
+
return {
|
|
670
|
+
id: subscription.id,
|
|
671
|
+
status,
|
|
672
|
+
customerId: idOf(subscription.customer) ?? '',
|
|
673
|
+
priceId: item?.price.id ?? '',
|
|
674
|
+
quantity: item?.quantity ?? 1,
|
|
675
|
+
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
676
|
+
livemode: subscription.livemode,
|
|
677
|
+
nextAction: status === 'incomplete'
|
|
678
|
+
? confirmAction(invoice?.confirmation_secret?.client_secret)
|
|
679
|
+
: { type: 'none' },
|
|
680
|
+
metadata: subscription.metadata ?? {},
|
|
681
|
+
currentPeriodStart: toDate(item?.current_period_start),
|
|
682
|
+
currentPeriodEnd: toDate(item?.current_period_end),
|
|
683
|
+
trialEnd: toDate(subscription.trial_end),
|
|
684
|
+
canceledAt: toDate(subscription.canceled_at),
|
|
685
|
+
endedAt: toDate(subscription.ended_at),
|
|
686
|
+
latestInvoiceId: idOf(subscription.latest_invoice)
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
function toInvoice(invoice) {
|
|
690
|
+
const payment = invoice.payments?.data.find((entry) => entry.payment.payment_intent);
|
|
691
|
+
const status = invoice.status;
|
|
692
|
+
return {
|
|
693
|
+
id: invoice.id,
|
|
694
|
+
status: status ?? 'draft',
|
|
695
|
+
customerId: idOf(invoice.customer) ?? '',
|
|
696
|
+
amountDue: invoice.amount_due,
|
|
697
|
+
amountPaid: invoice.amount_paid,
|
|
698
|
+
currency: invoice.currency.toUpperCase(),
|
|
699
|
+
attemptCount: invoice.attempt_count,
|
|
700
|
+
livemode: invoice.livemode,
|
|
701
|
+
subscriptionId: idOf(invoice.parent?.subscription_details?.subscription),
|
|
702
|
+
paymentId: idOf(payment?.payment.payment_intent),
|
|
703
|
+
number: invoice.number ?? undefined,
|
|
704
|
+
periodStart: toDate(invoice.period_start),
|
|
705
|
+
periodEnd: toDate(invoice.period_end),
|
|
706
|
+
nextAttemptAt: toDate(invoice.next_payment_attempt),
|
|
707
|
+
hostedUrl: invoice.hosted_invoice_url ?? undefined,
|
|
708
|
+
pdfUrl: invoice.invoice_pdf ?? undefined
|
|
709
|
+
};
|
|
710
|
+
}
|