@appweaver/payments 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.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -2
  3. package/config.d.ts +77 -0
  4. package/config.js +118 -0
  5. package/gateway/fake-gateway.d.ts +144 -0
  6. package/gateway/fake-gateway.js +805 -0
  7. package/gateway/gateway-registry.d.ts +99 -0
  8. package/gateway/gateway-registry.js +275 -0
  9. package/gateway/payment-gateway.d.ts +68 -0
  10. package/gateway/payment-gateway.js +82 -0
  11. package/index.d.ts +16 -0
  12. package/index.js +51 -0
  13. package/locales/en.json +47 -0
  14. package/maintenance/payment-maintenance-jobs.d.ts +5 -0
  15. package/maintenance/payment-maintenance-jobs.js +38 -0
  16. package/module.d.ts +8 -0
  17. package/module.js +85 -0
  18. package/package.json +67 -3
  19. package/resources/model-util.d.ts +40 -0
  20. package/resources/model-util.js +30 -0
  21. package/resources/payment/model.d.ts +2 -0
  22. package/resources/payment/model.js +106 -0
  23. package/resources/payment-customer/model.d.ts +2 -0
  24. package/resources/payment-customer/model.js +53 -0
  25. package/resources/payment-event/model.d.ts +2 -0
  26. package/resources/payment-event/model.js +31 -0
  27. package/resources/payment-invoice/model.d.ts +2 -0
  28. package/resources/payment-invoice/model.js +55 -0
  29. package/resources/payment-method/model.d.ts +2 -0
  30. package/resources/payment-method/model.js +37 -0
  31. package/resources/payment-plan/model.d.ts +2 -0
  32. package/resources/payment-plan/model.js +37 -0
  33. package/resources/payment-subscription/model.d.ts +2 -0
  34. package/resources/payment-subscription/model.js +82 -0
  35. package/resources/payment-transaction/model.d.ts +2 -0
  36. package/resources/payment-transaction/model.js +43 -0
  37. package/resources/payment-webhook-event/model.d.ts +2 -0
  38. package/resources/payment-webhook-event/model.js +32 -0
  39. package/resources/policies.d.ts +15 -0
  40. package/resources/policies.js +36 -0
  41. package/resources/services.d.ts +6 -0
  42. package/resources/services.js +19 -0
  43. package/resources/subscriptions.d.ts +9 -0
  44. package/resources/subscriptions.js +30 -0
  45. package/resources.d.ts +8 -0
  46. package/resources.js +34 -0
  47. package/service/payment-emails.d.ts +12 -0
  48. package/service/payment-emails.js +145 -0
  49. package/service/payment-events.d.ts +90 -0
  50. package/service/payment-events.js +472 -0
  51. package/service/payment-handlers.d.ts +26 -0
  52. package/service/payment-handlers.js +42 -0
  53. package/service/payment-store.d.ts +50 -0
  54. package/service/payment-store.js +95 -0
  55. package/service/payment-sync.d.ts +113 -0
  56. package/service/payment-sync.js +745 -0
  57. package/service/payments-service.d.ts +307 -0
  58. package/service/payments-service.js +747 -0
  59. package/service/subscriptions-service.d.ts +178 -0
  60. package/service/subscriptions-service.js +433 -0
  61. package/tasks/payments-replay.d.ts +10 -0
  62. package/tasks/payments-replay.js +36 -0
  63. package/tasks/payments-sync-plans.d.ts +10 -0
  64. package/tasks/payments-sync-plans.js +24 -0
  65. package/templates/emails/payment-action-required.html.hbs +28 -0
  66. package/templates/emails/payment-action-required.subject.hbs +1 -0
  67. package/templates/emails/payment-failed.html.hbs +37 -0
  68. package/templates/emails/payment-failed.subject.hbs +1 -0
  69. package/templates/emails/payment-receipt.html.hbs +45 -0
  70. package/templates/emails/payment-receipt.subject.hbs +1 -0
  71. package/templates/emails/payment-refunded.html.hbs +37 -0
  72. package/templates/emails/payment-refunded.subject.hbs +1 -0
  73. package/templates/emails/subscription-canceled.html.hbs +24 -0
  74. package/templates/emails/subscription-canceled.subject.hbs +1 -0
  75. package/templates/emails/subscription-trial-ending.html.hbs +25 -0
  76. package/templates/emails/subscription-trial-ending.subject.hbs +1 -0
  77. package/templates/layouts/email.html.hbs +36 -0
  78. package/templates/partials/email-button.html.hbs +15 -0
  79. package/tsconfig.build.tsbuildinfo +1 -0
  80. package/types.d.ts +488 -0
  81. package/types.js +2 -0
  82. package/utils/money-util.d.ts +61 -0
  83. package/utils/money-util.js +124 -0
  84. package/utils/status-util.d.ts +29 -0
  85. package/utils/status-util.js +93 -0
  86. package/utils/telemetry.d.ts +16 -0
  87. package/utils/telemetry.js +69 -0
  88. package/web/payment-routes.d.ts +7 -0
  89. package/web/payment-routes.js +410 -0
  90. package/web/payment-schemas.d.ts +70 -0
  91. package/web/payment-schemas.js +101 -0
