@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.
- package/LICENSE +21 -0
- package/README.md +212 -2
- package/config.d.ts +77 -0
- package/config.js +118 -0
- package/gateway/fake-gateway.d.ts +144 -0
- package/gateway/fake-gateway.js +805 -0
- package/gateway/gateway-registry.d.ts +99 -0
- package/gateway/gateway-registry.js +275 -0
- package/gateway/payment-gateway.d.ts +68 -0
- package/gateway/payment-gateway.js +82 -0
- package/index.d.ts +16 -0
- package/index.js +51 -0
- package/locales/en.json +47 -0
- package/maintenance/payment-maintenance-jobs.d.ts +5 -0
- package/maintenance/payment-maintenance-jobs.js +38 -0
- package/module.d.ts +8 -0
- package/module.js +85 -0
- package/package.json +67 -3
- package/resources/model-util.d.ts +40 -0
- package/resources/model-util.js +30 -0
- package/resources/payment/model.d.ts +2 -0
- package/resources/payment/model.js +106 -0
- package/resources/payment-customer/model.d.ts +2 -0
- package/resources/payment-customer/model.js +53 -0
- package/resources/payment-event/model.d.ts +2 -0
- package/resources/payment-event/model.js +31 -0
- package/resources/payment-invoice/model.d.ts +2 -0
- package/resources/payment-invoice/model.js +55 -0
- package/resources/payment-method/model.d.ts +2 -0
- package/resources/payment-method/model.js +37 -0
- package/resources/payment-plan/model.d.ts +2 -0
- package/resources/payment-plan/model.js +37 -0
- package/resources/payment-subscription/model.d.ts +2 -0
- package/resources/payment-subscription/model.js +82 -0
- package/resources/payment-transaction/model.d.ts +2 -0
- package/resources/payment-transaction/model.js +43 -0
- package/resources/payment-webhook-event/model.d.ts +2 -0
- package/resources/payment-webhook-event/model.js +32 -0
- package/resources/policies.d.ts +15 -0
- package/resources/policies.js +36 -0
- package/resources/services.d.ts +6 -0
- package/resources/services.js +19 -0
- package/resources/subscriptions.d.ts +9 -0
- package/resources/subscriptions.js +30 -0
- package/resources.d.ts +8 -0
- package/resources.js +34 -0
- package/service/payment-emails.d.ts +12 -0
- package/service/payment-emails.js +145 -0
- package/service/payment-events.d.ts +90 -0
- package/service/payment-events.js +472 -0
- package/service/payment-handlers.d.ts +26 -0
- package/service/payment-handlers.js +42 -0
- package/service/payment-store.d.ts +50 -0
- package/service/payment-store.js +95 -0
- package/service/payment-sync.d.ts +113 -0
- package/service/payment-sync.js +745 -0
- package/service/payments-service.d.ts +307 -0
- package/service/payments-service.js +747 -0
- package/service/subscriptions-service.d.ts +178 -0
- package/service/subscriptions-service.js +433 -0
- package/tasks/payments-replay.d.ts +10 -0
- package/tasks/payments-replay.js +36 -0
- package/tasks/payments-sync-plans.d.ts +10 -0
- package/tasks/payments-sync-plans.js +24 -0
- package/templates/emails/payment-action-required.html.hbs +28 -0
- package/templates/emails/payment-action-required.subject.hbs +1 -0
- package/templates/emails/payment-failed.html.hbs +37 -0
- package/templates/emails/payment-failed.subject.hbs +1 -0
- package/templates/emails/payment-receipt.html.hbs +45 -0
- package/templates/emails/payment-receipt.subject.hbs +1 -0
- package/templates/emails/payment-refunded.html.hbs +37 -0
- package/templates/emails/payment-refunded.subject.hbs +1 -0
- package/templates/emails/subscription-canceled.html.hbs +24 -0
- package/templates/emails/subscription-canceled.subject.hbs +1 -0
- package/templates/emails/subscription-trial-ending.html.hbs +25 -0
- package/templates/emails/subscription-trial-ending.subject.hbs +1 -0
- package/templates/layouts/email.html.hbs +36 -0
- package/templates/partials/email-button.html.hbs +15 -0
- package/tsconfig.build.tsbuildinfo +1 -0
- package/types.d.ts +488 -0
- package/types.js +2 -0
- package/utils/money-util.d.ts +61 -0
- package/utils/money-util.js +124 -0
- package/utils/status-util.d.ts +29 -0
- package/utils/status-util.js +93 -0
- package/utils/telemetry.d.ts +16 -0
- package/utils/telemetry.js +69 -0
- package/web/payment-routes.d.ts +7 -0
- package/web/payment-routes.js +410 -0
- package/web/payment-schemas.d.ts +70 -0
- package/web/payment-schemas.js +101 -0
|
@@ -0,0 +1,747 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PaymentsService = void 0;
|
|
4
|
+
const common_1 = require("@appweaver/common");
|
|
5
|
+
const core_1 = require("@appweaver/core");
|
|
6
|
+
const config_1 = require("../config");
|
|
7
|
+
const gateway_registry_1 = require("../gateway/gateway-registry");
|
|
8
|
+
const money_util_1 = require("../utils/money-util");
|
|
9
|
+
const status_util_1 = require("../utils/status-util");
|
|
10
|
+
const telemetry_1 = require("../utils/telemetry");
|
|
11
|
+
const payment_events_1 = require("./payment-events");
|
|
12
|
+
const payment_store_1 = require("./payment-store");
|
|
13
|
+
const payment_sync_1 = require("./payment-sync");
|
|
14
|
+
const logger = (0, common_1.createLogger)('payments');
|
|
15
|
+
/**
|
|
16
|
+
* Takes the payments of the gateways of the `payments` config: one-time payments confirmed by the client or charged
|
|
17
|
+
* to a saved payment method, hosted checkout pages, authorizations captured later, cancellations and refunds. A
|
|
18
|
+
* card never reaches the application: the client confirms a payment with the library of the gateway, or on its page.
|
|
19
|
+
* The records only move with what the gateway reports, here and in its webhooks, and every change is announced to
|
|
20
|
+
* the handlers of `onPaymentEvent`.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* const payments = inject(PaymentsService);
|
|
24
|
+
* const { payment, nextAction } = await payments.createPayment({
|
|
25
|
+
* amount: 1999,
|
|
26
|
+
* currency: 'EUR',
|
|
27
|
+
* userId: user.id,
|
|
28
|
+
* email: user.email,
|
|
29
|
+
* reference: order.id
|
|
30
|
+
* });
|
|
31
|
+
*/
|
|
32
|
+
class PaymentsService {
|
|
33
|
+
static [common_1.LIFECYCLE] = true;
|
|
34
|
+
static [common_1.HEALTH_CHECK] = true;
|
|
35
|
+
/** @internal */
|
|
36
|
+
_store = new payment_store_1.PaymentStore();
|
|
37
|
+
/** @internal */
|
|
38
|
+
_sync = new payment_sync_1.PaymentSync(this._store);
|
|
39
|
+
/** @internal */
|
|
40
|
+
_registry = (0, gateway_registry_1.gatewayRegistry)();
|
|
41
|
+
/** @internal */
|
|
42
|
+
_events = (0, core_1.inject)(payment_events_1.PaymentEvents);
|
|
43
|
+
/**
|
|
44
|
+
* Checks the gateways of the config.
|
|
45
|
+
*
|
|
46
|
+
* @throws {ConfigurationError} `CONFIGURATION_INVALID` for a default gateway that is not configured.
|
|
47
|
+
*/
|
|
48
|
+
onInit() {
|
|
49
|
+
const errors = this._registry.validate();
|
|
50
|
+
if (errors.length) {
|
|
51
|
+
throw new common_1.ConfigurationError(common_1.ErrorCode.ConfigurationInvalid, errors.join('; '));
|
|
52
|
+
}
|
|
53
|
+
logger.debug({ gateways: this._registry.names() }, 'Payments ready');
|
|
54
|
+
}
|
|
55
|
+
async checkHealth() {
|
|
56
|
+
for (const name of config_1.paymentsConfig.HEALTH_CHECK_GATEWAYS) {
|
|
57
|
+
const result = await (await this._registry.gateway(name)).checkHealth();
|
|
58
|
+
if (!result.success) {
|
|
59
|
+
return { ...result, message: `${name}: ${result.message ?? 'failed'}` };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { success: true };
|
|
63
|
+
}
|
|
64
|
+
checkHealthConfig() {
|
|
65
|
+
return { name: 'payments' };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Returns the names of the gateways.
|
|
69
|
+
*
|
|
70
|
+
* @return {string[]} The configured gateways, and the `fake` one outside of production.
|
|
71
|
+
*/
|
|
72
|
+
gateways() {
|
|
73
|
+
return this._registry.names();
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Selects the gateway of a payment: the one named, otherwise by the country and the currency.
|
|
77
|
+
*
|
|
78
|
+
* @param {GatewaySelection} [selection] - The name of the gateway, or the country and currency of the payment.
|
|
79
|
+
* @return {string} The name of the gateway.
|
|
80
|
+
* @throws {PaymentError} `PAYMENT_GATEWAY_UNKNOWN` for a gateway that is not configured.
|
|
81
|
+
*/
|
|
82
|
+
selectGateway(selection) {
|
|
83
|
+
return this._registry.select(selection);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Returns the driver of a gateway, for the calls the service does not wrap.
|
|
87
|
+
*
|
|
88
|
+
* @param {string} [name] - The name of the gateway. Default: the default one.
|
|
89
|
+
* @return {Promise<PaymentGateway>} The driver.
|
|
90
|
+
*/
|
|
91
|
+
gateway(name) {
|
|
92
|
+
return this._registry.gateway(name ?? this._registry.defaultName());
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Returns the public key the clients of a gateway confirm the payments with.
|
|
96
|
+
*
|
|
97
|
+
* @param {string} [name] - The name of the gateway. Default: the default one.
|
|
98
|
+
* @return {string | undefined} The key, `undefined` when none is configured.
|
|
99
|
+
*/
|
|
100
|
+
publicKey(name) {
|
|
101
|
+
return this._registry.config(name ?? this._registry.defaultName())
|
|
102
|
+
.publicKey;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Finds the customer of a user at a gateway.
|
|
106
|
+
*
|
|
107
|
+
* @param {string | number} userId - The ID of the user.
|
|
108
|
+
* @param {string} [gateway] - The name of the gateway. Default: the default one.
|
|
109
|
+
* @return {Promise<PaymentCustomerRecord | null>} The customer, `null` before the first payment of the user.
|
|
110
|
+
*/
|
|
111
|
+
findCustomer(userId, gateway) {
|
|
112
|
+
return this._store.customers.find({
|
|
113
|
+
userId: String(userId),
|
|
114
|
+
provider: gateway ?? this._registry.defaultName(),
|
|
115
|
+
deletedAtProvider: null
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Returns the customer of a user at a gateway, created there on the first call. A changed email, name or locale
|
|
120
|
+
* is sent to the gateway.
|
|
121
|
+
*
|
|
122
|
+
* @param {PaymentCustomerInput} input - The user, and the gateway or the country and currency selecting it.
|
|
123
|
+
* @return {Promise<PaymentCustomerRecord>} The customer.
|
|
124
|
+
*/
|
|
125
|
+
async ensureCustomer(input) {
|
|
126
|
+
const userId = String(input.userId);
|
|
127
|
+
const provider = this._registry.select({ ...input, userId });
|
|
128
|
+
const details = {
|
|
129
|
+
email: input.email,
|
|
130
|
+
name: input.name,
|
|
131
|
+
locale: input.locale
|
|
132
|
+
};
|
|
133
|
+
const where = { userId, provider, deletedAtProvider: null };
|
|
134
|
+
// Two calls of a new user would otherwise create two customers at the gateway
|
|
135
|
+
const lock = await (0, core_1.inject)(common_1.Memory, false)?.lock(`payments:customer:${provider}:${userId}`, { expireMs: 30_000, retryCount: 60, retryDelay: 250 });
|
|
136
|
+
try {
|
|
137
|
+
const existing = await this._store.customers.find(where);
|
|
138
|
+
if (!existing) {
|
|
139
|
+
const customer = await this.call(provider, 'createCustomer', (gateway) => gateway.createCustomer({ ...details, metadata: { userId } }));
|
|
140
|
+
return await this._store.customers.create({
|
|
141
|
+
provider,
|
|
142
|
+
providerCustomerId: customer.id,
|
|
143
|
+
userId,
|
|
144
|
+
email: details.email ?? null,
|
|
145
|
+
name: details.name ?? null,
|
|
146
|
+
locale: details.locale ?? null
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
const changed = ['email', 'name', 'locale'].filter((key) => details[key] && details[key] !== existing[key]);
|
|
150
|
+
if (!changed.length) {
|
|
151
|
+
return existing;
|
|
152
|
+
}
|
|
153
|
+
await this.call(provider, 'updateCustomer', (gateway) => gateway.updateCustomer(existing.providerCustomerId, details));
|
|
154
|
+
return await this._store.customers.update(existing.id, Object.fromEntries(changed.map((key) => [key, details[key]])));
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
await lock?.release();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Creates a payment. With a saved payment method it is charged at once; without one the client confirms it with
|
|
162
|
+
* the `clientSecret` of the next action, in the card form of the gateway. The result of a confirmation arrives in
|
|
163
|
+
* a webhook, announced as `payment.succeeded` or `payment.failed`.
|
|
164
|
+
*
|
|
165
|
+
* @param {CreatePaymentInput} input - The amount, who pays, and what for.
|
|
166
|
+
* @return {Promise<PaymentResult>} The payment and what its client does next.
|
|
167
|
+
* @throws {PaymentError} `PAYMENT_AMOUNT_INVALID`, `PAYMENT_CURRENCY_UNSUPPORTED`, `PAYMENT_METHOD_NOT_FOUND`,
|
|
168
|
+
* `PAYMENT_DECLINED` for a refused saved method, or the error of the gateway.
|
|
169
|
+
*/
|
|
170
|
+
async createPayment(input) {
|
|
171
|
+
const existing = await this.findByKey(input.idempotencyKey);
|
|
172
|
+
if (existing) {
|
|
173
|
+
return this.resume(existing);
|
|
174
|
+
}
|
|
175
|
+
const currency = this.currency(input);
|
|
176
|
+
(0, money_util_1.validateAmount)(input.amount, currency);
|
|
177
|
+
const provider = this._registry.select({
|
|
178
|
+
...input,
|
|
179
|
+
currency,
|
|
180
|
+
userId: toId(input.userId)
|
|
181
|
+
});
|
|
182
|
+
const customer = await this.customerOf(input, provider);
|
|
183
|
+
const method = input.paymentMethodId
|
|
184
|
+
? await this.methodOf(input.paymentMethodId, customer)
|
|
185
|
+
: null;
|
|
186
|
+
const captureMethod = input.captureMethod ?? 'automatic';
|
|
187
|
+
if (captureMethod === 'manual') {
|
|
188
|
+
await this.require(provider, 'manualCapture');
|
|
189
|
+
}
|
|
190
|
+
const created = await this.createRecord(input, {
|
|
191
|
+
provider,
|
|
192
|
+
currency,
|
|
193
|
+
captureMethod,
|
|
194
|
+
customerId: customer?.id ?? null,
|
|
195
|
+
paymentMethodId: method?.id ?? null
|
|
196
|
+
});
|
|
197
|
+
if (!created.created) {
|
|
198
|
+
return this.resume(created.record);
|
|
199
|
+
}
|
|
200
|
+
const { record } = created;
|
|
201
|
+
let payment;
|
|
202
|
+
try {
|
|
203
|
+
payment = await this.call(provider, 'createPayment', (gateway) => gateway.createPayment({
|
|
204
|
+
amount: input.amount,
|
|
205
|
+
currency,
|
|
206
|
+
captureMethod,
|
|
207
|
+
idempotencyKey: `payment-${record.id}`,
|
|
208
|
+
customerId: customer?.providerCustomerId,
|
|
209
|
+
paymentMethodId: method?.providerPaymentMethodId,
|
|
210
|
+
offSession: input.offSession,
|
|
211
|
+
savePaymentMethod: input.savePaymentMethod,
|
|
212
|
+
description: input.description,
|
|
213
|
+
statementDescriptor: input.statementDescriptor,
|
|
214
|
+
returnUrl: input.returnUrl ?? this.returnUrl(record.id),
|
|
215
|
+
metadata: this.metadata(input, record)
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
if ((0, common_1.isAppweaverError)(e) && e.is(common_1.ErrorCode.PaymentDeclined)) {
|
|
220
|
+
await this.decline(record, e);
|
|
221
|
+
}
|
|
222
|
+
throw e;
|
|
223
|
+
}
|
|
224
|
+
const result = await this.applied(provider, payment, record.id);
|
|
225
|
+
if (result.payment.status === 'failed') {
|
|
226
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentDeclined, result.payment.failureMessage ?? 'The payment was declined', {
|
|
227
|
+
gateway: provider,
|
|
228
|
+
operation: 'createPayment',
|
|
229
|
+
declineCode: result.payment.failureCode ?? undefined
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
return result;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Creates a payment paid on a hosted page of the gateway, where the customer is sent with the `redirect` of the
|
|
236
|
+
* next action. They come back to the return route, which reads the payment from the gateway and redirects to
|
|
237
|
+
* `payments.successUrl` with its `paymentId` and `status`.
|
|
238
|
+
*
|
|
239
|
+
* @param {CreateCheckoutInput} input - The amount, who pays, and what for.
|
|
240
|
+
* @return {Promise<PaymentResult>} The payment and the redirect to its page.
|
|
241
|
+
* @throws {PaymentError} `PAYMENT_CAPABILITY_UNSUPPORTED` for a gateway without hosted pages, and the errors of
|
|
242
|
+
* {@link createPayment}.
|
|
243
|
+
*/
|
|
244
|
+
async createCheckout(input) {
|
|
245
|
+
const existing = await this.findByKey(input.idempotencyKey);
|
|
246
|
+
if (existing) {
|
|
247
|
+
return this.resume(existing);
|
|
248
|
+
}
|
|
249
|
+
const currency = this.currency(input);
|
|
250
|
+
(0, money_util_1.validateAmount)(input.amount, currency);
|
|
251
|
+
const provider = this._registry.select({
|
|
252
|
+
...input,
|
|
253
|
+
currency,
|
|
254
|
+
userId: toId(input.userId)
|
|
255
|
+
});
|
|
256
|
+
await this.require(provider, 'checkout');
|
|
257
|
+
const captureMethod = input.captureMethod ?? 'automatic';
|
|
258
|
+
const customer = await this.customerOf(input, provider);
|
|
259
|
+
const created = await this.createRecord(input, {
|
|
260
|
+
provider,
|
|
261
|
+
currency,
|
|
262
|
+
captureMethod,
|
|
263
|
+
customerId: customer?.id ?? null,
|
|
264
|
+
paymentMethodId: null
|
|
265
|
+
});
|
|
266
|
+
if (!created.created) {
|
|
267
|
+
return this.resume(created.record);
|
|
268
|
+
}
|
|
269
|
+
const { record } = created;
|
|
270
|
+
const checkout = await this.call(provider, 'createCheckout', (gateway) => gateway.createCheckout({
|
|
271
|
+
mode: 'payment',
|
|
272
|
+
amount: input.amount,
|
|
273
|
+
currency,
|
|
274
|
+
captureMethod,
|
|
275
|
+
idempotencyKey: `checkout-${record.id}`,
|
|
276
|
+
customerId: customer?.providerCustomerId,
|
|
277
|
+
description: input.description,
|
|
278
|
+
locale: input.locale,
|
|
279
|
+
successUrl: input.successUrl ?? this.returnUrl(record.id),
|
|
280
|
+
cancelUrl: input.cancelUrl ??
|
|
281
|
+
config_1.paymentsConfig.CANCEL_URL ??
|
|
282
|
+
this.returnUrl(record.id),
|
|
283
|
+
metadata: this.metadata(input, record)
|
|
284
|
+
}));
|
|
285
|
+
const payment = await this._store.payments.update(record.id, {
|
|
286
|
+
providerCheckoutId: checkout.id,
|
|
287
|
+
providerPaymentId: checkout.paymentId ?? null
|
|
288
|
+
});
|
|
289
|
+
return {
|
|
290
|
+
payment,
|
|
291
|
+
nextAction: checkout.url
|
|
292
|
+
? { type: 'redirect', url: checkout.url }
|
|
293
|
+
: { type: 'none' }
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Returns a payment.
|
|
298
|
+
*
|
|
299
|
+
* @param {string} id - The ID of the payment.
|
|
300
|
+
* @return {Promise<PaymentRecord>} The payment.
|
|
301
|
+
* @throws {PaymentError} `PAYMENT_NOT_FOUND` for an unknown payment.
|
|
302
|
+
*/
|
|
303
|
+
async getPayment(id) {
|
|
304
|
+
const payment = await this._store.payments.findById(id);
|
|
305
|
+
if (!payment) {
|
|
306
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentNotFound, `No payment '${id}' found`, { id });
|
|
307
|
+
}
|
|
308
|
+
return payment;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Finds the payments of what the application sells, the newest first.
|
|
312
|
+
*
|
|
313
|
+
* @param {string} reference - The reference of the payments, i.e. the ID of an order.
|
|
314
|
+
* @param {string} [referenceType] - The kind of the reference.
|
|
315
|
+
* @return {Promise<PaymentRecord[]>} The payments.
|
|
316
|
+
*/
|
|
317
|
+
findPayments(reference, referenceType) {
|
|
318
|
+
return this._store.payments.list({ reference, ...(referenceType ? { referenceType } : {}) }, { orderBy: { createdAt: 'desc' } });
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Returns the ledger of a payment: its authorization, charge, capture, refunds and disputes, the oldest first.
|
|
322
|
+
*
|
|
323
|
+
* @param {string} id - The ID of the payment.
|
|
324
|
+
* @return {Promise<PaymentTransactionRecord[]>} The entries.
|
|
325
|
+
*/
|
|
326
|
+
listTransactions(id) {
|
|
327
|
+
return this._store.transactions.list({ paymentId: id }, { orderBy: { occurredAt: 'asc' } });
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Reads a payment from its gateway and applies its state, i.e. when the customer comes back from its page before
|
|
331
|
+
* the webhook arrives. A payment of a hosted page that is not paid yet is found through its checkout.
|
|
332
|
+
*
|
|
333
|
+
* @param {string} id - The ID of the payment.
|
|
334
|
+
* @return {Promise<PaymentResult>} The payment and what its client does next.
|
|
335
|
+
* @throws {PaymentError} `PAYMENT_NOT_FOUND` for an unknown payment.
|
|
336
|
+
*/
|
|
337
|
+
async syncPayment(id) {
|
|
338
|
+
return this.resume(await this.getPayment(id));
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Takes the money of an authorized payment.
|
|
342
|
+
*
|
|
343
|
+
* @param {string} id - The ID of the payment.
|
|
344
|
+
* @param {number} [amount] - A part of the authorized amount, in minor units, the rest released. Default: all.
|
|
345
|
+
* @return {Promise<PaymentRecord>} The payment.
|
|
346
|
+
* @throws {PaymentError} `PAYMENT_NOT_FOUND`, `PAYMENT_INVALID_STATE` for a payment that is not authorized,
|
|
347
|
+
* `PAYMENT_AMOUNT_INVALID` for an amount above the authorized one.
|
|
348
|
+
*/
|
|
349
|
+
async capturePayment(id, amount) {
|
|
350
|
+
const record = await this.getPayment(id);
|
|
351
|
+
if (record.status !== 'authorized' || !record.providerPaymentId) {
|
|
352
|
+
throw invalidState(record, 'capture');
|
|
353
|
+
}
|
|
354
|
+
if (amount !== undefined) {
|
|
355
|
+
(0, money_util_1.validateAmount)(amount, record.currency);
|
|
356
|
+
if (amount > record.amount) {
|
|
357
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentAmountInvalid, `The amount to capture is above the authorized ${record.amount}`, { amount, currency: record.currency });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
const payment = await this.call(record.provider, 'capturePayment', (gateway) => gateway.capturePayment(record.providerPaymentId, amount, `capture-${record.id}`));
|
|
361
|
+
return (await this.applied(record.provider, payment, record.id)).payment;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Cancels a payment that is not paid, releasing its authorization. The hosted page of a payment is closed at the
|
|
365
|
+
* gateway first, so it cannot be paid once its payment is canceled.
|
|
366
|
+
*
|
|
367
|
+
* @param {string} id - The ID of the payment.
|
|
368
|
+
* @return {Promise<PaymentRecord>} The payment.
|
|
369
|
+
* @throws {PaymentError} `PAYMENT_NOT_FOUND`, `PAYMENT_INVALID_STATE` for a paid or canceled payment, also one
|
|
370
|
+
* paid on its hosted page in the meantime.
|
|
371
|
+
*/
|
|
372
|
+
async cancelPayment(id) {
|
|
373
|
+
let record = await this.getPayment(id);
|
|
374
|
+
if ((0, status_util_1.isFinalStatus)(record.status)) {
|
|
375
|
+
throw invalidState(record, 'cancel');
|
|
376
|
+
}
|
|
377
|
+
if (!record.providerPaymentId && record.providerCheckoutId) {
|
|
378
|
+
record = await this.closeCheckout(record);
|
|
379
|
+
if (record.status === 'canceled') {
|
|
380
|
+
return record;
|
|
381
|
+
}
|
|
382
|
+
if ((0, status_util_1.isFinalStatus)(record.status)) {
|
|
383
|
+
throw invalidState(record, 'cancel');
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
if (!record.providerPaymentId) {
|
|
387
|
+
// Never reached the gateway, or waited on a hosted page that is closed now
|
|
388
|
+
const moved = await this._store.payments.updateWhere({ id, status: record.status }, { status: 'canceled', canceledAt: new Date() });
|
|
389
|
+
if (moved) {
|
|
390
|
+
await this._events.dispatch([
|
|
391
|
+
await this._sync.event('payment.canceled', record.provider, {
|
|
392
|
+
userId: record.userId,
|
|
393
|
+
paymentId: id
|
|
394
|
+
})
|
|
395
|
+
]);
|
|
396
|
+
}
|
|
397
|
+
return this.getPayment(id);
|
|
398
|
+
}
|
|
399
|
+
const payment = await this.call(record.provider, 'cancelPayment', (gateway) => gateway.cancelPayment(record.providerPaymentId));
|
|
400
|
+
return (await this.applied(record.provider, payment, record.id)).payment;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Refunds a paid payment, all of it or a part.
|
|
404
|
+
*
|
|
405
|
+
* @param {string} id - The ID of the payment.
|
|
406
|
+
* @param {RefundInput} [input] - The amount, the reason and the idempotency key of the refund.
|
|
407
|
+
* @return {Promise<PaymentTransactionRecord>} The ledger entry of the refund.
|
|
408
|
+
* @throws {PaymentError} `PAYMENT_NOT_FOUND`, `PAYMENT_INVALID_STATE` for a payment that is not paid,
|
|
409
|
+
* `PAYMENT_REFUND_EXCEEDED` for an amount above what is left of it.
|
|
410
|
+
*/
|
|
411
|
+
async refundPayment(id, input = {}) {
|
|
412
|
+
const record = await this.getPayment(id);
|
|
413
|
+
if (record.status !== 'succeeded' || !record.providerPaymentId) {
|
|
414
|
+
throw invalidState(record, 'refund');
|
|
415
|
+
}
|
|
416
|
+
const refundable = record.amountCaptured - record.amountRefunded;
|
|
417
|
+
const amount = input.amount ?? refundable;
|
|
418
|
+
if (input.amount !== undefined) {
|
|
419
|
+
(0, money_util_1.validateAmount)(input.amount, record.currency);
|
|
420
|
+
}
|
|
421
|
+
if (amount <= 0 || amount > refundable) {
|
|
422
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentRefundExceeded, `The refund of ${amount} is above the ${refundable} left of the payment '${id}'`, { id, amount, refundable });
|
|
423
|
+
}
|
|
424
|
+
const refund = await this.call(record.provider, 'refundPayment', (gateway) => gateway.refundPayment({
|
|
425
|
+
paymentId: record.providerPaymentId,
|
|
426
|
+
amount,
|
|
427
|
+
reason: input.reason,
|
|
428
|
+
// Without a key of the caller, the same refund asked twice is made once
|
|
429
|
+
idempotencyKey: `refund-${record.id}-${input.idempotencyKey ?? `${record.amountRefunded}-${amount}`}`,
|
|
430
|
+
metadata: { [payment_sync_1.PAYMENT_METADATA_KEY]: record.id }
|
|
431
|
+
}));
|
|
432
|
+
const applied = await this._sync.applyRefund(record.provider, refund);
|
|
433
|
+
await this._events.dispatch(applied.events);
|
|
434
|
+
return applied.record;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Starts saving a payment method of a user without a payment: the client confirms the `clientSecret` of the next
|
|
438
|
+
* action with the library of the gateway, and the method arrives in a webhook, announced as
|
|
439
|
+
* `paymentMethod.attached`.
|
|
440
|
+
*
|
|
441
|
+
* @param {PaymentCustomerInput} input - The user, and the gateway or the country and currency selecting it.
|
|
442
|
+
* @return {Promise<PaymentNextAction>} What the client does next.
|
|
443
|
+
* @throws {PaymentError} `PAYMENT_CAPABILITY_UNSUPPORTED` for a gateway saving no payment methods.
|
|
444
|
+
*/
|
|
445
|
+
async createSetup(input) {
|
|
446
|
+
const customer = await this.ensureCustomer(input);
|
|
447
|
+
await this.require(customer.provider, 'savedMethods');
|
|
448
|
+
const setup = await this.call(customer.provider, 'createSetup', (gateway) => gateway.createSetup(customer.providerCustomerId));
|
|
449
|
+
return this.withPublicKey(customer.provider, setup.nextAction);
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Lists the saved payment methods of a user, the default one first.
|
|
453
|
+
*
|
|
454
|
+
* @param {string | number} userId - The ID of the user.
|
|
455
|
+
* @param {string} [gateway] - The name of a gateway. Default: the methods of every gateway.
|
|
456
|
+
* @return {Promise<PaymentMethodRecord[]>} The payment methods.
|
|
457
|
+
*/
|
|
458
|
+
listPaymentMethods(userId, gateway) {
|
|
459
|
+
return this._store.methods.list({ userId: String(userId), ...(gateway ? { provider: gateway } : {}) }, { orderBy: { isDefault: 'desc' } });
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Reads the payment methods of a customer from the gateway: the new ones are saved, the removed ones deleted.
|
|
463
|
+
*
|
|
464
|
+
* @param {PaymentCustomerRecord} customer - The customer.
|
|
465
|
+
* @return {Promise<PaymentMethodRecord[]>} The payment methods of the customer.
|
|
466
|
+
*/
|
|
467
|
+
async syncPaymentMethods(customer) {
|
|
468
|
+
const { provider } = customer;
|
|
469
|
+
const methods = await this.call(provider, 'listPaymentMethods', (gateway) => gateway.listPaymentMethods(customer.providerCustomerId));
|
|
470
|
+
for (const method of methods) {
|
|
471
|
+
const applied = await this._sync.applyPaymentMethod(provider, {
|
|
472
|
+
...method,
|
|
473
|
+
customerId: customer.providerCustomerId
|
|
474
|
+
});
|
|
475
|
+
await this._events.dispatch(applied.events);
|
|
476
|
+
}
|
|
477
|
+
const known = new Set(methods.map((method) => method.id));
|
|
478
|
+
for (const local of await this._store.methods.list({
|
|
479
|
+
customerId: customer.id
|
|
480
|
+
})) {
|
|
481
|
+
if (!known.has(local.providerPaymentMethodId)) {
|
|
482
|
+
const applied = await this._sync.applyPaymentMethod(provider, { id: local.providerPaymentMethodId, type: local.type }, true);
|
|
483
|
+
await this._events.dispatch(applied.events);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return this._store.methods.list({ customerId: customer.id }, { orderBy: { isDefault: 'desc' } });
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Makes a saved payment method the one the subscriptions of its customer are charged to.
|
|
490
|
+
*
|
|
491
|
+
* @param {string} id - The ID of the payment method.
|
|
492
|
+
* @return {Promise<PaymentMethodRecord>} The payment method.
|
|
493
|
+
* @throws {PaymentError} `PAYMENT_METHOD_NOT_FOUND` for an unknown payment method.
|
|
494
|
+
*/
|
|
495
|
+
async setDefaultPaymentMethod(id) {
|
|
496
|
+
const method = await this.getPaymentMethod(id);
|
|
497
|
+
const customer = (await this._store.customers.findById(method.customerId));
|
|
498
|
+
await this.call(method.provider, 'setDefaultPaymentMethod', (gateway) => gateway.setDefaultPaymentMethod(customer.providerCustomerId, method.providerPaymentMethodId));
|
|
499
|
+
await this._store.methods.updateWhere({ customerId: customer.id, isDefault: true }, { isDefault: false });
|
|
500
|
+
await this._store.customers.update(customer.id, {
|
|
501
|
+
defaultPaymentMethodId: id
|
|
502
|
+
});
|
|
503
|
+
return this._store.methods.update(id, { isDefault: true });
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Removes a saved payment method, at the gateway too.
|
|
507
|
+
*
|
|
508
|
+
* @param {string} id - The ID of the payment method.
|
|
509
|
+
* @throws {PaymentError} `PAYMENT_METHOD_NOT_FOUND` for an unknown payment method.
|
|
510
|
+
*/
|
|
511
|
+
async detachPaymentMethod(id) {
|
|
512
|
+
const method = await this.getPaymentMethod(id);
|
|
513
|
+
await this.call(method.provider, 'detachPaymentMethod', (gateway) => gateway.detachPaymentMethod(method.providerPaymentMethodId));
|
|
514
|
+
const applied = await this._sync.applyPaymentMethod(method.provider, { id: method.providerPaymentMethodId, type: method.type }, true);
|
|
515
|
+
await this._events.dispatch(applied.events);
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Returns a saved payment method.
|
|
519
|
+
*
|
|
520
|
+
* @param {string} id - The ID of the payment method.
|
|
521
|
+
* @return {Promise<PaymentMethodRecord>} The payment method.
|
|
522
|
+
* @throws {PaymentError} `PAYMENT_METHOD_NOT_FOUND` for an unknown payment method.
|
|
523
|
+
*/
|
|
524
|
+
async getPaymentMethod(id) {
|
|
525
|
+
const method = await this._store.methods.findById(id);
|
|
526
|
+
if (!method) {
|
|
527
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentMethodNotFound, `No payment method '${id}' found`, { id });
|
|
528
|
+
}
|
|
529
|
+
return method;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Reads the payments in a state that is not final from their gateways again, catching the webhooks never
|
|
533
|
+
* received, and cancels the ones left unpaid longer than `payments.pendingTtl`.
|
|
534
|
+
*
|
|
535
|
+
* @param {Date} now - The current time.
|
|
536
|
+
* @param {number} limit - The most payments to read.
|
|
537
|
+
* @return {Promise<number>} The number of payments read or canceled.
|
|
538
|
+
*/
|
|
539
|
+
async reconcile(now, limit) {
|
|
540
|
+
const stale = await this._store.payments.list({
|
|
541
|
+
status: { in: status_util_1.OPEN_STATUSES.filter((status) => status !== 'failed') },
|
|
542
|
+
updatedAt: {
|
|
543
|
+
lt: new Date(now.valueOf() - config_1.paymentsConfig.RECONCILE_AFTER)
|
|
544
|
+
}
|
|
545
|
+
}, { orderBy: { updatedAt: 'asc' }, take: limit });
|
|
546
|
+
let handled = 0;
|
|
547
|
+
for (const record of stale) {
|
|
548
|
+
try {
|
|
549
|
+
const { payment } = await this.resume(record);
|
|
550
|
+
const expired = config_1.paymentsConfig.PENDING_TTL > 0 &&
|
|
551
|
+
['pending', 'requiresAction'].includes(payment.status) &&
|
|
552
|
+
payment.createdAt.valueOf() <
|
|
553
|
+
now.valueOf() - config_1.paymentsConfig.PENDING_TTL;
|
|
554
|
+
if (expired) {
|
|
555
|
+
await this.cancelPayment(payment.id);
|
|
556
|
+
}
|
|
557
|
+
else if (payment.status === record.status) {
|
|
558
|
+
// Read again only after another `payments.reconcileAfter`
|
|
559
|
+
await this._store.payments.update(record.id, { updatedAt: now });
|
|
560
|
+
}
|
|
561
|
+
handled++;
|
|
562
|
+
}
|
|
563
|
+
catch (e) {
|
|
564
|
+
logger.warn({ err: e, payment: record.id, gateway: record.provider }, 'Payment not reconciled');
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return handled;
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Returns a next action with the public key of its gateway, which the client confirms it with.
|
|
571
|
+
*
|
|
572
|
+
* @param {string} provider - The name of the gateway.
|
|
573
|
+
* @param {PaymentNextAction} action - The next action.
|
|
574
|
+
* @return {PaymentNextAction} The action, a `confirm` one with the public key.
|
|
575
|
+
*/
|
|
576
|
+
withPublicKey(provider, action) {
|
|
577
|
+
return action.type === 'confirm'
|
|
578
|
+
? {
|
|
579
|
+
...action,
|
|
580
|
+
publicKey: action.publicKey ?? this._registry.config(provider).publicKey
|
|
581
|
+
}
|
|
582
|
+
: action;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Returns the URL of the return route of a payment, where the gateway sends the customer back.
|
|
586
|
+
*
|
|
587
|
+
* @param {string} id - The ID of the payment.
|
|
588
|
+
* @return {string} The URL.
|
|
589
|
+
*/
|
|
590
|
+
returnUrl(id) {
|
|
591
|
+
return `${common_1.appConfig.HOSTNAME.replace(/\/+$/, '')}/payments/return/${id}`;
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Runs a call of a gateway in its span.
|
|
595
|
+
*
|
|
596
|
+
* @param {string} provider - The name of the gateway.
|
|
597
|
+
* @param {string} operation - The method of the gateway, the name of the span.
|
|
598
|
+
* @param {Function} fn - The call.
|
|
599
|
+
* @return {Promise<Object>} The result of the call.
|
|
600
|
+
*/
|
|
601
|
+
async call(provider, operation, fn) {
|
|
602
|
+
const gateway = await this._registry.gateway(provider);
|
|
603
|
+
return (0, telemetry_1.traceGatewayCall)(provider, gateway.config.driver, operation, () => fn(gateway));
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Checks that a gateway has a capability.
|
|
607
|
+
*
|
|
608
|
+
* @param {string} provider - The name of the gateway.
|
|
609
|
+
* @param {PaymentCapability} capability - The capability.
|
|
610
|
+
* @throws {PaymentError} `PAYMENT_CAPABILITY_UNSUPPORTED` when the gateway has not.
|
|
611
|
+
*/
|
|
612
|
+
async require(provider, capability) {
|
|
613
|
+
const gateway = await this._registry.gateway(provider);
|
|
614
|
+
if (!gateway.supports(capability)) {
|
|
615
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentCapabilityUnsupported, `The '${provider}' gateway has no ${capability}`, { gateway: provider, capability });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
/** @internal */
|
|
619
|
+
currency(input) {
|
|
620
|
+
return (0, money_util_1.normalizeCurrency)(input.currency);
|
|
621
|
+
}
|
|
622
|
+
/** @internal */
|
|
623
|
+
async findByKey(key) {
|
|
624
|
+
return key ? this._store.payments.find({ idempotencyKey: key }) : null;
|
|
625
|
+
}
|
|
626
|
+
/** @internal */
|
|
627
|
+
async customerOf(input, provider) {
|
|
628
|
+
return input.userId === undefined
|
|
629
|
+
? null
|
|
630
|
+
: this.ensureCustomer({
|
|
631
|
+
userId: input.userId,
|
|
632
|
+
email: input.email,
|
|
633
|
+
name: input.name,
|
|
634
|
+
locale: input.locale,
|
|
635
|
+
gateway: provider
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
/** @internal */
|
|
639
|
+
async methodOf(id, customer) {
|
|
640
|
+
const method = await this._store.methods.findById(id);
|
|
641
|
+
if (!method || method.customerId !== customer?.id) {
|
|
642
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentMethodNotFound, `No payment method '${id}' of the customer found`, { id });
|
|
643
|
+
}
|
|
644
|
+
return method;
|
|
645
|
+
}
|
|
646
|
+
/** Stores the payment before the gateway is called, so its webhooks always find it. @internal */
|
|
647
|
+
async createRecord(input, data) {
|
|
648
|
+
try {
|
|
649
|
+
const record = await this._store.payments.create({
|
|
650
|
+
...data,
|
|
651
|
+
status: 'pending',
|
|
652
|
+
amount: input.amount,
|
|
653
|
+
userId: toId(input.userId) ?? null,
|
|
654
|
+
email: input.email ?? null,
|
|
655
|
+
description: input.description ?? null,
|
|
656
|
+
reference: input.reference ?? null,
|
|
657
|
+
referenceType: input.referenceType ?? null,
|
|
658
|
+
idempotencyKey: input.idempotencyKey ?? null,
|
|
659
|
+
metadata: input.metadata ?? null
|
|
660
|
+
});
|
|
661
|
+
return { record, created: true };
|
|
662
|
+
}
|
|
663
|
+
catch (e) {
|
|
664
|
+
const existing = (0, payment_store_1.isUniqueViolation)(e)
|
|
665
|
+
? await this.findByKey(input.idempotencyKey)
|
|
666
|
+
: null;
|
|
667
|
+
if (!existing) {
|
|
668
|
+
throw e;
|
|
669
|
+
}
|
|
670
|
+
return { record: existing, created: false };
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
/** @internal */
|
|
674
|
+
metadata(input, record) {
|
|
675
|
+
return {
|
|
676
|
+
...input.metadata,
|
|
677
|
+
...(input.reference ? { reference: input.reference } : {}),
|
|
678
|
+
[payment_sync_1.PAYMENT_METADATA_KEY]: record.id
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
/** Applies a payment of a gateway to its record, and announces what changed. @internal */
|
|
682
|
+
async applied(provider, payment, recordId) {
|
|
683
|
+
const applied = await this._sync.applyPayment(provider, payment, recordId);
|
|
684
|
+
await this._events.dispatch(applied.events);
|
|
685
|
+
return {
|
|
686
|
+
payment: applied.record ?? (await this.getPayment(recordId)),
|
|
687
|
+
nextAction: this.withPublicKey(provider, payment.nextAction)
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Closes the hosted page of a payment at its gateway, and applies a payment made on the page in the meantime.
|
|
692
|
+
*
|
|
693
|
+
* @internal
|
|
694
|
+
*/
|
|
695
|
+
async closeCheckout(record) {
|
|
696
|
+
const checkout = await this.call(record.provider, 'expireCheckout', (gateway) => gateway.expireCheckout(record.providerCheckoutId));
|
|
697
|
+
return checkout.paymentId ? (await this.resume(record)).payment : record;
|
|
698
|
+
}
|
|
699
|
+
/** Reads a payment from its gateway, the state and the next action it has now. @internal */
|
|
700
|
+
async resume(record) {
|
|
701
|
+
const { provider } = record;
|
|
702
|
+
let providerPaymentId = record.providerPaymentId;
|
|
703
|
+
if (!providerPaymentId && record.providerCheckoutId) {
|
|
704
|
+
const checkout = await this.call(provider, 'getCheckout', (gateway) => gateway.getCheckout(record.providerCheckoutId));
|
|
705
|
+
providerPaymentId = checkout.paymentId ?? null;
|
|
706
|
+
if (!providerPaymentId) {
|
|
707
|
+
if (checkout.status === 'expired') {
|
|
708
|
+
await this._events.dispatch(await this._sync.expireCheckout(provider, checkout));
|
|
709
|
+
}
|
|
710
|
+
return {
|
|
711
|
+
payment: await this.getPayment(record.id),
|
|
712
|
+
nextAction: checkout.status === 'open' && checkout.url
|
|
713
|
+
? { type: 'redirect', url: checkout.url }
|
|
714
|
+
: { type: 'none' }
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
if (!providerPaymentId || (0, status_util_1.isFinalStatus)(record.status)) {
|
|
719
|
+
return { payment: record, nextAction: { type: 'none' } };
|
|
720
|
+
}
|
|
721
|
+
const payment = await this.call(provider, 'getPayment', (gateway) => gateway.getPayment(providerPaymentId));
|
|
722
|
+
return this.applied(provider, payment, record.id);
|
|
723
|
+
}
|
|
724
|
+
/** Records a payment the gateway refused before creating it. @internal */
|
|
725
|
+
async decline(record, error) {
|
|
726
|
+
const moved = await this._store.payments.updateWhere({ id: record.id, status: 'pending' }, {
|
|
727
|
+
status: 'failed',
|
|
728
|
+
failureCode: error.details?.declineCode ?? error.details?.providerCode ?? null,
|
|
729
|
+
failureMessage: error.message
|
|
730
|
+
});
|
|
731
|
+
if (moved) {
|
|
732
|
+
await this._events.dispatch([
|
|
733
|
+
await this._sync.event('payment.failed', record.provider, {
|
|
734
|
+
userId: record.userId,
|
|
735
|
+
paymentId: record.id
|
|
736
|
+
})
|
|
737
|
+
]);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
exports.PaymentsService = PaymentsService;
|
|
742
|
+
function toId(id) {
|
|
743
|
+
return id === undefined ? undefined : String(id);
|
|
744
|
+
}
|
|
745
|
+
function invalidState(record, action) {
|
|
746
|
+
return new common_1.PaymentError(common_1.ErrorCode.PaymentInvalidState, `Cannot ${action} the payment '${record.id}', it is ${record.status}`, { id: record.id, status: record.status, action });
|
|
747
|
+
}
|