@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,29 @@
|
|
|
1
|
+
import { PaymentStatus, SubscriptionStatus, TransactionStatus } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Tells whether a payment may move from a state to another one.
|
|
4
|
+
*
|
|
5
|
+
* @param {PaymentStatus} from - The current state.
|
|
6
|
+
* @param {PaymentStatus} to - The next state.
|
|
7
|
+
* @return {boolean} `true` when the transition is allowed.
|
|
8
|
+
*/
|
|
9
|
+
export declare function canTransition(from: PaymentStatus, to: PaymentStatus): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Returns the states a payment may come from to reach a state, the condition of the update moving it there.
|
|
12
|
+
*
|
|
13
|
+
* @param {PaymentStatus} to - The next state.
|
|
14
|
+
* @return {PaymentStatus[]} The states allowed before it.
|
|
15
|
+
*/
|
|
16
|
+
export declare function statusesBefore(to: PaymentStatus): PaymentStatus[];
|
|
17
|
+
/**
|
|
18
|
+
* Tells whether a payment is in a final state: paid or canceled.
|
|
19
|
+
*
|
|
20
|
+
* @param {PaymentStatus} status - The state.
|
|
21
|
+
* @return {boolean} `true` for a final state.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isFinalStatus(status: PaymentStatus): boolean;
|
|
24
|
+
/** The states of a payment the reconciliation reads from the gateway again. */
|
|
25
|
+
export declare const OPEN_STATUSES: PaymentStatus[];
|
|
26
|
+
/** The states of a subscription giving access to what it pays for. */
|
|
27
|
+
export declare const ACTIVE_SUBSCRIPTION_STATUSES: SubscriptionStatus[];
|
|
28
|
+
/** The states of a ledger entry that never change again. */
|
|
29
|
+
export declare const FINAL_TRANSACTION_STATUSES: TransactionStatus[];
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FINAL_TRANSACTION_STATUSES = exports.ACTIVE_SUBSCRIPTION_STATUSES = exports.OPEN_STATUSES = void 0;
|
|
4
|
+
exports.canTransition = canTransition;
|
|
5
|
+
exports.statusesBefore = statusesBefore;
|
|
6
|
+
exports.isFinalStatus = isFinalStatus;
|
|
7
|
+
/** The states a payment may move to from each state. A paid or canceled payment never moves again. */
|
|
8
|
+
const TRANSITIONS = {
|
|
9
|
+
pending: [
|
|
10
|
+
'requiresAction',
|
|
11
|
+
'processing',
|
|
12
|
+
'authorized',
|
|
13
|
+
'succeeded',
|
|
14
|
+
'failed',
|
|
15
|
+
'canceled'
|
|
16
|
+
],
|
|
17
|
+
requiresAction: [
|
|
18
|
+
'pending',
|
|
19
|
+
'processing',
|
|
20
|
+
'authorized',
|
|
21
|
+
'succeeded',
|
|
22
|
+
'failed',
|
|
23
|
+
'canceled'
|
|
24
|
+
],
|
|
25
|
+
processing: [
|
|
26
|
+
'requiresAction',
|
|
27
|
+
'authorized',
|
|
28
|
+
'succeeded',
|
|
29
|
+
'failed',
|
|
30
|
+
'canceled'
|
|
31
|
+
],
|
|
32
|
+
authorized: ['succeeded', 'canceled'],
|
|
33
|
+
// A failed attempt may be tried again with another payment method
|
|
34
|
+
failed: [
|
|
35
|
+
'pending',
|
|
36
|
+
'requiresAction',
|
|
37
|
+
'processing',
|
|
38
|
+
'authorized',
|
|
39
|
+
'succeeded',
|
|
40
|
+
'canceled'
|
|
41
|
+
],
|
|
42
|
+
succeeded: [],
|
|
43
|
+
canceled: []
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Tells whether a payment may move from a state to another one.
|
|
47
|
+
*
|
|
48
|
+
* @param {PaymentStatus} from - The current state.
|
|
49
|
+
* @param {PaymentStatus} to - The next state.
|
|
50
|
+
* @return {boolean} `true` when the transition is allowed.
|
|
51
|
+
*/
|
|
52
|
+
function canTransition(from, to) {
|
|
53
|
+
return TRANSITIONS[from].includes(to);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Returns the states a payment may come from to reach a state, the condition of the update moving it there.
|
|
57
|
+
*
|
|
58
|
+
* @param {PaymentStatus} to - The next state.
|
|
59
|
+
* @return {PaymentStatus[]} The states allowed before it.
|
|
60
|
+
*/
|
|
61
|
+
function statusesBefore(to) {
|
|
62
|
+
return Object.keys(TRANSITIONS).filter((from) => TRANSITIONS[from].includes(to));
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Tells whether a payment is in a final state: paid or canceled.
|
|
66
|
+
*
|
|
67
|
+
* @param {PaymentStatus} status - The state.
|
|
68
|
+
* @return {boolean} `true` for a final state.
|
|
69
|
+
*/
|
|
70
|
+
function isFinalStatus(status) {
|
|
71
|
+
return TRANSITIONS[status].length === 0;
|
|
72
|
+
}
|
|
73
|
+
/** The states of a payment the reconciliation reads from the gateway again. */
|
|
74
|
+
exports.OPEN_STATUSES = [
|
|
75
|
+
'pending',
|
|
76
|
+
'requiresAction',
|
|
77
|
+
'processing',
|
|
78
|
+
'authorized',
|
|
79
|
+
'failed'
|
|
80
|
+
];
|
|
81
|
+
/** The states of a subscription giving access to what it pays for. */
|
|
82
|
+
exports.ACTIVE_SUBSCRIPTION_STATUSES = [
|
|
83
|
+
'trialing',
|
|
84
|
+
'active'
|
|
85
|
+
];
|
|
86
|
+
/** The states of a ledger entry that never change again. */
|
|
87
|
+
exports.FINAL_TRANSACTION_STATUSES = [
|
|
88
|
+
'succeeded',
|
|
89
|
+
'failed',
|
|
90
|
+
'canceled',
|
|
91
|
+
'won',
|
|
92
|
+
'lost'
|
|
93
|
+
];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** What became of a webhook event. */
|
|
2
|
+
export type WebhookOutcome = 'received' | 'duplicate' | 'ignored' | 'invalid' | 'processed' | 'failed';
|
|
3
|
+
/**
|
|
4
|
+
* Runs a call to a payment gateway in a client span (`payments createPayment`), and records its duration.
|
|
5
|
+
*
|
|
6
|
+
* @param {string} gateway - The name of the gateway.
|
|
7
|
+
* @param {string} driver - The driver of the gateway.
|
|
8
|
+
* @param {string} operation - The method of the gateway, i.e. `createPayment`.
|
|
9
|
+
* @param {Function} call - The call.
|
|
10
|
+
* @return {Promise<Object>} The result of the call.
|
|
11
|
+
*/
|
|
12
|
+
export declare function traceGatewayCall<T>(gateway: string, driver: string, operation: string, call: () => Promise<T>): Promise<T>;
|
|
13
|
+
/** Counts a webhook event of a gateway by its outcome. */
|
|
14
|
+
export declare function countWebhookEvent(gateway: string, outcome: WebhookOutcome): void;
|
|
15
|
+
/** Counts an event of the payments by its type and what became of its delivery. */
|
|
16
|
+
export declare function countPaymentEvent(type: string, outcome: 'delivered' | 'retried' | 'failed'): void;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.traceGatewayCall = traceGatewayCall;
|
|
4
|
+
exports.countWebhookEvent = countWebhookEvent;
|
|
5
|
+
exports.countPaymentEvent = countPaymentEvent;
|
|
6
|
+
const common_1 = require("@appweaver/common");
|
|
7
|
+
const operationDuration = (0, common_1.telemetryHistogram)('appweaver.payments.gateway.duration', {
|
|
8
|
+
description: 'The duration of the calls to the payment gateways',
|
|
9
|
+
unit: 's',
|
|
10
|
+
advice: { explicitBucketBoundaries: common_1.DURATION_BUCKETS }
|
|
11
|
+
});
|
|
12
|
+
const webhookEvents = (0, common_1.telemetryCounter)('appweaver.payments.webhook.events', {
|
|
13
|
+
description: 'The webhook events of the payment gateways, by their outcome',
|
|
14
|
+
unit: '{event}'
|
|
15
|
+
});
|
|
16
|
+
const paymentEvents = (0, common_1.telemetryCounter)('appweaver.payments.events', {
|
|
17
|
+
description: 'The events of the payments, by their type and outcome',
|
|
18
|
+
unit: '{event}'
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* Runs a call to a payment gateway in a client span (`payments createPayment`), and records its duration.
|
|
22
|
+
*
|
|
23
|
+
* @param {string} gateway - The name of the gateway.
|
|
24
|
+
* @param {string} driver - The driver of the gateway.
|
|
25
|
+
* @param {string} operation - The method of the gateway, i.e. `createPayment`.
|
|
26
|
+
* @param {Function} call - The call.
|
|
27
|
+
* @return {Promise<Object>} The result of the call.
|
|
28
|
+
*/
|
|
29
|
+
async function traceGatewayCall(gateway, driver, operation, call) {
|
|
30
|
+
if (!(0, common_1.telemetryEnabled)('payments')) {
|
|
31
|
+
return call();
|
|
32
|
+
}
|
|
33
|
+
const started = performance.now();
|
|
34
|
+
const attributes = {
|
|
35
|
+
'appweaver.payments.gateway': gateway,
|
|
36
|
+
'appweaver.payments.driver': driver,
|
|
37
|
+
'appweaver.payments.operation': operation
|
|
38
|
+
};
|
|
39
|
+
try {
|
|
40
|
+
const result = await (0, common_1.withSpan)(`payments ${operation}`, { kind: common_1.SpanKind.CLIENT, attributes }, call);
|
|
41
|
+
(0, common_1.recordDuration)(operationDuration(), started, attributes);
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
(0, common_1.recordDuration)(operationDuration(), started, {
|
|
46
|
+
...attributes,
|
|
47
|
+
'error.type': (0, common_1.spanErrorType)(e)
|
|
48
|
+
});
|
|
49
|
+
throw e;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Counts a webhook event of a gateway by its outcome. */
|
|
53
|
+
function countWebhookEvent(gateway, outcome) {
|
|
54
|
+
if ((0, common_1.telemetryEnabled)('payments')) {
|
|
55
|
+
webhookEvents().add(1, {
|
|
56
|
+
'appweaver.payments.gateway': gateway,
|
|
57
|
+
'appweaver.payments.outcome': outcome
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Counts an event of the payments by its type and what became of its delivery. */
|
|
62
|
+
function countPaymentEvent(type, outcome) {
|
|
63
|
+
if ((0, common_1.telemetryEnabled)('payments')) {
|
|
64
|
+
paymentEvents().add(1, {
|
|
65
|
+
'appweaver.payments.event': type,
|
|
66
|
+
'appweaver.payments.outcome': outcome
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registers the web part of the payments: the webhook endpoint of every gateway (`POST /payments/webhooks/<gateway>`)
|
|
3
|
+
* and the return route of the hosted pages (`GET /payments/return/<id>`), both at the root of the server, and with
|
|
4
|
+
* `payments.routes.enabled` the routes of the records and of the actions of a user and of the admin roles, the ones
|
|
5
|
+
* of the subscriptions with `payments.subscriptions.enabled` only.
|
|
6
|
+
*/
|
|
7
|
+
export declare function registerPaymentRoutes(): void;
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerPaymentRoutes = registerPaymentRoutes;
|
|
4
|
+
const typebox_1 = require("typebox");
|
|
5
|
+
const common_1 = require("@appweaver/common");
|
|
6
|
+
const core_1 = require("@appweaver/core");
|
|
7
|
+
const internal_1 = require("@appweaver/core/internal");
|
|
8
|
+
const web_1 = require("@appweaver/web");
|
|
9
|
+
const config_1 = require("../config");
|
|
10
|
+
const fake_gateway_1 = require("../gateway/fake-gateway");
|
|
11
|
+
const gateway_registry_1 = require("../gateway/gateway-registry");
|
|
12
|
+
const policies_1 = require("../resources/policies");
|
|
13
|
+
const payment_events_1 = require("../service/payment-events");
|
|
14
|
+
const payments_service_1 = require("../service/payments-service");
|
|
15
|
+
const subscriptions_service_1 = require("../service/subscriptions-service");
|
|
16
|
+
const payment_schemas_1 = require("./payment-schemas");
|
|
17
|
+
const logger = (0, common_1.createLogger)('payments');
|
|
18
|
+
/** Marks the routes the payments helper of the generated client calls, among the ones of the application. */
|
|
19
|
+
const OPERATION = {
|
|
20
|
+
tags: ['Payments'],
|
|
21
|
+
[`x-${common_1.CONFIG_NAME}-module`]: 'payments'
|
|
22
|
+
};
|
|
23
|
+
/** The codes the routes calling a gateway answer with. */
|
|
24
|
+
const GATEWAY_ERRORS = [
|
|
25
|
+
common_1.ErrorCode.PaymentGatewayUnknown,
|
|
26
|
+
common_1.ErrorCode.PaymentGatewayFailed,
|
|
27
|
+
common_1.ErrorCode.PaymentGatewayUnavailable,
|
|
28
|
+
common_1.ErrorCode.PaymentRequestInvalid,
|
|
29
|
+
common_1.ErrorCode.PaymentCapabilityUnsupported
|
|
30
|
+
];
|
|
31
|
+
const SUBSCRIPTION_ERRORS = [
|
|
32
|
+
...GATEWAY_ERRORS,
|
|
33
|
+
common_1.ErrorCode.PaymentSubscriptionNotFound,
|
|
34
|
+
common_1.ErrorCode.PaymentInvalidState
|
|
35
|
+
];
|
|
36
|
+
/** The read-only routes of the records of the payments, with the policies showing a user their own. */
|
|
37
|
+
const RESOURCES = ['Payment', 'PaymentMethod', 'PaymentTransaction'];
|
|
38
|
+
/** The ones of the subscriptions, registered with `payments.subscriptions.enabled`. */
|
|
39
|
+
const SUBSCRIPTION_RESOURCES = [
|
|
40
|
+
'PaymentSubscription',
|
|
41
|
+
'PaymentInvoice',
|
|
42
|
+
'PaymentPlan'
|
|
43
|
+
];
|
|
44
|
+
/**
|
|
45
|
+
* Registers the web part of the payments: the webhook endpoint of every gateway (`POST /payments/webhooks/<gateway>`)
|
|
46
|
+
* and the return route of the hosted pages (`GET /payments/return/<id>`), both at the root of the server, and with
|
|
47
|
+
* `payments.routes.enabled` the routes of the records and of the actions of a user and of the admin roles, the ones
|
|
48
|
+
* of the subscriptions with `payments.subscriptions.enabled` only.
|
|
49
|
+
*/
|
|
50
|
+
function registerPaymentRoutes() {
|
|
51
|
+
(0, core_1.define)(Object.assign(webhookRoutes, { apiPrefix: false }), common_1.ROUTE, 'append');
|
|
52
|
+
if (!config_1.paymentsRoutesConfig.ENABLED) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const resources = config_1.paymentsSubscriptionsConfig.ENABLED
|
|
56
|
+
? [...RESOURCES, ...SUBSCRIPTION_RESOURCES]
|
|
57
|
+
: RESOURCES;
|
|
58
|
+
for (const modelName of resources) {
|
|
59
|
+
// The application may define the routes of a model itself
|
|
60
|
+
if (internal_1.context.resource.routes.has(modelName)) {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
(0, web_1.createRoutes)({
|
|
64
|
+
modelName,
|
|
65
|
+
actions: ['find', 'query'],
|
|
66
|
+
defaults: { errorCodes: [], audit: false }
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
registerUserRoutes();
|
|
70
|
+
if (config_1.paymentsSubscriptionsConfig.ENABLED) {
|
|
71
|
+
registerSubscriptionRoutes();
|
|
72
|
+
}
|
|
73
|
+
registerAdminRoutes();
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The routes the gateways call, in a scope of their own: the body of a webhook is kept as it was received, since its
|
|
77
|
+
* signature is computed over its bytes.
|
|
78
|
+
*/
|
|
79
|
+
async function webhookRoutes(server) {
|
|
80
|
+
server.removeAllContentTypeParsers();
|
|
81
|
+
server.addContentTypeParser('*', { parseAs: 'buffer', bodyLimit: config_1.paymentsWebhooksConfig.BODY_MAX_SIZE }, (_request, body, done) => done(null, body));
|
|
82
|
+
const route = (method, url, handler) => server.route({
|
|
83
|
+
method,
|
|
84
|
+
url,
|
|
85
|
+
handler,
|
|
86
|
+
// Called by the gateways and their pages, not a part of the API of the application
|
|
87
|
+
schema: { hide: true },
|
|
88
|
+
config: { audit: false, compress: false }
|
|
89
|
+
});
|
|
90
|
+
route('POST', '/payments/webhooks/:gateway', async (request, reply) => {
|
|
91
|
+
const { gateway } = request.params;
|
|
92
|
+
if (!(0, core_1.inject)(payments_service_1.PaymentsService).gateways().includes(gateway)) {
|
|
93
|
+
return reply.callNotFound();
|
|
94
|
+
}
|
|
95
|
+
// Answered once the event is stored: its processing never delays the gateway, which sends it again otherwise
|
|
96
|
+
await (0, core_1.inject)(payment_events_1.PaymentEvents).receiveWebhook(gateway, Buffer.isBuffer(request.body) ? request.body : Buffer.alloc(0), request.headers);
|
|
97
|
+
return reply.code(200).send({ received: true });
|
|
98
|
+
});
|
|
99
|
+
route('GET', '/payments/return/:id', async (request, reply) => {
|
|
100
|
+
const { id } = request.params;
|
|
101
|
+
let status = 'unknown';
|
|
102
|
+
try {
|
|
103
|
+
// The customer may be back before the webhook of their payment
|
|
104
|
+
status = (await (0, core_1.inject)(payments_service_1.PaymentsService).syncPayment(id)).payment.status;
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
logger.warn({ err: e, payment: id }, 'Returned payment not read');
|
|
108
|
+
}
|
|
109
|
+
const paid = ['succeeded', 'authorized', 'processing'].includes(status);
|
|
110
|
+
const target = new URL((paid ? undefined : config_1.paymentsConfig.CANCEL_URL) ??
|
|
111
|
+
config_1.paymentsConfig.SUCCESS_URL ??
|
|
112
|
+
common_1.appConfig.HOSTNAME);
|
|
113
|
+
target.searchParams.set('paymentId', id);
|
|
114
|
+
target.searchParams.set('status', status);
|
|
115
|
+
return reply.redirect(target.toString());
|
|
116
|
+
});
|
|
117
|
+
if ((0, core_1.inject)(payments_service_1.PaymentsService).gateways().includes(gateway_registry_1.FAKE_GATEWAY)) {
|
|
118
|
+
route('GET', '/payments/fake/checkout/:gateway/:id', fakeCheckout);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The page of the `fake` gateway standing in for the hosted page of a provider: it pays or leaves the checkout, then
|
|
123
|
+
* sends the customer where the provider would.
|
|
124
|
+
*/
|
|
125
|
+
async function fakeCheckout(request, reply) {
|
|
126
|
+
const { gateway: name, id } = request.params;
|
|
127
|
+
const { outcome } = request.query;
|
|
128
|
+
const payments = (0, core_1.inject)(payments_service_1.PaymentsService);
|
|
129
|
+
const gateway = payments.gateways().includes(name)
|
|
130
|
+
? await payments.gateway(name)
|
|
131
|
+
: undefined;
|
|
132
|
+
if (!(gateway instanceof fake_gateway_1.FakePaymentGateway)) {
|
|
133
|
+
return reply.callNotFound();
|
|
134
|
+
}
|
|
135
|
+
const input = gateway.checkoutInput(id);
|
|
136
|
+
if (outcome === 'pay' || outcome === 'cancel') {
|
|
137
|
+
await gateway.completeCheckout(id, outcome === 'pay' ? 'succeeded' : 'expired');
|
|
138
|
+
return reply.redirect(outcome === 'pay' ? input.successUrl : input.cancelUrl);
|
|
139
|
+
}
|
|
140
|
+
const title = escapeHtml(input.description ?? input.priceId ?? 'Payment');
|
|
141
|
+
const amount = input.amount !== undefined
|
|
142
|
+
? `${input.amount} ${escapeHtml(input.currency ?? '')} (minor units)`
|
|
143
|
+
: '';
|
|
144
|
+
return reply.type('text/html; charset=utf-8').send(`<!doctype html><html><head><meta charset="utf-8"><title>Fake checkout</title></head>
|
|
145
|
+
<body style="font-family: sans-serif; max-width: 420px; margin: 80px auto; text-align: center">
|
|
146
|
+
<h1>Fake checkout</h1><p>${title}</p><p>${amount}</p>
|
|
147
|
+
<p><a href="?outcome=pay">Pay</a> <a href="?outcome=cancel">Cancel</a></p>
|
|
148
|
+
<p style="color: #777; font-size: 13px">The built-in gateway of development, no money moves.</p>
|
|
149
|
+
</body></html>`);
|
|
150
|
+
}
|
|
151
|
+
/** The routes of an authenticated user: saving a card, their payment methods and billing page. */
|
|
152
|
+
function registerUserRoutes() {
|
|
153
|
+
const schemas = (0, payment_schemas_1.paymentRouteSchemas)();
|
|
154
|
+
(0, web_1.registerRoute)((router) => {
|
|
155
|
+
const payments = () => (0, core_1.inject)(payments_service_1.PaymentsService);
|
|
156
|
+
const subscriptions = () => (0, core_1.inject)(subscriptions_service_1.SubscriptionsService);
|
|
157
|
+
router.post('/payment-methods/setup', {
|
|
158
|
+
schema: {
|
|
159
|
+
...OPERATION,
|
|
160
|
+
summary: 'Start saving a payment method',
|
|
161
|
+
description: 'Starts saving a payment method of the user without a payment. The client confirms the ' +
|
|
162
|
+
'`clientSecret` of the next action with the library of the gateway; the saved method arrives ' +
|
|
163
|
+
'with a webhook of the gateway.',
|
|
164
|
+
body: schemas.SetupBody,
|
|
165
|
+
response: { 200: schemas.SetupResponse }
|
|
166
|
+
},
|
|
167
|
+
config: { errorCodes: GATEWAY_ERRORS }
|
|
168
|
+
}, async (request) => ({
|
|
169
|
+
nextAction: await payments().createSetup(customer(request.body))
|
|
170
|
+
}));
|
|
171
|
+
router.post('/payment-methods/:id/default', {
|
|
172
|
+
schema: {
|
|
173
|
+
...OPERATION,
|
|
174
|
+
summary: 'Set the default payment method',
|
|
175
|
+
description: 'Makes a saved payment method the one the subscriptions of the user are charged to.',
|
|
176
|
+
params: schemas.Id,
|
|
177
|
+
response: { 200: schemas.Record }
|
|
178
|
+
},
|
|
179
|
+
config: {
|
|
180
|
+
errorCodes: [...GATEWAY_ERRORS, common_1.ErrorCode.PaymentMethodNotFound]
|
|
181
|
+
}
|
|
182
|
+
}, async (request) => {
|
|
183
|
+
await ownMethod(request.params.id);
|
|
184
|
+
return payments().setDefaultPaymentMethod(request.params.id);
|
|
185
|
+
});
|
|
186
|
+
router.delete('/payment-methods/:id', {
|
|
187
|
+
schema: {
|
|
188
|
+
...OPERATION,
|
|
189
|
+
summary: 'Remove a payment method',
|
|
190
|
+
description: 'Removes a saved payment method, at the gateway too.',
|
|
191
|
+
params: schemas.Id,
|
|
192
|
+
response: { 204: typebox_1.Type.Null() }
|
|
193
|
+
},
|
|
194
|
+
config: {
|
|
195
|
+
errorCodes: [...GATEWAY_ERRORS, common_1.ErrorCode.PaymentMethodNotFound]
|
|
196
|
+
}
|
|
197
|
+
}, async (request, reply) => {
|
|
198
|
+
await ownMethod(request.params.id);
|
|
199
|
+
await payments().detachPaymentMethod(request.params.id);
|
|
200
|
+
return reply.code(204).send(null);
|
|
201
|
+
});
|
|
202
|
+
router.post('/payments/portal', {
|
|
203
|
+
schema: {
|
|
204
|
+
...OPERATION,
|
|
205
|
+
summary: 'Open the billing page of the gateway',
|
|
206
|
+
description: 'Creates a session of the page of the gateway where the user manages their payment methods, ' +
|
|
207
|
+
'subscriptions and invoices, and answers with its URL.',
|
|
208
|
+
body: schemas.PortalBody,
|
|
209
|
+
response: { 200: schemas.PortalResponse }
|
|
210
|
+
},
|
|
211
|
+
config: { errorCodes: GATEWAY_ERRORS }
|
|
212
|
+
}, async (request) => {
|
|
213
|
+
const { returnUrl, ...choice } = request.body;
|
|
214
|
+
return {
|
|
215
|
+
url: await subscriptions().createPortalSession(customer(choice), returnUrl)
|
|
216
|
+
};
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/** The routes of the subscriptions of an authenticated user, registered with `payments.subscriptions.enabled`. */
|
|
221
|
+
function registerSubscriptionRoutes() {
|
|
222
|
+
const schemas = { ...(0, payment_schemas_1.paymentRouteSchemas)(), ...(0, payment_schemas_1.subscriptionRouteSchemas)() };
|
|
223
|
+
(0, web_1.registerRoute)((router) => {
|
|
224
|
+
const subscriptions = () => (0, core_1.inject)(subscriptions_service_1.SubscriptionsService);
|
|
225
|
+
router.post('/payment-subscriptions/subscribe', {
|
|
226
|
+
schema: {
|
|
227
|
+
...OPERATION,
|
|
228
|
+
summary: 'Subscribe to a plan',
|
|
229
|
+
description: 'Subscribes the user to a plan, charged to a saved payment method. A subscription whose first ' +
|
|
230
|
+
'payment the bank wants confirmed stays `incomplete` until the client confirms the next action.',
|
|
231
|
+
body: schemas.SubscribeBody,
|
|
232
|
+
response: { 200: schemas.SubscriptionResponse }
|
|
233
|
+
},
|
|
234
|
+
config: {
|
|
235
|
+
errorCodes: [
|
|
236
|
+
...GATEWAY_ERRORS,
|
|
237
|
+
common_1.ErrorCode.PaymentPlanUnknown,
|
|
238
|
+
common_1.ErrorCode.PaymentMethodNotFound,
|
|
239
|
+
common_1.ErrorCode.PaymentDeclined
|
|
240
|
+
]
|
|
241
|
+
}
|
|
242
|
+
}, async (request) => {
|
|
243
|
+
const { plan, quantity, paymentMethodId, ...choice } = request.body;
|
|
244
|
+
return subscriptions().subscribe({
|
|
245
|
+
...customer(choice),
|
|
246
|
+
plan,
|
|
247
|
+
quantity,
|
|
248
|
+
paymentMethodId
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
router.post('/payment-subscriptions/checkout', {
|
|
252
|
+
schema: {
|
|
253
|
+
...OPERATION,
|
|
254
|
+
summary: 'Subscribe on the page of the gateway',
|
|
255
|
+
description: 'Starts a subscription on a hosted page of the gateway, where the user enters their payment ' +
|
|
256
|
+
'method: open the `url` of the `redirect` next action. The subscription starts with the webhook of ' +
|
|
257
|
+
'the completed page.',
|
|
258
|
+
body: schemas.SubscriptionCheckoutBody,
|
|
259
|
+
response: { 200: schemas.SubscriptionResponse }
|
|
260
|
+
},
|
|
261
|
+
config: {
|
|
262
|
+
errorCodes: [...GATEWAY_ERRORS, common_1.ErrorCode.PaymentPlanUnknown]
|
|
263
|
+
}
|
|
264
|
+
}, async (request) => {
|
|
265
|
+
const { plan, quantity, ...choice } = request.body;
|
|
266
|
+
return subscriptions().createCheckout({
|
|
267
|
+
...customer(choice),
|
|
268
|
+
plan,
|
|
269
|
+
quantity
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
router.post('/payment-subscriptions/:id/cancel', {
|
|
273
|
+
schema: {
|
|
274
|
+
...OPERATION,
|
|
275
|
+
summary: 'Cancel a subscription',
|
|
276
|
+
description: 'Cancels a subscription of the user: with the period they paid for, or at once with ' +
|
|
277
|
+
'`atPeriodEnd: false`.',
|
|
278
|
+
params: schemas.Id,
|
|
279
|
+
body: schemas.CancelSubscriptionBody,
|
|
280
|
+
response: { 200: schemas.Record }
|
|
281
|
+
},
|
|
282
|
+
config: { errorCodes: SUBSCRIPTION_ERRORS }
|
|
283
|
+
}, async (request) => {
|
|
284
|
+
await ownSubscription(request.params.id);
|
|
285
|
+
return subscriptions().cancel(request.params.id, request.body?.atPeriodEnd ?? true);
|
|
286
|
+
});
|
|
287
|
+
router.post('/payment-subscriptions/:id/resume', {
|
|
288
|
+
schema: {
|
|
289
|
+
...OPERATION,
|
|
290
|
+
summary: 'Keep a canceled subscription',
|
|
291
|
+
description: 'Keeps a subscription that was canceled with the end of its period.',
|
|
292
|
+
params: schemas.Id,
|
|
293
|
+
response: { 200: schemas.Record }
|
|
294
|
+
},
|
|
295
|
+
config: { errorCodes: SUBSCRIPTION_ERRORS }
|
|
296
|
+
}, async (request) => {
|
|
297
|
+
await ownSubscription(request.params.id);
|
|
298
|
+
return subscriptions().resume(request.params.id);
|
|
299
|
+
});
|
|
300
|
+
router.post('/payment-subscriptions/:id/plan', {
|
|
301
|
+
schema: {
|
|
302
|
+
...OPERATION,
|
|
303
|
+
summary: 'Change the plan of a subscription',
|
|
304
|
+
description: 'Moves a subscription of the user to another plan of its gateway, the difference charged or ' +
|
|
305
|
+
'credited for the rest of the period with `payments.subscriptions.prorate`.',
|
|
306
|
+
params: schemas.Id,
|
|
307
|
+
body: schemas.ChangePlanBody,
|
|
308
|
+
response: { 200: schemas.Record }
|
|
309
|
+
},
|
|
310
|
+
config: {
|
|
311
|
+
errorCodes: [...SUBSCRIPTION_ERRORS, common_1.ErrorCode.PaymentPlanUnknown]
|
|
312
|
+
}
|
|
313
|
+
}, async (request) => {
|
|
314
|
+
await ownSubscription(request.params.id);
|
|
315
|
+
return subscriptions().changePlan(request.params.id, request.body.plan, { quantity: request.body.quantity });
|
|
316
|
+
});
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
/** The routes of the admin roles: capturing, canceling, refunding and reading a payment again. */
|
|
320
|
+
function registerAdminRoutes() {
|
|
321
|
+
const schemas = (0, payment_schemas_1.paymentRouteSchemas)();
|
|
322
|
+
(0, web_1.registerRoute)((router) => {
|
|
323
|
+
const payments = () => (0, core_1.inject)(payments_service_1.PaymentsService);
|
|
324
|
+
const errorCodes = [
|
|
325
|
+
...GATEWAY_ERRORS,
|
|
326
|
+
common_1.ErrorCode.PaymentNotFound,
|
|
327
|
+
common_1.ErrorCode.PaymentInvalidState
|
|
328
|
+
];
|
|
329
|
+
router.post('/payments/:id/refund', {
|
|
330
|
+
schema: {
|
|
331
|
+
...OPERATION,
|
|
332
|
+
summary: 'Refund a payment',
|
|
333
|
+
description: 'Refunds a paid payment, all of it or the amount of the body, and answers with the ledger entry ' +
|
|
334
|
+
'of the refund.',
|
|
335
|
+
params: schemas.Id,
|
|
336
|
+
body: schemas.RefundBody,
|
|
337
|
+
response: { 200: schemas.Record }
|
|
338
|
+
},
|
|
339
|
+
config: {
|
|
340
|
+
errorCodes: [
|
|
341
|
+
...errorCodes,
|
|
342
|
+
common_1.ErrorCode.PaymentAmountInvalid,
|
|
343
|
+
common_1.ErrorCode.PaymentRefundExceeded
|
|
344
|
+
]
|
|
345
|
+
}
|
|
346
|
+
}, async (request) => payments().refundPayment(request.params.id, request.body ?? {}));
|
|
347
|
+
router.post('/payments/:id/capture', {
|
|
348
|
+
schema: {
|
|
349
|
+
...OPERATION,
|
|
350
|
+
summary: 'Capture an authorized payment',
|
|
351
|
+
description: 'Takes the money of an authorized payment, all of it or the amount of the body, the rest released.',
|
|
352
|
+
params: schemas.Id,
|
|
353
|
+
body: schemas.CaptureBody,
|
|
354
|
+
response: { 200: schemas.Record }
|
|
355
|
+
},
|
|
356
|
+
config: {
|
|
357
|
+
errorCodes: [...errorCodes, common_1.ErrorCode.PaymentAmountInvalid]
|
|
358
|
+
}
|
|
359
|
+
}, async (request) => payments().capturePayment(request.params.id, request.body?.amount));
|
|
360
|
+
router.post('/payments/:id/cancel', {
|
|
361
|
+
schema: {
|
|
362
|
+
...OPERATION,
|
|
363
|
+
summary: 'Cancel a payment',
|
|
364
|
+
description: 'Cancels a payment that is not paid, releasing its authorization.',
|
|
365
|
+
params: schemas.Id,
|
|
366
|
+
response: { 200: schemas.Record }
|
|
367
|
+
},
|
|
368
|
+
config: { errorCodes }
|
|
369
|
+
}, async (request) => payments().cancelPayment(request.params.id));
|
|
370
|
+
router.post('/payments/:id/sync', {
|
|
371
|
+
schema: {
|
|
372
|
+
...OPERATION,
|
|
373
|
+
summary: 'Read a payment from its gateway',
|
|
374
|
+
description: 'Reads a payment from its gateway and applies its state, i.e. after a webhook that never arrived.',
|
|
375
|
+
params: schemas.Id,
|
|
376
|
+
response: { 200: schemas.Record }
|
|
377
|
+
},
|
|
378
|
+
config: { errorCodes }
|
|
379
|
+
}, async (request) => (await payments().syncPayment(request.params.id)).payment);
|
|
380
|
+
}, { roles: config_1.paymentsRoutesConfig.ADMIN_ROLES });
|
|
381
|
+
}
|
|
382
|
+
/** The user of the request as the customer of a gateway. */
|
|
383
|
+
function customer(choice) {
|
|
384
|
+
const user = (0, core_1.currentAuthUser)();
|
|
385
|
+
return {
|
|
386
|
+
userId: user.id,
|
|
387
|
+
email: user.email,
|
|
388
|
+
gateway: choice.gateway,
|
|
389
|
+
country: choice.country
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
/** Answers as for an unknown payment method when it is the one of another user. */
|
|
393
|
+
async function ownMethod(id) {
|
|
394
|
+
const user = (0, core_1.currentAuthUser)();
|
|
395
|
+
const method = await (0, core_1.inject)(payments_service_1.PaymentsService).getPaymentMethod(id);
|
|
396
|
+
if (method.userId !== String(user?.id) && !(0, policies_1.isPaymentAdmin)(user)) {
|
|
397
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentMethodNotFound, `No payment method '${id}' found`, { id });
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
/** Answers as for an unknown subscription when it is the one of another user. */
|
|
401
|
+
async function ownSubscription(id) {
|
|
402
|
+
const user = (0, core_1.currentAuthUser)();
|
|
403
|
+
const subscription = await (0, core_1.inject)(subscriptions_service_1.SubscriptionsService).getSubscription(id);
|
|
404
|
+
if (subscription.userId !== String(user?.id) && !(0, policies_1.isPaymentAdmin)(user)) {
|
|
405
|
+
throw new common_1.PaymentError(common_1.ErrorCode.PaymentSubscriptionNotFound, `No subscription '${id}' found`, { id });
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
function escapeHtml(value) {
|
|
409
|
+
return value.replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
|
|
410
|
+
}
|