@@ -0,0 +1,805 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FakePaymentGateway = exports.FAKE_ACTION_METHOD = exports.FAKE_DECLINED_METHOD = void 0;
4
+ exports.onFakePaymentEvent = onFakePaymentEvent;
5
+ exports.setFakeCheckoutUrl = setFakeCheckoutUrl;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const common_1 = require("@appweaver/common");
8
+ const payment_gateway_1 = require("./payment-gateway");
9
+ /** A saved payment method of the fake gateway refused when charged. */
10
+ exports.FAKE_DECLINED_METHOD = 'pm_fake_declined';
11
+ /** A saved payment method of the fake gateway whose payments wait for the customer, like a card with 3D Secure. */
12
+ exports.FAKE_ACTION_METHOD = 'pm_fake_action';
13
+ const SIGNATURE_HEADER = 'x-fake-signature';
14
+ const TIMESTAMP_HEADER = 'x-fake-timestamp';
15
+ const DEFAULT_SECRET = 'fake';
16
+ const DAY = 86_400_000;
17
+ const INTERVAL_DAYS = {
18
+ day: 1,
19
+ week: 7,
20
+ month: 30,
21
+ year: 365
22
+ };
23
+ const FAKE_LISTENER = Symbol.for('appweaver.FakePaymentListener');
24
+ const FAKE_CHECKOUT_URL = Symbol.for('appweaver.FakeCheckoutUrl');
25
+ const globals = globalThis;
26
+ /**
27
+ * Sets the function receiving the events of the fake gateways, in place of a webhook request. The payment module
28
+ * sets its own, so the events of a fake gateway are processed like the webhooks of a real one.
29
+ *
30
+ * @param {FakeEventListener | undefined} listener - The function, or `undefined` to remove it.
31
+ */
32
+ function onFakePaymentEvent(listener) {
33
+ globals[FAKE_LISTENER] = listener;
34
+ }
35
+ /**
36
+ * Sets the base URL of the checkout pages of the fake gateways, the ID of a checkout appended to it.
37
+ *
38
+ * @param {string | undefined} url - The base URL, or `undefined` for the default one.
39
+ */
40
+ function setFakeCheckoutUrl(url) {
41
+ globals[FAKE_CHECKOUT_URL] = url;
42
+ }
43
+ /**
44
+ * The built-in `fake` gateway, calling no provider and moving no money, for the tests and the development without
45
+ * an account. A payment with a saved payment method is paid at once ({@link FAKE_DECLINED_METHOD} refuses it,
46
+ * {@link FAKE_ACTION_METHOD} holds it), any other one waits for `confirmPayment`, standing for the customer and the
47
+ * client library of a provider. Every change emits the event a provider would send to the webhook endpoint.
48
+ */
49
+ class FakePaymentGateway extends payment_gateway_1.PaymentGateway {
50
+ capabilities = [
51
+ 'checkout',
52
+ 'manualCapture',
53
+ 'savedMethods',
54
+ 'subscriptions',
55
+ 'portal',
56
+ 'prices'
57
+ ];
58
+ /** The events emitted so far, in their order. */
59
+ events = [];
60
+ /** @internal */
61
+ _customers = new Map();
62
+ /** @internal */
63
+ _defaultMethods = new Map();
64
+ /** @internal */
65
+ _methods = new Map();
66
+ /** @internal */
67
+ _payments = new Map();
68
+ /** @internal */
69
+ _saveMethod = new Set();
70
+ /** The payments authorized only, captured later. @internal */
71
+ _manual = new Set();
72
+ /** @internal */
73
+ _refunds = new Map();
74
+ /** @internal */
75
+ _checkouts = new Map();
76
+ /** @internal */
77
+ _setups = new Map();
78
+ /** @internal */
79
+ _prices = new Map();
80
+ /** @internal */
81
+ _subscriptions = new Map();
82
+ /** @internal */
83
+ _invoices = new Map();
84
+ /** @internal */
85
+ _idempotent = new Map();
86
+ /** @internal */
87
+ _sequence = 0;
88
+ /** @internal */
89
+ _delivery = Promise.resolve();
90
+ async createCustomer(input) {
91
+ const customer = {
92
+ id: this.id('cus'),
93
+ email: input.email,
94
+ name: input.name
95
+ };
96
+ this._customers.set(customer.id, customer);
97
+ return { ...customer };
98
+ }
99
+ async updateCustomer(customerId, input) {
100
+ const customer = this.find(this._customers, customerId, 'customer');
101
+ Object.assign(customer, {
102
+ email: input.email ?? customer.email,
103
+ name: input.name ?? customer.name
104
+ });
105
+ return { ...customer };
106
+ }
107
+ async deleteCustomer(customerId) {
108
+ this._customers.delete(customerId);
109
+ }
110
+ async createPayment(input) {
111
+ return this.once(input.idempotencyKey, () => {
112
+ if (input.paymentMethodId === exports.FAKE_DECLINED_METHOD) {
113
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentDeclined, 'The fake gateway declined the payment method', {
114
+ gateway: this.config.name,
115
+ operation: 'createPayment',
116
+ providerCode: 'card_declined',
117
+ declineCode: 'generic_decline'
118
+ });
119
+ }
120
+ const payment = this.newPayment(input);
121
+ if (input.savePaymentMethod) {
122
+ this._saveMethod.add(payment.id);
123
+ }
124
+ if (input.paymentMethodId === exports.FAKE_ACTION_METHOD) {
125
+ this.settle(payment, 'requiresAction');
126
+ }
127
+ else if (input.paymentMethodId) {
128
+ payment.paymentMethod = this._methods.get(input.paymentMethodId);
129
+ this.settle(payment, 'succeeded');
130
+ }
131
+ return payment;
132
+ });
133
+ }
134
+ async getPayment(paymentId) {
135
+ return { ...this.find(this._payments, paymentId, 'payment') };
136
+ }
137
+ async capturePayment(paymentId, amount) {
138
+ const payment = this.find(this._payments, paymentId, 'payment');
139
+ if (payment.status !== 'authorized') {
140
+ throw this.invalid('capturePayment', 'The payment is not authorized');
141
+ }
142
+ payment.status = 'succeeded';
143
+ payment.amountCaptured = Math.min(amount ?? payment.amount, payment.amount);
144
+ this.emit('payment.captured', { kind: 'payment', payment: { ...payment } });
145
+ return { ...payment };
146
+ }
147
+ async cancelPayment(paymentId) {
148
+ const payment = this.find(this._payments, paymentId, 'payment');
149
+ if (payment.status === 'succeeded' || payment.status === 'canceled') {
150
+ throw this.invalid('cancelPayment', `The payment is ${payment.status}`);
151
+ }
152
+ payment.status = 'canceled';
153
+ payment.nextAction = { type: 'none' };
154
+ this.emit('payment.canceled', { kind: 'payment', payment: { ...payment } });
155
+ return { ...payment };
156
+ }
157
+ async refundPayment(input) {
158
+ return this.once(input.idempotencyKey, () => {
159
+ const payment = this.find(this._payments, input.paymentId, 'payment');
160
+ const refundable = payment.amountCaptured - payment.amountRefunded;
161
+ const amount = input.amount ?? refundable;
162
+ if (payment.status !== 'succeeded' ||
163
+ amount <= 0 ||
164
+ amount > refundable) {
165
+ throw this.invalid('refundPayment', 'The amount cannot be refunded');
166
+ }
167
+ const refund = {
168
+ id: this.id('re'),
169
+ paymentId: payment.id,
170
+ amount,
171
+ currency: payment.currency,
172
+ status: 'succeeded',
173
+ reason: input.reason
174
+ };
175
+ payment.amountRefunded += amount;
176
+ this._refunds.set(refund.id, refund);
177
+ this.emit('refund.succeeded', { kind: 'refund', refund: { ...refund } });
178
+ return { ...refund };
179
+ });
180
+ }
181
+ async createCheckout(input) {
182
+ return this.once(input.idempotencyKey, () => {
183
+ if (input.mode === 'subscription') {
184
+ this.find(this._prices, input.priceId ?? '', 'price');
185
+ }
186
+ const id = this.id('cs');
187
+ const checkout = {
188
+ id,
189
+ status: 'open',
190
+ url: `${globals[FAKE_CHECKOUT_URL] ?? `${common_1.appConfig.HOSTNAME}/payments/fake/checkout`}/${this.config.name}/${id}`,
191
+ customerId: input.customerId,
192
+ metadata: input.metadata,
193
+ input
194
+ };
195
+ this._checkouts.set(id, checkout);
196
+ return publicCheckout(checkout);
197
+ });
198
+ }
199
+ async getCheckout(checkoutId) {
200
+ return publicCheckout(this.find(this._checkouts, checkoutId, 'checkout'));
201
+ }
202
+ async expireCheckout(checkoutId) {
203
+ const checkout = this.find(this._checkouts, checkoutId, 'checkout');
204
+ if (checkout.status === 'open') {
205
+ checkout.status = 'expired';
206
+ checkout.url = undefined;
207
+ this.emit('checkout.expired', {
208
+ kind: 'checkout',
209
+ checkout: publicCheckout(checkout)
210
+ });
211
+ }
212
+ return publicCheckout(checkout);
213
+ }
214
+ async createSetup(customerId) {
215
+ this.find(this._customers, customerId, 'customer');
216
+ const id = this.id('seti');
217
+ const setup = {
218
+ id,
219
+ status: 'pending',
220
+ nextAction: this.confirmAction(id),
221
+ customerId
222
+ };
223
+ this._setups.set(id, setup);
224
+ return publicSetup(setup);
225
+ }
226
+ async listPaymentMethods(customerId) {
227
+ return [...this._methods.values()]
228
+ .filter((method) => method.customerId === customerId)
229
+ .map((method) => ({ ...method }));
230
+ }
231
+ async detachPaymentMethod(paymentMethodId) {
232
+ const method = this.find(this._methods, paymentMethodId, 'payment method');
233
+ this._methods.delete(paymentMethodId);
234
+ this.emit('payment_method.detached', {
235
+ kind: 'paymentMethod',
236
+ paymentMethod: { ...method },
237
+ detached: true
238
+ });
239
+ }
240
+ async setDefaultPaymentMethod(customerId, paymentMethodId) {
241
+ this.find(this._methods, paymentMethodId, 'payment method');
242
+ this._defaultMethods.set(customerId, paymentMethodId);
243
+ }
244
+ async createSubscription(input) {
245
+ return this.once(input.idempotencyKey, () => {
246
+ this.find(this._customers, input.customerId, 'customer');
247
+ const price = this.find(this._prices, input.priceId, 'price');
248
+ const now = Date.now();
249
+ const trialDays = input.trialDays ?? price.trialDays ?? 0;
250
+ const methodId = input.paymentMethodId ??
251
+ this._defaultMethods.get(input.customerId) ??
252
+ [...this._methods.values()].find((method) => method.customerId === input.customerId)?.id;
253
+ const subscription = {
254
+ id: this.id('sub'),
255
+ status: 'incomplete',
256
+ customerId: input.customerId,
257
+ priceId: price.id,
258
+ quantity: input.quantity ?? 1,
259
+ cancelAtPeriodEnd: false,
260
+ livemode: false,
261
+ nextAction: { type: 'none' },
262
+ metadata: input.metadata ?? {},
263
+ currentPeriodStart: new Date(now),
264
+ currentPeriodEnd: new Date(now + (trialDays || periodDays(price)) * DAY)
265
+ };
266
+ this._subscriptions.set(subscription.id, subscription);
267
+ if (trialDays > 0) {
268
+ subscription.status = 'trialing';
269
+ subscription.trialEnd = subscription.currentPeriodEnd;
270
+ this.emitSubscription('subscription.created', subscription);
271
+ }
272
+ else {
273
+ const payment = this.bill(subscription, methodId);
274
+ subscription.nextAction = payment.nextAction;
275
+ this.emitSubscription('subscription.created', subscription);
276
+ }
277
+ return subscription;
278
+ });
279
+ }
280
+ async getSubscription(subscriptionId) {
281
+ return {
282
+ ...this.find(this._subscriptions, subscriptionId, 'subscription')
283
+ };
284
+ }
285
+ async updateSubscription(subscriptionId, update) {
286
+ const subscription = this.find(this._subscriptions, subscriptionId, 'subscription');
287
+ if (update.priceId) {
288
+ subscription.priceId = this.find(this._prices, update.priceId, 'price').id;
289
+ }
290
+ subscription.quantity = update.quantity ?? subscription.quantity;
291
+ subscription.cancelAtPeriodEnd =
292
+ update.cancelAtPeriodEnd ?? subscription.cancelAtPeriodEnd;
293
+ subscription.metadata = { ...subscription.metadata, ...update.metadata };
294
+ this.emitSubscription('subscription.updated', subscription);
295
+ return { ...subscription };
296
+ }
297
+ async cancelSubscription(subscriptionId) {
298
+ const subscription = this.find(this._subscriptions, subscriptionId, 'subscription');
299
+ const now = new Date();
300
+ Object.assign(subscription, {
301
+ status: 'canceled',
302
+ canceledAt: now,
303
+ endedAt: now,
304
+ nextAction: { type: 'none' }
305
+ });
306
+ this.emitSubscription('subscription.deleted', subscription);
307
+ return { ...subscription };
308
+ }
309
+ async getInvoice(invoiceId) {
310
+ return { ...this.find(this._invoices, invoiceId, 'invoice') };
311
+ }
312
+ async listPrices() {
313
+ return [...this._prices.values()].map((price) => ({ ...price }));
314
+ }
315
+ async createPortalSession(customerId, returnUrl) {
316
+ this.find(this._customers, customerId, 'customer');
317
+ return { url: returnUrl };
318
+ }
319
+ async verifyWebhook(body, headers, tolerance) {
320
+ const signature = String(headers[SIGNATURE_HEADER] ?? '');
321
+ const timestamp = Number(headers[TIMESTAMP_HEADER]);
322
+ const expected = this.signature(timestamp, body);
323
+ if (signature.length !== expected.length ||
324
+ !(0, node_crypto_1.timingSafeEqual)(Buffer.from(signature), Buffer.from(expected))) {
325
+ throw this.invalidWebhook('The signature does not match');
326
+ }
327
+ if (Math.abs(Date.now() - timestamp) > tolerance) {
328
+ throw this.invalidWebhook('The signature is too old');
329
+ }
330
+ return reviveDates(JSON.parse(body.toString('utf8')));
331
+ }
332
+ async checkHealth() {
333
+ return { success: true };
334
+ }
335
+ /**
336
+ * Signs an event the way the fake gateway sends it, for a request to the webhook endpoint of the gateway.
337
+ *
338
+ * @param {GatewayEvent} event - The event.
339
+ * @param {number} [timestamp] - The time of the signature, now by default.
340
+ * @return The body and the headers of the request.
341
+ */
342
+ signWebhook(event, timestamp = Date.now()) {
343
+ const body = Buffer.from(JSON.stringify(event));
344
+ return {
345
+ body,
346
+ headers: {
347
+ 'content-type': 'application/json',
348
+ [SIGNATURE_HEADER]: this.signature(timestamp, body),
349
+ [TIMESTAMP_HEADER]: String(timestamp)
350
+ }
351
+ };
352
+ }
353
+ /**
354
+ * Returns what a checkout was created with, i.e. for the page standing in for the one of a provider.
355
+ *
356
+ * @param {string} checkoutId - The ID of the checkout.
357
+ * @return {GatewayCheckoutInput} The input of the checkout.
358
+ */
359
+ checkoutInput(checkoutId) {
360
+ return this.find(this._checkouts, checkoutId, 'checkout').input;
361
+ }
362
+ /**
363
+ * Adds a recurring price the subscriptions are created with.
364
+ *
365
+ * @param {Partial<GatewayPrice>} price - The price, a monthly one of 1000 `USD` minor units by default.
366
+ * @return {GatewayPrice} The price.
367
+ */
368
+ addPrice(price = {}) {
369
+ const added = {
370
+ id: price.id ?? this.id('price'),
371
+ amount: 1000,
372
+ currency: 'USD',
373
+ interval: 'month',
374
+ intervalCount: 1,
375
+ active: true,
376
+ ...price
377
+ };
378
+ this._prices.set(added.id, added);
379
+ return { ...added };
380
+ }
381
+ /**
382
+ * Saves a card to a customer, as when the customer completes a setup.
383
+ *
384
+ * @param {string} customerId - The ID of the customer.
385
+ * @param {Partial<GatewayPaymentMethod>} [card] - The details of the card, a Visa ending with 4242 by default.
386
+ * @return {Promise<GatewayPaymentMethod>} The payment method, once its event is delivered.
387
+ */
388
+ async attachPaymentMethod(customerId, card = {}) {
389
+ const method = this.newMethod(customerId, card);
390
+ await this.flush();
391
+ return method;
392
+ }
393
+ /**
394
+ * Answers a payment waiting for the customer, as the client library of a provider does with a card.
395
+ *
396
+ * @param {string} paymentId - The ID of the payment at the gateway.
397
+ * @param {FakeOutcome} [outcome='succeeded'] - Whether the payment is paid, refused or held by the bank.
398
+ * @return {Promise<GatewayPayment>} The payment, once its events are delivered.
399
+ */
400
+ async confirmPayment(paymentId, outcome = 'succeeded') {
401
+ const payment = this.find(this._payments, paymentId, 'payment');
402
+ if (payment.status === 'succeeded' || payment.status === 'canceled') {
403
+ throw this.invalid('confirmPayment', `The payment is ${payment.status}`);
404
+ }
405
+ if (outcome === 'succeeded' && payment.customerId) {
406
+ payment.paymentMethod ??= this._saveMethod.has(payment.id)
407
+ ? this.newMethod(payment.customerId)
408
+ : undefined;
409
+ }
410
+ this.settle(payment, outcome);
411
+ await this.flush();
412
+ return { ...payment };
413
+ }
414
+ /**
415
+ * Completes a setup, saving a card to its customer.
416
+ *
417
+ * @param {string} setupId - The ID of the setup.
418
+ * @return {Promise<GatewayPaymentMethod>} The saved payment method, once its event is delivered.
419
+ */
420
+ async confirmSetup(setupId) {
421
+ const setup = this.find(this._setups, setupId, 'setup');
422
+ const method = this.newMethod(setup.customerId);
423
+ Object.assign(setup, {
424
+ status: 'succeeded',
425
+ paymentMethodId: method.id,
426
+ nextAction: { type: 'none' }
427
+ });
428
+ await this.flush();
429
+ return method;
430
+ }
431
+ /**
432
+ * Completes a checkout as the customer paying on its page does, or leaves it unpaid.
433
+ *
434
+ * @param {string} checkoutId - The ID of the checkout.
435
+ * @param {'succeeded' | 'expired'} [outcome='succeeded'] - Whether the customer paid or the page expired.
436
+ * @return {Promise<GatewayCheckout>} The checkout, once its events are delivered.
437
+ */
438
+ async completeCheckout(checkoutId, outcome = 'succeeded') {
439
+ const checkout = this.find(this._checkouts, checkoutId, 'checkout');
440
+ if (checkout.status !== 'open') {
441
+ return publicCheckout(checkout);
442
+ }
443
+ const { input } = checkout;
444
+ if (outcome === 'expired') {
445
+ checkout.status = 'expired';
446
+ }
447
+ else if (input.mode === 'subscription') {
448
+ const customerId = input.customerId ?? (await this.createCustomer({})).id;
449
+ const method = this.newMethod(customerId);
450
+ const subscription = await this.createSubscription({
451
+ customerId,
452
+ priceId: input.priceId,
453
+ quantity: input.quantity,
454
+ trialDays: input.trialDays,
455
+ paymentMethodId: method.id,
456
+ metadata: input.metadata,
457
+ idempotencyKey: `checkout:${checkout.id}`
458
+ });
459
+ Object.assign(checkout, {
460
+ status: 'complete',
461
+ customerId,
462
+ subscriptionId: subscription.id
463
+ });
464
+ }
465
+ else {
466
+ const payment = this.newPayment({
467
+ amount: input.amount ?? 0,
468
+ currency: input.currency ?? 'USD',
469
+ captureMethod: input.captureMethod ?? 'automatic',
470
+ customerId: input.customerId,
471
+ metadata: input.metadata,
472
+ idempotencyKey: `checkout:${checkout.id}`
473
+ });
474
+ Object.assign(checkout, { status: 'complete', paymentId: payment.id });
475
+ this.settle(payment, 'succeeded');
476
+ }
477
+ checkout.url = undefined;
478
+ this.emit(`checkout.${checkout.status}`, {
479
+ kind: 'checkout',
480
+ checkout: publicCheckout(checkout)
481
+ });
482
+ await this.flush();
483
+ return publicCheckout(checkout);
484
+ }
485
+ /**
486
+ * Starts the next period of a subscription and collects its invoice, as a provider does when the period ends.
487
+ *
488
+ * @param {string} subscriptionId - The ID of the subscription at the gateway.
489
+ * @param {'succeeded' | 'failed'} [outcome='succeeded'] - Whether the renewal is paid.
490
+ * @return {Promise<GatewaySubscription>} The subscription, once its events are delivered.
491
+ */
492
+ async renewSubscription(subscriptionId, outcome = 'succeeded') {
493
+ const subscription = this.find(this._subscriptions, subscriptionId, 'subscription');
494
+ if (subscription.cancelAtPeriodEnd) {
495
+ return this.cancelSubscription(subscriptionId).then(async (canceled) => {
496
+ await this.flush();
497
+ return canceled;
498
+ });
499
+ }
500
+ const price = this.find(this._prices, subscription.priceId, 'price');
501
+ const start = subscription.currentPeriodEnd ?? new Date();
502
+ subscription.currentPeriodStart = start;
503
+ subscription.currentPeriodEnd = new Date(start.getTime() + periodDays(price) * DAY);
504
+ subscription.trialEnd = undefined;
505
+ this.bill(subscription, outcome === 'failed'
506
+ ? exports.FAKE_DECLINED_METHOD
507
+ : (this._defaultMethods.get(subscription.customerId) ??
508
+ this.newMethod(subscription.customerId).id));
509
+ this.emitSubscription('subscription.updated', subscription);
510
+ await this.flush();
511
+ return { ...subscription };
512
+ }
513
+ /**
514
+ * Announces the end of the trial of a subscription, as a provider does a few days before it.
515
+ *
516
+ * @param {string} subscriptionId - The ID of the subscription at the gateway.
517
+ */
518
+ async announceTrialEnd(subscriptionId) {
519
+ const subscription = this.find(this._subscriptions, subscriptionId, 'subscription');
520
+ this.emit('subscription.trial_will_end', {
521
+ kind: 'subscription',
522
+ subscription: { ...subscription },
523
+ trialWillEnd: true
524
+ });
525
+ await this.flush();
526
+ }
527
+ /**
528
+ * Opens a dispute of a paid payment, then closes it when an outcome is given.
529
+ *
530
+ * @param {string} paymentId - The ID of the payment at the gateway.
531
+ * @param {'won' | 'lost'} [outcome] - How the dispute ends, left open without it.
532
+ */
533
+ async disputePayment(paymentId, outcome) {
534
+ const payment = this.find(this._payments, paymentId, 'payment');
535
+ const dispute = {
536
+ id: `dp_fake_${payment.id}`,
537
+ paymentId: payment.id,
538
+ amount: payment.amountCaptured,
539
+ currency: payment.currency,
540
+ reason: 'fraudulent'
541
+ };
542
+ this.emit(outcome ? 'dispute.closed' : 'dispute.created', {
543
+ kind: 'dispute',
544
+ dispute: { ...dispute, status: outcome ?? 'pending' }
545
+ });
546
+ await this.flush();
547
+ }
548
+ /**
549
+ * Waits until every event emitted so far is delivered to the listener.
550
+ *
551
+ * @return {Promise<void>} A promise resolved once the events are delivered.
552
+ */
553
+ async flush() {
554
+ await this._delivery;
555
+ }
556
+ /** @internal */
557
+ id(prefix) {
558
+ return `${prefix}_fake_${++this._sequence}`;
559
+ }
560
+ /** @internal */
561
+ find(records, id, what) {
562
+ const record = records.get(id);
563
+ if (!record) {
564
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentRequestInvalid, `The fake gateway has no ${what} '${id}'`, {
565
+ gateway: this.config.name,
566
+ status: 404,
567
+ providerCode: 'resource_missing'
568
+ });
569
+ }
570
+ return record;
571
+ }
572
+ /** @internal */
573
+ invalid(operation, message) {
574
+ return new common_1.PaymentError(common_1.ErrorCode.PaymentRequestInvalid, message, {
575
+ gateway: this.config.name,
576
+ operation,
577
+ status: 400
578
+ });
579
+ }
580
+ /** @internal */
581
+ invalidWebhook(reason) {
582
+ return new common_1.PaymentError(common_1.ErrorCode.PaymentWebhookInvalid, `Invalid webhook of the '${this.config.name}' gateway: ${reason}`, { gateway: this.config.name, reason });
583
+ }
584
+ /** Returns the result of the first call of a key, like the idempotency keys of a provider. @internal */
585
+ once(key, create) {
586
+ if (!this._idempotent.has(key)) {
587
+ this._idempotent.set(key, create());
588
+ }
589
+ return { ...this._idempotent.get(key) };
590
+ }
591
+ /** @internal */
592
+ confirmAction(id) {
593
+ return {
594
+ type: 'confirm',
595
+ clientSecret: `${id}_secret`,
596
+ publicKey: this.config.publicKey
597
+ };
598
+ }
599
+ /** @internal */
600
+ newPayment(input) {
601
+ const id = this.id('pi');
602
+ const payment = {
603
+ id,
604
+ status: 'pending',
605
+ amount: input.amount,
606
+ currency: input.currency,
607
+ amountCaptured: 0,
608
+ amountRefunded: 0,
609
+ livemode: false,
610
+ nextAction: this.confirmAction(id),
611
+ metadata: input.metadata ?? {},
612
+ customerId: input.customerId,
613
+ paymentMethodId: input.paymentMethodId
614
+ };
615
+ this._payments.set(id, payment);
616
+ if (input.captureMethod === 'manual') {
617
+ this._manual.add(id);
618
+ }
619
+ return payment;
620
+ }
621
+ /** @internal */
622
+ newMethod(customerId, card = {}) {
623
+ const method = {
624
+ id: this.id('pm'),
625
+ type: 'card',
626
+ brand: 'visa',
627
+ last4: '4242',
628
+ expMonth: 12,
629
+ expYear: new Date().getFullYear() + 3,
630
+ fingerprint: 'fake4242',
631
+ country: 'US',
632
+ ...card,
633
+ customerId
634
+ };
635
+ this._methods.set(method.id, method);
636
+ if (!this._defaultMethods.has(customerId)) {
637
+ this._defaultMethods.set(customerId, method.id);
638
+ }
639
+ this.emit('payment_method.attached', {
640
+ kind: 'paymentMethod',
641
+ paymentMethod: { ...method }
642
+ });
643
+ return { ...method };
644
+ }
645
+ /** Moves a payment to the state of an outcome, and tells its subscription. @internal */
646
+ settle(payment, outcome) {
647
+ if (outcome === 'succeeded') {
648
+ payment.status = this._manual.has(payment.id)
649
+ ? 'authorized'
650
+ : 'succeeded';
651
+ payment.amountCaptured =
652
+ payment.status === 'succeeded' ? payment.amount : 0;
653
+ payment.chargeId = `ch_${payment.id}`;
654
+ payment.receiptUrl = `${common_1.appConfig.HOSTNAME}/payments/fake/receipts/${payment.id}`;
655
+ payment.paymentMethodId ??= payment.paymentMethod?.id;
656
+ payment.failureCode = undefined;
657
+ payment.failureMessage = undefined;
658
+ payment.nextAction = { type: 'none' };
659
+ }
660
+ else if (outcome === 'failed') {
661
+ payment.status = 'failed';
662
+ payment.failureCode = 'card_declined';
663
+ payment.failureMessage = 'The card was declined.';
664
+ payment.nextAction = this.confirmAction(payment.id);
665
+ }
666
+ else {
667
+ payment.status = 'requiresAction';
668
+ payment.nextAction = this.confirmAction(payment.id);
669
+ }
670
+ this.emit(`payment.${payment.status}`, {
671
+ kind: 'payment',
672
+ payment: { ...payment }
673
+ });
674
+ if (payment.invoiceId) {
675
+ this.settleInvoice(payment);
676
+ }
677
+ }
678
+ /** Creates the invoice of the current period of a subscription and its payment. @internal */
679
+ bill(subscription, methodId) {
680
+ const price = this.find(this._prices, subscription.priceId, 'price');
681
+ const amount = price.amount * subscription.quantity;
682
+ const invoice = {
683
+ id: this.id('in'),
684
+ status: 'open',
685
+ customerId: subscription.customerId,
686
+ subscriptionId: subscription.id,
687
+ amountDue: amount,
688
+ amountPaid: 0,
689
+ currency: price.currency,
690
+ attemptCount: 0,
691
+ livemode: false,
692
+ number: `FAKE-${String(this._sequence).padStart(4, '0')}`,
693
+ periodStart: subscription.currentPeriodStart,
694
+ periodEnd: subscription.currentPeriodEnd
695
+ };
696
+ const payment = this.newPayment({
697
+ amount,
698
+ currency: price.currency,
699
+ captureMethod: 'automatic',
700
+ customerId: subscription.customerId,
701
+ paymentMethodId: methodId,
702
+ metadata: subscription.metadata,
703
+ idempotencyKey: invoice.id
704
+ });
705
+ Object.assign(payment, {
706
+ subscriptionId: subscription.id,
707
+ invoiceId: invoice.id
708
+ });
709
+ invoice.paymentId = payment.id;
710
+ subscription.latestInvoiceId = invoice.id;
711
+ this._invoices.set(invoice.id, invoice);
712
+ if (methodId === exports.FAKE_DECLINED_METHOD) {
713
+ this.settle(payment, 'failed');
714
+ }
715
+ else if (methodId) {
716
+ this.settle(payment, 'succeeded');
717
+ }
718
+ return payment;
719
+ }
720
+ /** Applies the payment of an invoice to it and to its subscription. @internal */
721
+ settleInvoice(payment) {
722
+ const invoice = this._invoices.get(payment.invoiceId);
723
+ const subscription = this._subscriptions.get(payment.subscriptionId ?? '');
724
+ if (!invoice || !subscription) {
725
+ return;
726
+ }
727
+ invoice.attemptCount += 1;
728
+ if (payment.status === 'succeeded') {
729
+ Object.assign(invoice, { status: 'paid', amountPaid: invoice.amountDue });
730
+ subscription.status = 'active';
731
+ subscription.nextAction = { type: 'none' };
732
+ this.emit('invoice.paid', { kind: 'invoice', invoice: { ...invoice } });
733
+ }
734
+ else if (payment.status === 'failed') {
735
+ invoice.nextAttemptAt = new Date(Date.now() + 3 * DAY);
736
+ if (subscription.status !== 'incomplete') {
737
+ subscription.status = 'pastDue';
738
+ }
739
+ this.emit('invoice.payment_failed', {
740
+ kind: 'invoice',
741
+ invoice: { ...invoice }
742
+ });
743
+ }
744
+ if (subscription.status !== 'incomplete') {
745
+ this.emitSubscription('subscription.updated', subscription);
746
+ }
747
+ }
748
+ /** @internal */
749
+ emitSubscription(type, subscription) {
750
+ this.emit(type, {
751
+ kind: 'subscription',
752
+ subscription: { ...subscription }
753
+ });
754
+ }
755
+ /** Records an event and delivers it to the listener after the ones before it. @internal */
756
+ emit(type, data) {
757
+ const event = {
758
+ id: this.id('evt'),
759
+ type,
760
+ occurredAt: new Date(),
761
+ livemode: false,
762
+ data
763
+ };
764
+ this.events.push(event);
765
+ const listener = globals[FAKE_LISTENER];
766
+ if (listener) {
767
+ this._delivery = this._delivery
768
+ .then(() => listener(this.config.name, event))
769
+ .catch(() => undefined);
770
+ }
771
+ }
772
+ /** @internal */
773
+ signature(timestamp, body) {
774
+ return (0, node_crypto_1.createHmac)('sha256', this.config.webhookSecret ?? DEFAULT_SECRET)
775
+ .update(`${timestamp}.`)
776
+ .update(body)
777
+ .digest('hex');
778
+ }
779
+ }
780
+ exports.FakePaymentGateway = FakePaymentGateway;
781
+ /** The days of a period of a price. */
782
+ function periodDays(price) {
783
+ return INTERVAL_DAYS[price.interval] * price.intervalCount;
784
+ }
785
+ function publicCheckout({ input, ...checkout }) {
786
+ return checkout;
787
+ }
788
+ function publicSetup({ customerId, ...setup }) {
789
+ return setup;
790
+ }
791
+ /** Turns the ISO dates of a parsed event back into dates. */
792
+ function reviveDates(value) {
793
+ if (typeof value === 'string') {
794
+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
795
+ ? new Date(value)
796
+ : value;
797
+ }
798
+ if (Array.isArray(value)) {
799
+ return value.map(reviveDates);
800
+ }
801
+ if (value && typeof value === 'object') {
802
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, reviveDates(entry)]));
803
+ }
804
+ return value;
805
+ }