@tly-pay/vendure-plugin 0.0.0-stage → 1.0.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/CHANGELOG.md +38 -0
- package/LICENSE +21 -0
- package/README.md +192 -2
- package/assets/coins/arb.svg +10 -0
- package/assets/coins/base.svg +4 -0
- package/assets/coins/bln.svg +4 -0
- package/assets/coins/bnb.svg +13 -0
- package/assets/coins/btc.svg +1 -0
- package/assets/coins/busd.svg +7 -0
- package/assets/coins/coin.svg +1 -0
- package/assets/coins/dai.svg +1 -0
- package/assets/coins/doge.svg +109 -0
- package/assets/coins/eth.svg +10 -0
- package/assets/coins/jst.svg +11 -0
- package/assets/coins/link.svg +4 -0
- package/assets/coins/ltc.svg +4 -0
- package/assets/coins/op.svg +12 -0
- package/assets/coins/pol.svg +11 -0
- package/assets/coins/shib.svg +18 -0
- package/assets/coins/sol.svg +15 -0
- package/assets/coins/sun.svg +71 -0
- package/assets/coins/trx.svg +4 -0
- package/assets/coins/uni.svg +10 -0
- package/assets/coins/usdc.svg +6 -0
- package/assets/coins/usdd.svg +18 -0
- package/assets/coins/usdt.svg +1 -0
- package/assets/coins/wbtc.svg +16 -0
- package/assets/coins/weth.svg +17 -0
- package/assets/tly-pay-mark.svg +31 -0
- package/dashboard/api.ts +167 -0
- package/dashboard/appearance.tsx +253 -0
- package/dashboard/banner.tsx +72 -0
- package/dashboard/i18n/en.po +584 -0
- package/dashboard/index.tsx +33 -0
- package/dashboard/logic.ts +219 -0
- package/dashboard/messages.tsx +90 -0
- package/dashboard/notice.tsx +15 -0
- package/dashboard/order-block.tsx +21 -0
- package/dashboard/orders.tsx +246 -0
- package/dashboard/page.tsx +174 -0
- package/dashboard/settings.tsx +186 -0
- package/dashboard/use-connect.ts +46 -0
- package/dist/api.d.ts +169 -0
- package/dist/api.js +541 -0
- package/dist/client-ref.d.ts +75 -0
- package/dist/client-ref.js +165 -0
- package/dist/connect-flow.d.ts +65 -0
- package/dist/connect-flow.js +177 -0
- package/dist/connection-check.d.ts +28 -0
- package/dist/connection-check.js +49 -0
- package/dist/connection.d.ts +140 -0
- package/dist/connection.js +361 -0
- package/dist/contracts.d.ts +66 -0
- package/dist/contracts.js +151 -0
- package/dist/creation-service.d.ts +136 -0
- package/dist/creation-service.js +242 -0
- package/dist/handler.d.ts +13 -0
- package/dist/handler.js +45 -0
- package/dist/hosted-checkout.d.ts +3 -0
- package/dist/hosted-checkout.js +25 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +32 -0
- package/dist/ownership.d.ts +38 -0
- package/dist/ownership.js +38 -0
- package/dist/payment-sync.d.ts +45 -0
- package/dist/payment-sync.js +111 -0
- package/dist/persistence.d.ts +104 -0
- package/dist/persistence.js +405 -0
- package/dist/plugin.d.ts +26 -0
- package/dist/plugin.js +112 -0
- package/dist/public-api.d.ts +56 -0
- package/dist/public-api.js +221 -0
- package/dist/records.d.ts +53 -0
- package/dist/records.js +109 -0
- package/dist/release-config.d.ts +55 -0
- package/dist/release-config.js +107 -0
- package/dist/release-config.json +15 -0
- package/dist/secret-box.d.ts +19 -0
- package/dist/secret-box.js +65 -0
- package/dist/service.d.ts +267 -0
- package/dist/service.js +788 -0
- package/dist/signed-webhook.d.ts +67 -0
- package/dist/signed-webhook.js +119 -0
- package/dist/storefront/checkout.d.mts +86 -0
- package/dist/storefront/checkout.mjs +149 -0
- package/package.json +97 -4
package/dist/service.js
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.TlyPayService = exports.CHECKOUT_MESSAGES = exports.CHECKOUT_ICON_CATALOG = exports.CHECKER_CODE = exports.HANDLER_CODE = exports.TLY_PAY_PLUGIN_OPTIONS = void 0;
|
|
16
|
+
exports.assetMark = assetMark;
|
|
17
|
+
exports.acceptedMarks = acceptedMarks;
|
|
18
|
+
exports.checkoutIconOptions = checkoutIconOptions;
|
|
19
|
+
exports.coinList = coinList;
|
|
20
|
+
const node_crypto_1 = require("node:crypto");
|
|
21
|
+
const node_fs_1 = require("node:fs");
|
|
22
|
+
const node_path_1 = require("node:path");
|
|
23
|
+
const common_1 = require("@nestjs/common");
|
|
24
|
+
const core_1 = require("@vendure/core");
|
|
25
|
+
const generated_types_1 = require("@vendure/common/lib/generated-types");
|
|
26
|
+
const shared_constants_1 = require("@vendure/common/lib/shared-constants");
|
|
27
|
+
const client_ref_1 = require("./client-ref");
|
|
28
|
+
const connect_flow_1 = require("./connect-flow");
|
|
29
|
+
const connection_1 = require("./connection");
|
|
30
|
+
const connection_check_1 = require("./connection-check");
|
|
31
|
+
const contracts_1 = require("./contracts");
|
|
32
|
+
const creation_service_1 = require("./creation-service");
|
|
33
|
+
const ownership_1 = require("./ownership");
|
|
34
|
+
const payment_sync_1 = require("./payment-sync");
|
|
35
|
+
const persistence_1 = require("./persistence");
|
|
36
|
+
const public_api_1 = require("./public-api");
|
|
37
|
+
const records_1 = require("./records");
|
|
38
|
+
const release_config_1 = require("./release-config");
|
|
39
|
+
const secret_box_1 = require("./secret-box");
|
|
40
|
+
const signed_webhook_1 = require("./signed-webhook");
|
|
41
|
+
exports.TLY_PAY_PLUGIN_OPTIONS = Symbol("TLY_PAY_PLUGIN_OPTIONS");
|
|
42
|
+
exports.HANDLER_CODE = "tly-pay";
|
|
43
|
+
exports.CHECKER_CODE = "tly-pay-ready";
|
|
44
|
+
const LOG_CONTEXT = "TlyPay";
|
|
45
|
+
const SYNC_QUEUE = "tly-pay-sync";
|
|
46
|
+
const COINS_DIR = (0, node_path_1.join)(__dirname, "..", "assets", "coins");
|
|
47
|
+
const FALLBACK_COIN = "coin.svg";
|
|
48
|
+
/**
|
|
49
|
+
* Coins TLY Pay supports, in the order checkout shows their icons. This is the only place that holds
|
|
50
|
+
* the catalog: the Dashboard and the Shop API receive it as checkout icon options. Each mark is labelled
|
|
51
|
+
* with its uppercase form and drawn from `assets/coins/<mark>.svg`; USDT0 shares `usdt` (see `assetMark`).
|
|
52
|
+
*/
|
|
53
|
+
exports.CHECKOUT_ICON_CATALOG = ["usdt", "usdc", "dai", "eth", "btc", "bnb", "pol", "trx", "ltc"];
|
|
54
|
+
/**
|
|
55
|
+
* The checkout icon mark of an asset symbol: its lowercase symbol, except USDT0 (Arbitrum One), which is
|
|
56
|
+
* Tether USD and shares the `usdt` mark, so USDT and USDT0 show one icon.
|
|
57
|
+
*/
|
|
58
|
+
function assetMark(symbol) {
|
|
59
|
+
return symbol.toUpperCase() === "USDT0" ? "usdt" : symbol.toLowerCase();
|
|
60
|
+
}
|
|
61
|
+
/** Marks of the Store's assets, deduplicated in Store order; a symbol that is not a mark is skipped. */
|
|
62
|
+
function storeMarks(assets) {
|
|
63
|
+
return [...new Set(assets.map((asset) => assetMark(asset.symbol)).filter((mark) => client_ref_1.ICON_MARK.test(mark)))];
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Marks the Store accepts now, in option order: catalog marks first, then the others in Store order.
|
|
67
|
+
* This is the selection while none was saved and the one Sync with TLY Pay store saves.
|
|
68
|
+
*/
|
|
69
|
+
function acceptedMarks(assets) {
|
|
70
|
+
const accepted = storeMarks(assets);
|
|
71
|
+
return [...new Set([...exports.CHECKOUT_ICON_CATALOG, ...accepted])].filter((mark) => accepted.includes(mark));
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Checkout icon options in the order checkout shows them: the catalog, then the other marks the Store
|
|
75
|
+
* accepts in Store order, then other chosen marks, so every chosen mark stays listed and can be removed.
|
|
76
|
+
* Each option is labelled with its uppercase mark (`USDT` for the Tether mark USDT0 shares).
|
|
77
|
+
*/
|
|
78
|
+
function checkoutIconOptions(assets, chosen, iconUrl) {
|
|
79
|
+
const accepted = storeMarks(assets);
|
|
80
|
+
return [...new Set([...exports.CHECKOUT_ICON_CATALOG, ...accepted, ...chosen.filter((mark) => client_ref_1.ICON_MARK.test(mark))])]
|
|
81
|
+
.map((mark) => ({ mark, label: mark.toUpperCase(), iconUrl: iconUrl(mark), accepted: accepted.includes(mark) }));
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Customer copy of the Shop API, in English. Each entry is looked up in Vendure's message catalogs as
|
|
85
|
+
* `tlyPay.<name>` first, so a host translates it with `I18nService.addTranslation()`. `listLocale` is
|
|
86
|
+
* the BCP 47 tag whose list format joins the coin names, so a translated sentence gets a list in its
|
|
87
|
+
* own language.
|
|
88
|
+
*/
|
|
89
|
+
exports.CHECKOUT_MESSAGES = {
|
|
90
|
+
title: "Crypto payment",
|
|
91
|
+
coinNames: "Pay with {list}.",
|
|
92
|
+
coinNamesGeneric: "Pay with supported crypto assets through TLY Pay Checkout.",
|
|
93
|
+
listLocale: "en",
|
|
94
|
+
};
|
|
95
|
+
/** A checkout message in the request's language when a catalog has it, else its English text. */
|
|
96
|
+
function checkoutMessage(ctx, name, list = "") {
|
|
97
|
+
const key = `${client_ref_1.CLIENT_REF_NAMESPACE}.${name}`;
|
|
98
|
+
const text = ctx.translate(key, { list });
|
|
99
|
+
// Vendure answers the key itself for an entry no catalog has.
|
|
100
|
+
return text === key ? exports.CHECKOUT_MESSAGES[name].replace("{list}", () => list) : text;
|
|
101
|
+
}
|
|
102
|
+
/** Joins coin labels with the list format of a locale: "USDT and USDC", "USDT, USDC, and DAI" in English. */
|
|
103
|
+
function coinList(labels, locale) {
|
|
104
|
+
const join = (tag) => new Intl.ListFormat(tag, { style: "long", type: "conjunction" }).format(labels);
|
|
105
|
+
try {
|
|
106
|
+
return join(locale.replace(/_/g, "-"));
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return join(exports.CHECKOUT_MESSAGES.listLocale);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The plugin's runtime: connection, checkout, Webhook intake and Payment synchronization on Vendure's
|
|
114
|
+
* own services. Every request to TLY Pay uses the saved connection and the packaged release constants
|
|
115
|
+
* with the Origins of the site chosen in Settings > Advanced; an incomplete release fails closed.
|
|
116
|
+
*/
|
|
117
|
+
let TlyPayService = class TlyPayService {
|
|
118
|
+
options;
|
|
119
|
+
connection;
|
|
120
|
+
clientRefs;
|
|
121
|
+
jobQueues;
|
|
122
|
+
requestContexts;
|
|
123
|
+
orders;
|
|
124
|
+
activeOrders;
|
|
125
|
+
paymentMethods;
|
|
126
|
+
history;
|
|
127
|
+
config;
|
|
128
|
+
translator;
|
|
129
|
+
events;
|
|
130
|
+
/** Packaged constants; the Origins in effect come from `release()`. */
|
|
131
|
+
packaged = (0, release_config_1.releaseConfig)();
|
|
132
|
+
connections;
|
|
133
|
+
flow;
|
|
134
|
+
associations;
|
|
135
|
+
inbox;
|
|
136
|
+
checkoutSettings;
|
|
137
|
+
iconSettings;
|
|
138
|
+
coinNameSettings;
|
|
139
|
+
siteSettings;
|
|
140
|
+
sync;
|
|
141
|
+
coins;
|
|
142
|
+
queue;
|
|
143
|
+
constructor(options, connection, clientRefs, jobQueues, requestContexts, orders, activeOrders, paymentMethods, history, config, translator, events) {
|
|
144
|
+
this.options = options;
|
|
145
|
+
this.connection = connection;
|
|
146
|
+
this.clientRefs = clientRefs;
|
|
147
|
+
this.jobQueues = jobQueues;
|
|
148
|
+
this.requestContexts = requestContexts;
|
|
149
|
+
this.orders = orders;
|
|
150
|
+
this.activeOrders = activeOrders;
|
|
151
|
+
this.paymentMethods = paymentMethods;
|
|
152
|
+
this.history = history;
|
|
153
|
+
this.config = config;
|
|
154
|
+
this.translator = translator;
|
|
155
|
+
this.events = events;
|
|
156
|
+
if (options === undefined)
|
|
157
|
+
throw new TypeError("Configure the plugin with TlyPayPlugin.init({ publicUrl, secretKey })");
|
|
158
|
+
const records = new records_1.SealedRecords(new records_1.TypeOrmRecordStore(connection), new secret_box_1.SecretBox(options.secretKey));
|
|
159
|
+
const batch = this.packaged?.recoveryBatchSize ?? 1;
|
|
160
|
+
this.siteSettings = new client_ref_1.TlyPaySiteSettings(connection);
|
|
161
|
+
this.connections = new connection_1.ConnectionService({ records, release: () => this.release(), publicUrl: options.publicUrl,
|
|
162
|
+
api: (apiKey, release) => new public_api_1.PublicApiClient(release, apiKey) });
|
|
163
|
+
this.flow = new connect_flow_1.ConnectFlow(records, this.connections);
|
|
164
|
+
this.associations = new persistence_1.TypeOrmAssociationStore(connection, batch);
|
|
165
|
+
this.inbox = new persistence_1.TypeOrmEventInbox(connection, batch);
|
|
166
|
+
this.checkoutSettings = new client_ref_1.TlyPayCheckoutSettings(connection);
|
|
167
|
+
this.iconSettings = new client_ref_1.TlyPayCheckoutIconSettings(connection);
|
|
168
|
+
this.coinNameSettings = new client_ref_1.TlyPayCoinNamesSettings(connection);
|
|
169
|
+
this.sync = new payment_sync_1.PaymentSync(this.associations, this.inbox, {
|
|
170
|
+
settle: (intent) => this.settleOrder(intent),
|
|
171
|
+
note: (intent, status) => this.noteOrder(intent, status),
|
|
172
|
+
}, () => this.connections.get(), (apiKey) => this.api(apiKey), () => this.clientRefs.get(), this.packaged?.paymentRecoveryDelaySecs ?? 0);
|
|
173
|
+
this.coins = new Set((0, node_fs_1.existsSync)(COINS_DIR) ? (0, node_fs_1.readdirSync)(COINS_DIR).filter((name) => /^[a-z0-9_]+\.svg$/.test(name)) : []);
|
|
174
|
+
}
|
|
175
|
+
async onModuleInit() {
|
|
176
|
+
this.queue = await this.jobQueues.createQueue({
|
|
177
|
+
name: SYNC_QUEUE,
|
|
178
|
+
process: async (job) => {
|
|
179
|
+
const outcome = await this.sync.sync(job.data.paymentId);
|
|
180
|
+
if (outcome !== "applied" && outcome !== "settled" && outcome !== "already_settled") {
|
|
181
|
+
core_1.Logger.warn(`Payment ${job.data.paymentId} was not applied: ${outcome}`, LOG_CONTEXT);
|
|
182
|
+
}
|
|
183
|
+
return { outcome };
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
this.events.ofType(core_1.OrderStateTransitionEvent).subscribe((event) => {
|
|
187
|
+
if (event.toState !== "Cancelled")
|
|
188
|
+
return;
|
|
189
|
+
this.cancelForOrder(event.ctx.channel.token, event.order.code).catch((error) => {
|
|
190
|
+
core_1.Logger.error(`TLY Pay Payment of cancelled Order ${event.order.code} could not be cancelled: ${error.message}`, LOG_CONTEXT);
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* After Vendure cancels an Order: cancels its TLY Pay Payments that are still open, so a cancelled Order
|
|
196
|
+
* cannot be paid (as the WooCommerce and Medusa plugins do). A Payment that received funds or is closed,
|
|
197
|
+
* or that belongs to another TLY Store than the connected one, is left as it is. The change reaches the
|
|
198
|
+
* Orders view through the notification and the queued sync. Answers the resulting status per Payment.
|
|
199
|
+
*/
|
|
200
|
+
async cancelForOrder(channelToken, orderCode) {
|
|
201
|
+
const intents = (await this.associations.findOrderIntents(channelToken, orderCode))
|
|
202
|
+
.filter((intent) => intent.paymentId !== null);
|
|
203
|
+
if (intents.length === 0)
|
|
204
|
+
return [];
|
|
205
|
+
const connection = await this.connections.get();
|
|
206
|
+
if (connection === null)
|
|
207
|
+
return [];
|
|
208
|
+
const api = await this.api(connection.apiKey);
|
|
209
|
+
const results = [];
|
|
210
|
+
for (const intent of intents) {
|
|
211
|
+
if (intent.storeId !== connection.storeId)
|
|
212
|
+
continue;
|
|
213
|
+
const view = await api.getPayment(intent.paymentId);
|
|
214
|
+
if (view.status !== "open") {
|
|
215
|
+
results.push(view.status);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
let status;
|
|
219
|
+
try {
|
|
220
|
+
status = (await api.cancelPayment(view.paymentId)).status;
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
// 409: the Payment left `open` meanwhile (paid, expired); the sync below reads its status.
|
|
224
|
+
if (!(error instanceof public_api_1.TlyApiError) || error.httpStatus !== 409)
|
|
225
|
+
throw error;
|
|
226
|
+
status = "conflict";
|
|
227
|
+
}
|
|
228
|
+
core_1.Logger.info(`TLY Pay Payment ${view.paymentId} of cancelled Order ${orderCode}: ${status}`, LOG_CONTEXT);
|
|
229
|
+
results.push(status);
|
|
230
|
+
await this.enqueue(view.paymentId);
|
|
231
|
+
}
|
|
232
|
+
return results;
|
|
233
|
+
}
|
|
234
|
+
/** The release constants with the Origins of the stored site, or null for an incomplete release. */
|
|
235
|
+
async release() {
|
|
236
|
+
return this.packaged === null ? null : (0, release_config_1.siteRelease)(this.packaged, await this.siteSettings.get());
|
|
237
|
+
}
|
|
238
|
+
async api(apiKey) {
|
|
239
|
+
return this.connections.api(apiKey);
|
|
240
|
+
}
|
|
241
|
+
/** Base of the plugin's public routes under the host's public URL. */
|
|
242
|
+
publicBase() {
|
|
243
|
+
return this.options.publicUrl.replace(/\/+$/, "");
|
|
244
|
+
}
|
|
245
|
+
callbackUrl() {
|
|
246
|
+
return this.publicBase() + connection_1.CALLBACK_PATH;
|
|
247
|
+
}
|
|
248
|
+
/** The bundled icon file of a mark, or the neutral fallback. */
|
|
249
|
+
coinFile(mark) {
|
|
250
|
+
const name = `${mark}.svg`;
|
|
251
|
+
return this.coins.has(name) ? name : FALLBACK_COIN;
|
|
252
|
+
}
|
|
253
|
+
/** Checkout icon options for the Store's assets and the chosen marks, with the plugin's public icon URLs. */
|
|
254
|
+
iconOptions(assets, chosen) {
|
|
255
|
+
return checkoutIconOptions(assets, chosen, (mark) => `${this.publicBase()}/tly-pay/coins/${this.coinFile(mark)}`);
|
|
256
|
+
}
|
|
257
|
+
/** The marks the merchant chose, which may be none, or every mark the Store accepts while none was saved. */
|
|
258
|
+
async chosenMarks(assets) {
|
|
259
|
+
return await this.iconSettings.get() ?? acceptedMarks(assets);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Re-reads the Store through the connection check, then saves the coins it accepts now as the checkout
|
|
263
|
+
* icons. A failed check reports its code and keeps the previous choice; the coin names switch and the
|
|
264
|
+
* title are not changed.
|
|
265
|
+
*/
|
|
266
|
+
async syncCheckoutIcons() {
|
|
267
|
+
await this.connections.refresh();
|
|
268
|
+
const status = await this.connections.status();
|
|
269
|
+
// Without a saved connection the check cannot run.
|
|
270
|
+
const code = status.connected ? status.lastErr : "api_key_required";
|
|
271
|
+
if (code !== "")
|
|
272
|
+
return { result: code, retry: false };
|
|
273
|
+
await this.iconSettings.set(acceptedMarks(status.paymentAssets));
|
|
274
|
+
return { result: "checkout_icons_synced", retry: false };
|
|
275
|
+
}
|
|
276
|
+
coinPath(file) {
|
|
277
|
+
return this.coins.has(file) ? (0, node_path_1.join)(COINS_DIR, file) : null;
|
|
278
|
+
}
|
|
279
|
+
// Connection
|
|
280
|
+
async status() {
|
|
281
|
+
return this.connections.status();
|
|
282
|
+
}
|
|
283
|
+
async start(ctx, adminUrl, popup) {
|
|
284
|
+
try {
|
|
285
|
+
const url = await this.flow.start({ userId: String(ctx.activeUserId ?? ""), adminUrl, popup,
|
|
286
|
+
currency: ctx.channel.defaultCurrencyCode });
|
|
287
|
+
return { url, result: "started" };
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
if (error instanceof connection_1.ConnectionError)
|
|
291
|
+
return { url: null, result: error.code };
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
complete(ctx, state, code) {
|
|
296
|
+
return this.flow.complete(state, code, String(ctx.activeUserId ?? ""));
|
|
297
|
+
}
|
|
298
|
+
async disconnect(confirm) {
|
|
299
|
+
if (!confirm)
|
|
300
|
+
return { result: "disconnect_unconfirmed", retry: false };
|
|
301
|
+
await this.connections.disconnect();
|
|
302
|
+
return { result: "disconnected", retry: false };
|
|
303
|
+
}
|
|
304
|
+
async refreshConnection() {
|
|
305
|
+
await this.connections.refresh();
|
|
306
|
+
}
|
|
307
|
+
// Checkout
|
|
308
|
+
/** Whether the payment method may be offered for this Order: see `ConnectionService.available`. */
|
|
309
|
+
async eligible(order) {
|
|
310
|
+
return await this.connections.available(order.currencyCode) !== null;
|
|
311
|
+
}
|
|
312
|
+
async presentation(ctx) {
|
|
313
|
+
const order = ctx.session === undefined ? undefined : await this.activeOrders.getActiveOrder(ctx, undefined);
|
|
314
|
+
const release = await this.release();
|
|
315
|
+
const connection = release === null ? null
|
|
316
|
+
: await this.connections.available(order?.currencyCode ?? ctx.currencyCode);
|
|
317
|
+
const assets = connection?.paymentAssets ?? [];
|
|
318
|
+
const chosen = connection === null ? [] : await this.chosenMarks(assets);
|
|
319
|
+
const icons = this.iconOptions(assets, chosen).filter((option) => chosen.includes(option.mark))
|
|
320
|
+
.map(({ mark, label, iconUrl }) => ({ mark, label, iconUrl }));
|
|
321
|
+
return {
|
|
322
|
+
available: connection !== null,
|
|
323
|
+
checkoutMode: await this.checkoutSettings.get(),
|
|
324
|
+
widgetScriptUrl: release === null ? "" : (0, release_config_1.widgetScriptUrl)(release),
|
|
325
|
+
widgetActionTimeoutSecs: release?.widgetActionTimeoutSecs ?? 0,
|
|
326
|
+
paidStatuses: [...contracts_1.PAID_STATUSES],
|
|
327
|
+
title: (await this.checkoutTitle(ctx)).title,
|
|
328
|
+
coinNames: connection !== null && await this.coinNameSettings.get() ? coinNamesText(ctx, icons, assets) : null,
|
|
329
|
+
icons,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* The checkout title and the payment method it belongs to. Vendure's native, translatable name of the
|
|
334
|
+
* Channel's TLY Pay payment method is the title source: it is what `eligiblePaymentMethods` and the
|
|
335
|
+
* Dashboard show, and the merchant edits it under Settings > Payment methods. The method is the one a
|
|
336
|
+
* Payment is created with (the enabled one, else the first); without a method or a name the title is
|
|
337
|
+
* the default.
|
|
338
|
+
*/
|
|
339
|
+
async checkoutTitle(ctx) {
|
|
340
|
+
const methods = await this.channelMethods(ctx);
|
|
341
|
+
const method = methods.find((candidate) => candidate.enabled) ?? methods[0];
|
|
342
|
+
let name = "";
|
|
343
|
+
if (method !== undefined) {
|
|
344
|
+
try {
|
|
345
|
+
name = (this.translator.translate(method, ctx).name ?? "").trim();
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
// A method without a translation has no name to show.
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return { title: name === "" ? checkoutMessage(ctx, "title") : name, methodId: method?.id ?? null };
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Creates or recovers the Payment of the active Order in `ArrangingPayment`, using the Channel's
|
|
355
|
+
* enabled TLY Pay payment method. The Order's existing Payment of the connected Store, for the same
|
|
356
|
+
* currency and amount, is continued even after the Store changed its pricing currency; a new Payment
|
|
357
|
+
* needs the connection to be available for the Order's currency.
|
|
358
|
+
*/
|
|
359
|
+
async createPayment(ctx, returnUrl) {
|
|
360
|
+
const release = await this.release();
|
|
361
|
+
if (release === null)
|
|
362
|
+
throw new creation_service_1.CheckoutRejected("connection_unavailable");
|
|
363
|
+
const order = ctx.session === undefined ? undefined : await this.activeOrders.getActiveOrder(ctx, undefined);
|
|
364
|
+
if (order === undefined)
|
|
365
|
+
throw new creation_service_1.CheckoutRejected("no_active_order");
|
|
366
|
+
if (order.state !== "ArrangingPayment")
|
|
367
|
+
throw new creation_service_1.CheckoutRejected("order_state_invalid");
|
|
368
|
+
const method = (await this.channelMethods(ctx)).find((candidate) => candidate.enabled);
|
|
369
|
+
const connection = await this.connections.get();
|
|
370
|
+
if (method === undefined || connection === null)
|
|
371
|
+
throw new creation_service_1.CheckoutRejected("checkout_unavailable");
|
|
372
|
+
const creation = await this.creation(connection, release);
|
|
373
|
+
let created;
|
|
374
|
+
try {
|
|
375
|
+
created = await creation.createOrRecover({
|
|
376
|
+
channelToken: ctx.channel.token, orderCode: order.code, paymentMethodCode: method.code,
|
|
377
|
+
amountMinor: order.totalWithTax, currencyCode: order.currencyCode,
|
|
378
|
+
checkoutMode: await this.checkoutSettings.get(), returnUrl,
|
|
379
|
+
}, async () => await this.connections.available(order.currencyCode) !== null);
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
if (error instanceof creation_service_1.CheckoutRejected)
|
|
383
|
+
throw error;
|
|
384
|
+
core_1.Logger.warn(`Payment creation for Order ${order.code} did not complete: ${error.message}`, LOG_CONTEXT);
|
|
385
|
+
throw new creation_service_1.CheckoutRejected("payment_pending");
|
|
386
|
+
}
|
|
387
|
+
const embedded = (0, creation_service_1.embeddedBody)(created.requestBody);
|
|
388
|
+
const body = JSON.parse(created.requestBody);
|
|
389
|
+
return {
|
|
390
|
+
paymentId: created.view.paymentId,
|
|
391
|
+
checkoutMode: embedded ? "embedded" : "hosted",
|
|
392
|
+
hostedUrl: created.hostedUrl,
|
|
393
|
+
returnUrl: embedded && typeof body.return_url === "string" ? body.return_url : null,
|
|
394
|
+
widgetScriptUrl: (0, release_config_1.widgetScriptUrl)(release),
|
|
395
|
+
widgetActionTimeoutSecs: release.widgetActionTimeoutSecs,
|
|
396
|
+
paidStatuses: [...contracts_1.PAID_STATUSES],
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Whether an admin context may add a verified paid Payment of this Order, Channel and total. Vendure
|
|
401
|
+
* runs the eligibility checker again when the plugin settles, so a Payment created before the Store
|
|
402
|
+
* changed its pricing currency or readiness still settles; customers are offered the method only
|
|
403
|
+
* while the connection is available.
|
|
404
|
+
*/
|
|
405
|
+
async settlable(ctx, order) {
|
|
406
|
+
if (ctx.apiType !== "admin")
|
|
407
|
+
return false;
|
|
408
|
+
const intents = await this.associations.findOrderIntents(ctx.channel.token, order.code);
|
|
409
|
+
return intents.some((intent) => intent.status !== null
|
|
410
|
+
&& contracts_1.PAID_STATUSES.includes(intent.status) && matchesPayment(order, intent.requestBody));
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Validates the settlement the plugin itself requested for a verified paid Payment of this Order,
|
|
414
|
+
* Channel and amount; every other call is declined.
|
|
415
|
+
*/
|
|
416
|
+
async verifySettlement(ctx, order, amount, paymentId) {
|
|
417
|
+
if (typeof paymentId !== "string")
|
|
418
|
+
return null;
|
|
419
|
+
const intent = await this.associations.findByPaymentId(paymentId);
|
|
420
|
+
if (intent === null || intent.orderCode !== order.code || intent.channelToken !== ctx.channel.token
|
|
421
|
+
|| intent.status === null || !contracts_1.PAID_STATUSES.includes(intent.status)
|
|
422
|
+
|| sourceRaw(intent.requestBody) !== String(amount)) {
|
|
423
|
+
return null;
|
|
424
|
+
}
|
|
425
|
+
return intent.paymentId;
|
|
426
|
+
}
|
|
427
|
+
// Webhook
|
|
428
|
+
/**
|
|
429
|
+
* Handles one Webhook delivery and returns the answer to write: 401 for missing or malformed
|
|
430
|
+
* headers, a rejected signature or timestamp; 503 while not connected or while storage or creation
|
|
431
|
+
* recovery fails transiently; 400 for a verified body that is not a valid Event, a connection check
|
|
432
|
+
* naming another Endpoint, or invalid Payment fields of a known Payment; 200 with the site's facts
|
|
433
|
+
* and a signed acknowledgment for TLY Pay's connection check; and 204 once a local Event is stored,
|
|
434
|
+
* a foreign one is ignored or the signed event type is one this version does not know.
|
|
435
|
+
*/
|
|
436
|
+
async webhook(body, headers) {
|
|
437
|
+
const release = this.packaged;
|
|
438
|
+
const connection = release === null ? null : await this.connections.get();
|
|
439
|
+
if (release === null || connection === null)
|
|
440
|
+
return { status: 503 };
|
|
441
|
+
let request;
|
|
442
|
+
try {
|
|
443
|
+
request = (0, signed_webhook_1.verifySignedRequest)(body, headers, [connection.webhookSecret, connection.pendingWebhookSecret].filter((secret) => secret !== ""), Math.floor(Date.now() / 1000), release.webhookToleranceSecs);
|
|
444
|
+
}
|
|
445
|
+
catch (error) {
|
|
446
|
+
return { status: error instanceof signed_webhook_1.InvalidSignedEvent ? 400 : 401 };
|
|
447
|
+
}
|
|
448
|
+
if (request.eventType === signed_webhook_1.CONNECTION_CHECK) {
|
|
449
|
+
try {
|
|
450
|
+
(0, signed_webhook_1.verifyConnectionCheck)(request, connection.endpointId);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
return { status: 400 };
|
|
454
|
+
}
|
|
455
|
+
// A check is not an event: nothing is stored or queued.
|
|
456
|
+
return (0, connection_check_1.connectionCheckAnswer)(request, { pluginVersion: (0, connection_check_1.pluginVersion)(), platformVersion: core_1.VENDURE_VERSION,
|
|
457
|
+
gatewayEnabled: await this.gatewayEnabled() });
|
|
458
|
+
}
|
|
459
|
+
// A signed event type this version does not know is acknowledged and ignored.
|
|
460
|
+
if (request.eventType !== null && request.eventType !== signed_webhook_1.PAYMENT_UPDATED)
|
|
461
|
+
return { status: 204 };
|
|
462
|
+
let event;
|
|
463
|
+
try {
|
|
464
|
+
event = (0, signed_webhook_1.paymentEvent)(request);
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
return { status: 400 };
|
|
468
|
+
}
|
|
469
|
+
return { status: await this.receivePayment(event, connection, body) };
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* The native payment method switch for the connection check: at least one PaymentMethod using the
|
|
473
|
+
* TLY Pay handler is enabled, in any Channel. The connection's readiness takes no part.
|
|
474
|
+
*/
|
|
475
|
+
async gatewayEnabled() {
|
|
476
|
+
const methods = await this.connection.getRepository(undefined, core_1.PaymentMethod).find({ where: { enabled: true } });
|
|
477
|
+
return methods.some((method) => method.handler?.code === exports.HANDLER_CODE);
|
|
478
|
+
}
|
|
479
|
+
async receivePayment(event, connection, body) {
|
|
480
|
+
const decision = await (0, ownership_1.decideOwnership)(event, await this.clientRefs.get(), this.associations, await this.creation(connection));
|
|
481
|
+
if (decision.action === "ignore") {
|
|
482
|
+
if (decision.reason === "no_intent") {
|
|
483
|
+
core_1.Logger.warn(`Event ${event.eventId} of Payment ${event.paymentId} has no local intent`, LOG_CONTEXT);
|
|
484
|
+
}
|
|
485
|
+
return 204;
|
|
486
|
+
}
|
|
487
|
+
if (decision.action !== "process") {
|
|
488
|
+
if (decision.action === "reject")
|
|
489
|
+
core_1.Logger.error(`Event ${event.eventId} has invalid Payment fields`, LOG_CONTEXT);
|
|
490
|
+
return decision.httpStatus;
|
|
491
|
+
}
|
|
492
|
+
try {
|
|
493
|
+
const stored = await this.inbox.store({
|
|
494
|
+
eventId: event.eventId, paymentId: event.paymentId, status: decision.payment.status,
|
|
495
|
+
statusVersion: event.statusVersion, occurredAt: decision.payment.occurredAt,
|
|
496
|
+
bodyHash: (0, node_crypto_1.createHash)("sha256").update(body).digest("hex"), receivedAt: new Date(),
|
|
497
|
+
});
|
|
498
|
+
if (stored === "conflict") {
|
|
499
|
+
core_1.Logger.error(`Event ${event.eventId} was received again with other content; the stored Event is kept`, LOG_CONTEXT);
|
|
500
|
+
return 204;
|
|
501
|
+
}
|
|
502
|
+
await this.enqueue(event.paymentId);
|
|
503
|
+
}
|
|
504
|
+
catch (error) {
|
|
505
|
+
core_1.Logger.warn(`Event ${event.eventId} could not be stored: ${error.message}`, LOG_CONTEXT);
|
|
506
|
+
return 503;
|
|
507
|
+
}
|
|
508
|
+
return 204;
|
|
509
|
+
}
|
|
510
|
+
async enqueue(paymentId) {
|
|
511
|
+
if (this.queue === undefined)
|
|
512
|
+
throw new Error("TLY Pay job queue is not ready");
|
|
513
|
+
await this.queue.add({ paymentId });
|
|
514
|
+
}
|
|
515
|
+
// Scheduled work
|
|
516
|
+
/** One run of the recovery task: an early connection check, creation recovery and stored Events. */
|
|
517
|
+
async recover(now = new Date()) {
|
|
518
|
+
if (this.packaged === null)
|
|
519
|
+
return;
|
|
520
|
+
if (await this.connections.earlyCheckDue())
|
|
521
|
+
await this.connections.refresh();
|
|
522
|
+
const connection = await this.connections.get();
|
|
523
|
+
if (connection === null)
|
|
524
|
+
return;
|
|
525
|
+
try {
|
|
526
|
+
await (await this.creation(connection)).recoverDue(now);
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
core_1.Logger.warn(`Payment creation recovery did not complete: ${error.message}`, LOG_CONTEXT);
|
|
530
|
+
}
|
|
531
|
+
const due = await this.inbox.duePayments(new Date(now.getTime() - this.packaged.paymentRecoveryDelaySecs * 1000), now);
|
|
532
|
+
for (const paymentId of due)
|
|
533
|
+
await this.enqueue(paymentId);
|
|
534
|
+
}
|
|
535
|
+
// Orders view
|
|
536
|
+
async listOrders(ctx, filter, skip, take) {
|
|
537
|
+
const limit = this.config.apiOptions.adminListQueryLimit;
|
|
538
|
+
const page = await this.associations.list(persistence_1.ORDER_FILTERS[filter] === undefined ? "all" : filter, Math.max(0, skip), Math.min(Math.max(1, take), limit), await this.channelScope(ctx));
|
|
539
|
+
const orders = await this.ordersByCode(ctx, page.items.map((row) => row.orderCode));
|
|
540
|
+
return { items: page.items.map((row) => this.row(row, orders.get(row.orderCode))), totalItems: page.totalItems,
|
|
541
|
+
counts: page.counts };
|
|
542
|
+
}
|
|
543
|
+
/** Local facts, live status and stored Events of one intent; the live read happens once per call. */
|
|
544
|
+
async orderDetail(ctx, id) {
|
|
545
|
+
const row = await this.associations.findById(id);
|
|
546
|
+
const scope = await this.channelScope(ctx);
|
|
547
|
+
if (row === null || scope !== null && row.channelToken !== scope)
|
|
548
|
+
return null;
|
|
549
|
+
const order = (await this.ordersByCode(ctx, [row.orderCode])).get(row.orderCode);
|
|
550
|
+
const body = JSON.parse(row.requestBody);
|
|
551
|
+
let live = null;
|
|
552
|
+
let liveErr = null;
|
|
553
|
+
if (row.paymentId !== null) {
|
|
554
|
+
const connection = await this.connections.get();
|
|
555
|
+
if (connection === null || connection.storeId !== row.storeId) {
|
|
556
|
+
liveErr = "connection_unavailable";
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
try {
|
|
560
|
+
live = await (await this.api(connection.apiKey)).getPayment(row.paymentId);
|
|
561
|
+
}
|
|
562
|
+
catch (error) {
|
|
563
|
+
liveErr = error instanceof public_api_1.TlyApiError ? error.code : "invalid_response";
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
const events = row.paymentId === null ? [] : await this.inbox.forPayment(row.paymentId);
|
|
568
|
+
return {
|
|
569
|
+
row: this.row(row, order),
|
|
570
|
+
checkoutOrigin: typeof body.checkout_origin === "string" ? body.checkout_origin : null,
|
|
571
|
+
returnUrl: typeof body.return_url === "string" ? body.return_url : null,
|
|
572
|
+
clientRef: typeof body.client_ref === "string" ? body.client_ref : null,
|
|
573
|
+
live, liveErr, events,
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
/** The latest intent of a Vendure Order, for the Order detail block. */
|
|
577
|
+
async intentForOrder(ctx, orderCode) {
|
|
578
|
+
const intents = await this.associations.findOrderIntents(ctx.channel.token, orderCode);
|
|
579
|
+
return intents[0]?.id ?? null;
|
|
580
|
+
}
|
|
581
|
+
async reconcile(ctx, id) {
|
|
582
|
+
const row = await this.associations.findById(id);
|
|
583
|
+
const scope = await this.channelScope(ctx);
|
|
584
|
+
if (row === null || row.paymentId === null || scope !== null && row.channelToken !== scope) {
|
|
585
|
+
return { result: "reconcile_unavailable", retry: false };
|
|
586
|
+
}
|
|
587
|
+
try {
|
|
588
|
+
await this.enqueue(row.paymentId);
|
|
589
|
+
}
|
|
590
|
+
catch {
|
|
591
|
+
return { result: "reconcile_failed", retry: false };
|
|
592
|
+
}
|
|
593
|
+
return { result: "reconcile_scheduled", retry: false };
|
|
594
|
+
}
|
|
595
|
+
// Payment method of the current Channel
|
|
596
|
+
/** `missing`, `disabled`, `no_checker` or `ready`. */
|
|
597
|
+
async methodState(ctx) {
|
|
598
|
+
const methods = await this.channelMethods(ctx);
|
|
599
|
+
if (methods.length === 0)
|
|
600
|
+
return "missing";
|
|
601
|
+
if (!methods.some((method) => method.enabled))
|
|
602
|
+
return "disabled";
|
|
603
|
+
return methods.some((method) => method.enabled && method.checker?.code === exports.CHECKER_CODE) ? "ready" : "no_checker";
|
|
604
|
+
}
|
|
605
|
+
async createMethod(ctx, name) {
|
|
606
|
+
if (await this.methodState(ctx) !== "missing")
|
|
607
|
+
return { result: "payment_method_exists", retry: false };
|
|
608
|
+
const title = name.trim();
|
|
609
|
+
if (title === "" || title.length > 255)
|
|
610
|
+
return { result: "payment_method_invalid", retry: false };
|
|
611
|
+
await this.paymentMethods.create(ctx, {
|
|
612
|
+
code: ctx.channel.code === shared_constants_1.DEFAULT_CHANNEL_CODE ? exports.HANDLER_CODE
|
|
613
|
+
: `${exports.HANDLER_CODE}-${ctx.channel.code}`.toLowerCase().replace(/[^a-z0-9-]/g, "-"), enabled: true,
|
|
614
|
+
handler: { code: exports.HANDLER_CODE, arguments: [] },
|
|
615
|
+
checker: { code: exports.CHECKER_CODE, arguments: [] },
|
|
616
|
+
translations: [{ languageCode: ctx.languageCode ?? generated_types_1.LanguageCode.en, name: title, description: "" }],
|
|
617
|
+
});
|
|
618
|
+
return { result: "payment_method_created", retry: false };
|
|
619
|
+
}
|
|
620
|
+
// Internals
|
|
621
|
+
async creation(connection, effective) {
|
|
622
|
+
const release = effective === undefined ? await this.release() : effective;
|
|
623
|
+
if (release === null)
|
|
624
|
+
throw new connection_1.ConnectionError("connection_unavailable");
|
|
625
|
+
return new creation_service_1.TlyPayCreationService(new public_api_1.PublicApiClient(release, connection.apiKey), this.associations, release, await this.clientRefs.get(), async () => {
|
|
626
|
+
const current = await this.connections.get();
|
|
627
|
+
if (current === null)
|
|
628
|
+
throw new connection_1.ConnectionError("api_key_required");
|
|
629
|
+
return current;
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
async channelMethods(ctx) {
|
|
633
|
+
const methods = await this.connection.getRepository(ctx, core_1.PaymentMethod).createQueryBuilder("method")
|
|
634
|
+
.leftJoinAndSelect("method.translations", "translation")
|
|
635
|
+
.leftJoin("method.channels", "channel").where("channel.id = :channelId", { channelId: ctx.channelId }).getMany();
|
|
636
|
+
return methods.filter((method) => method.handler?.code === exports.HANDLER_CODE);
|
|
637
|
+
}
|
|
638
|
+
/** Administrators of the default Channel see every Channel; others only their own. */
|
|
639
|
+
async channelScope(ctx) {
|
|
640
|
+
return ctx.channel.code === shared_constants_1.DEFAULT_CHANNEL_CODE ? null : ctx.channel.token;
|
|
641
|
+
}
|
|
642
|
+
async ordersByCode(ctx, codes) {
|
|
643
|
+
if (codes.length === 0)
|
|
644
|
+
return new Map();
|
|
645
|
+
const rows = await this.connection.getRepository(ctx, core_1.Order).createQueryBuilder("order")
|
|
646
|
+
.select(["order.id", "order.code", "order.state"]).where("order.code IN (:...codes)", { codes }).getMany();
|
|
647
|
+
return new Map(rows.map((order) => [order.code, { id: order.id, state: order.state }]));
|
|
648
|
+
}
|
|
649
|
+
row(row, order) {
|
|
650
|
+
let source = {};
|
|
651
|
+
try {
|
|
652
|
+
const body = JSON.parse(row.requestBody);
|
|
653
|
+
if ((0, contracts_1.isRecord)(body) && (0, contracts_1.isRecord)(body.source_amount))
|
|
654
|
+
source = body.source_amount;
|
|
655
|
+
}
|
|
656
|
+
catch {
|
|
657
|
+
source = {};
|
|
658
|
+
}
|
|
659
|
+
return {
|
|
660
|
+
id: row.id, orderCode: row.orderCode, orderId: order === undefined ? null : String(order.id),
|
|
661
|
+
orderState: order?.state ?? null, state: row.state, status: row.status, statusVersion: row.statusVersion,
|
|
662
|
+
amountRaw: typeof source.amount_raw === "string" ? source.amount_raw : "",
|
|
663
|
+
currency: typeof source.currency === "string" ? source.currency : "",
|
|
664
|
+
checkoutMode: (0, creation_service_1.embeddedBody)(row.requestBody) ? "embedded" : "hosted", paymentId: row.paymentId,
|
|
665
|
+
err: row.err, settleErr: row.settleErr, settledAt: row.settledAt, createdAt: row.createdAt, updatedAt: row.updatedAt,
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Adds the Settled Vendure Payment for a verified paid Payment, once. An Order back in `AddingItems`
|
|
670
|
+
* is moved to `ArrangingPayment` first. Vendure recalculates the Order on that transition and writes
|
|
671
|
+
* the new totals before it may refuse it (for example when the selected shipping method is no longer
|
|
672
|
+
* eligible). A refused transition (`order_transition_refused`) or a recalculated total that no
|
|
673
|
+
* longer equals the Payment (`amount_mismatch`) rolls the transaction back: no Vendure Payment is
|
|
674
|
+
* added and the Order keeps its state and totals.
|
|
675
|
+
*/
|
|
676
|
+
async settleOrder(intent) {
|
|
677
|
+
const paymentId = intent.paymentId;
|
|
678
|
+
if (paymentId === null)
|
|
679
|
+
return "payment_association_missing";
|
|
680
|
+
const ctx = await this.requestContexts.create({ apiType: "admin", channelOrToken: intent.channelToken });
|
|
681
|
+
try {
|
|
682
|
+
return await this.connection.withTransaction(ctx, async (tx) => {
|
|
683
|
+
const order = await this.orders.findOneByCode(tx, intent.orderCode, ["payments"]);
|
|
684
|
+
if (order === undefined)
|
|
685
|
+
return "order_missing";
|
|
686
|
+
if (order.payments?.some((payment) => payment.transactionId === paymentId && payment.state === "Settled")) {
|
|
687
|
+
return "already_settled";
|
|
688
|
+
}
|
|
689
|
+
if (!matchesPayment(order, intent.requestBody))
|
|
690
|
+
return "amount_mismatch";
|
|
691
|
+
if (order.state === "AddingItems") {
|
|
692
|
+
const moved = await this.orders.transitionToState(tx, order.id, "ArrangingPayment");
|
|
693
|
+
if ((0, core_1.isGraphQlErrorResult)(moved)) {
|
|
694
|
+
core_1.Logger.warn(`Order ${order.code} was not moved to ArrangingPayment for Payment ${paymentId}: `
|
|
695
|
+
+ moved.transitionError, LOG_CONTEXT);
|
|
696
|
+
throw new SettlementAborted("order_transition_refused");
|
|
697
|
+
}
|
|
698
|
+
if (!matchesPayment(moved, intent.requestBody))
|
|
699
|
+
throw new SettlementAborted("amount_mismatch");
|
|
700
|
+
}
|
|
701
|
+
else if (order.state !== "ArrangingPayment") {
|
|
702
|
+
return `order_state_${order.state.toLowerCase()}`.slice(0, 64);
|
|
703
|
+
}
|
|
704
|
+
const result = await this.orders.addPaymentToOrder(tx, order.id, { method: intent.paymentMethodCode, metadata: { paymentId } });
|
|
705
|
+
return (0, core_1.isGraphQlErrorResult)(result) ? "payment_declined" : "settled";
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
catch (error) {
|
|
709
|
+
if (error instanceof SettlementAborted)
|
|
710
|
+
return error.code;
|
|
711
|
+
throw error;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
async noteOrder(intent, status) {
|
|
715
|
+
const notes = {
|
|
716
|
+
partially_paid: "TLY Pay received a partial payment. Keep the order out of fulfillment and review it in TLY Pay.",
|
|
717
|
+
overpaid: "TLY Pay reports an overpayment. Review the Payment in TLY Pay.",
|
|
718
|
+
review_required: "TLY Pay requires review before fulfillment.",
|
|
719
|
+
expired: "TLY Pay reports that the unpaid Payment is no longer payable.",
|
|
720
|
+
cancelled: "TLY Pay reports that the unpaid Payment was cancelled.",
|
|
721
|
+
};
|
|
722
|
+
const note = notes[status];
|
|
723
|
+
if (note === undefined)
|
|
724
|
+
return;
|
|
725
|
+
const ctx = await this.requestContexts.create({ apiType: "admin", channelOrToken: intent.channelToken });
|
|
726
|
+
const order = await this.orders.findOneByCode(ctx, intent.orderCode);
|
|
727
|
+
if (order === undefined)
|
|
728
|
+
return;
|
|
729
|
+
await this.history.createHistoryEntryForOrder({ ctx, orderId: order.id, type: generated_types_1.HistoryEntryType.ORDER_NOTE,
|
|
730
|
+
data: { note: `${note} (${intent.paymentId})` } }, false);
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
exports.TlyPayService = TlyPayService;
|
|
734
|
+
exports.TlyPayService = TlyPayService = __decorate([
|
|
735
|
+
(0, common_1.Injectable)(),
|
|
736
|
+
__param(0, (0, common_1.Inject)(exports.TLY_PAY_PLUGIN_OPTIONS)),
|
|
737
|
+
__metadata("design:paramtypes", [Object, core_1.TransactionalConnection,
|
|
738
|
+
client_ref_1.TlyPayClientRefService,
|
|
739
|
+
core_1.JobQueueService,
|
|
740
|
+
core_1.RequestContextService,
|
|
741
|
+
core_1.OrderService,
|
|
742
|
+
core_1.ActiveOrderService,
|
|
743
|
+
core_1.PaymentMethodService,
|
|
744
|
+
core_1.HistoryService,
|
|
745
|
+
core_1.ConfigService,
|
|
746
|
+
core_1.TranslatorService,
|
|
747
|
+
core_1.EventBus])
|
|
748
|
+
], TlyPayService);
|
|
749
|
+
/**
|
|
750
|
+
* The sentence that names the coins under the title. It always agrees with the icons: the labels of the
|
|
751
|
+
* icons shown, or of the coins the Store accepts while no icon is chosen, and the generic sentence while
|
|
752
|
+
* the Store accepts none either.
|
|
753
|
+
*/
|
|
754
|
+
function coinNamesText(ctx, icons, assets) {
|
|
755
|
+
const labels = icons.length > 0 ? icons.map((icon) => icon.label)
|
|
756
|
+
: acceptedMarks(assets).map((mark) => mark.toUpperCase());
|
|
757
|
+
if (labels.length === 0)
|
|
758
|
+
return checkoutMessage(ctx, "coinNamesGeneric");
|
|
759
|
+
return checkoutMessage(ctx, "coinNames", coinList(labels, checkoutMessage(ctx, "listLocale")));
|
|
760
|
+
}
|
|
761
|
+
function sourceField(requestBody, field) {
|
|
762
|
+
try {
|
|
763
|
+
const body = JSON.parse(requestBody);
|
|
764
|
+
const source = (0, contracts_1.isRecord)(body) ? body.source_amount : null;
|
|
765
|
+
return (0, contracts_1.isRecord)(source) && typeof source[field] === "string" ? source[field] : null;
|
|
766
|
+
}
|
|
767
|
+
catch {
|
|
768
|
+
return null;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
function sourceRaw(requestBody) {
|
|
772
|
+
return sourceField(requestBody, "amount_raw");
|
|
773
|
+
}
|
|
774
|
+
function sourceCurrency(requestBody) {
|
|
775
|
+
return sourceField(requestBody, "currency");
|
|
776
|
+
}
|
|
777
|
+
/** Whether the Order's total and currency are exactly the source amount of the Payment's request. */
|
|
778
|
+
function matchesPayment(order, requestBody) {
|
|
779
|
+
return String(order.totalWithTax) === sourceRaw(requestBody) && order.currencyCode === sourceCurrency(requestBody);
|
|
780
|
+
}
|
|
781
|
+
/** Ends a settlement with a code and rolls back what its transaction wrote. */
|
|
782
|
+
class SettlementAborted extends Error {
|
|
783
|
+
code;
|
|
784
|
+
constructor(code) {
|
|
785
|
+
super(code);
|
|
786
|
+
this.code = code;
|
|
787
|
+
}
|
|
788
|
+
}
|