@orboni/vendure-plugin 0.0.0-stage → 1.0.1
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 +14 -0
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/constants.d.ts +10 -0
- package/dist/constants.js +9 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +17 -0
- package/dist/money.d.ts +15 -0
- package/dist/money.js +38 -0
- package/dist/orboni.controller.d.ts +10 -0
- package/dist/orboni.controller.js +43 -0
- package/dist/orboni.handler.d.ts +61 -0
- package/dist/orboni.handler.js +56 -0
- package/dist/orboni.plugin.d.ts +18 -0
- package/dist/orboni.plugin.js +147 -0
- package/dist/orboni.resolver.d.ts +7 -0
- package/dist/orboni.resolver.js +42 -0
- package/dist/orboni.service.d.ts +120 -0
- package/dist/orboni.service.js +658 -0
- package/dist/status.d.ts +22 -0
- package/dist/status.js +31 -0
- package/package.json +56 -5
|
@@ -0,0 +1,658 @@
|
|
|
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.OrboniService = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const core_1 = require("@vendure/core");
|
|
18
|
+
const generated_types_1 = require("@vendure/common/lib/generated-types");
|
|
19
|
+
const orboni_1 = require("orboni");
|
|
20
|
+
const constants_1 = require("./constants");
|
|
21
|
+
const money_1 = require("./money");
|
|
22
|
+
const status_1 = require("./status");
|
|
23
|
+
/** A payment that counts: not declined, failed or cancelled. */
|
|
24
|
+
const LIVE_PAYMENT_STATES = ['Created', 'Authorized', 'Settled'];
|
|
25
|
+
/** An open page is sent again only with this long still to run (seconds). */
|
|
26
|
+
const REUSE_MIN_SECONDS = 300;
|
|
27
|
+
const REVERSED_EVENT = 'checkout.session.payment_reversed';
|
|
28
|
+
/** The check lists the sessions paid, on their way or held this long back (seconds)… */
|
|
29
|
+
const LISTED_SECONDS = 3 * 24 * 3600;
|
|
30
|
+
/** …reads an authorized payment again after this long (ms), until it is settled or 30 days old… */
|
|
31
|
+
const AUTHORIZED_RECHECK_MS = 50 * 60 * 1000;
|
|
32
|
+
const AUTHORIZED_DAYS = 30;
|
|
33
|
+
/** …and a settled one every six hours for two days, so money that left the chain is seen without its webhook. */
|
|
34
|
+
const SETTLED_RECHECK_MS = 6 * 3600 * 1000;
|
|
35
|
+
const SETTLED_DAYS = 2;
|
|
36
|
+
/** At most this many sessions read one by one in a check. */
|
|
37
|
+
const CHECK_READS = 100;
|
|
38
|
+
/** Databases whose rows can be locked; SQLite writes one transaction at a time anyway. */
|
|
39
|
+
const ROW_LOCKS = ['postgres', 'mysql', 'mariadb', 'cockroachdb', 'mssql', 'oracle'];
|
|
40
|
+
/** The first words of the note left when money that paid an order left the chain. */
|
|
41
|
+
const LEFT_THE_CHAIN = 'Orboni: money that paid this order left the chain';
|
|
42
|
+
let OrboniService = class OrboniService {
|
|
43
|
+
options;
|
|
44
|
+
activeOrderService;
|
|
45
|
+
orderService;
|
|
46
|
+
paymentMethodService;
|
|
47
|
+
historyService;
|
|
48
|
+
requestContextService;
|
|
49
|
+
connection;
|
|
50
|
+
channelService;
|
|
51
|
+
/** Work on one order at a time in this process; the order's row is locked too, for the other processes. */
|
|
52
|
+
locks = new Map();
|
|
53
|
+
/** When the check last read each recorded payment, in this process. */
|
|
54
|
+
lastRead = new Map();
|
|
55
|
+
constructor(options, activeOrderService, orderService, paymentMethodService, historyService, requestContextService, connection, channelService) {
|
|
56
|
+
this.options = options;
|
|
57
|
+
this.activeOrderService = activeOrderService;
|
|
58
|
+
this.orderService = orderService;
|
|
59
|
+
this.paymentMethodService = paymentMethodService;
|
|
60
|
+
this.historyService = historyService;
|
|
61
|
+
this.requestContextService = requestContextService;
|
|
62
|
+
this.connection = connection;
|
|
63
|
+
this.channelService = channelService;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The Shop API's `createOrboniPaymentIntent`: moves the active order to
|
|
67
|
+
* ArrangingPayment and returns the payment page to send the buyer to.
|
|
68
|
+
* An open page of the same order, total and currency is sent again; any
|
|
69
|
+
* other open page of it is closed, so it can no longer be paid.
|
|
70
|
+
*/
|
|
71
|
+
async createPaymentIntent(ctx, input) {
|
|
72
|
+
let order = await this.activeOrderService.getActiveOrder(ctx, undefined);
|
|
73
|
+
if (!order) {
|
|
74
|
+
throw new core_1.UserInputError('There is no active order to pay.');
|
|
75
|
+
}
|
|
76
|
+
if (order.state !== 'ArrangingPayment') {
|
|
77
|
+
const moved = await this.orderService.transitionToState(ctx, order.id, 'ArrangingPayment');
|
|
78
|
+
if (moved instanceof core_1.OrderStateTransitionError) {
|
|
79
|
+
throw new core_1.UserInputError(moved.transitionError || moved.message);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
order = (await this.orderService.findOne(ctx, order.id, ['lines', 'lines.productVariant', 'customer'])) ?? order;
|
|
83
|
+
if (!order.customer?.emailAddress) {
|
|
84
|
+
throw new core_1.UserInputError('The order needs a customer before it is paid.');
|
|
85
|
+
}
|
|
86
|
+
const method = await this.methodFor(ctx, order, input.paymentMethodCode);
|
|
87
|
+
const args = this.argsOf(method);
|
|
88
|
+
const currency = order.currencyCode.toLowerCase();
|
|
89
|
+
if (!(0, money_1.supports)(currency)) {
|
|
90
|
+
throw new core_1.UserInputError(`Orboni does not price in ${order.currencyCode}.`);
|
|
91
|
+
}
|
|
92
|
+
const outstanding = order.totalWithTax - (await this.coveredAmount(ctx, order));
|
|
93
|
+
const amount = (0, money_1.toOrboni)(outstanding, currency);
|
|
94
|
+
const client = this.client(args);
|
|
95
|
+
const open = await this.call(async () => await client.checkout.sessions.list({ client_reference_id: order.code, status: 'open', limit: 10 }));
|
|
96
|
+
const now = Math.floor(Date.now() / 1000);
|
|
97
|
+
let reuse;
|
|
98
|
+
for (const session of open.data) {
|
|
99
|
+
if (session.metadata?.vendure_channel !== ctx.channel.token) {
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const same = session.amount_total === amount &&
|
|
103
|
+
session.currency === currency &&
|
|
104
|
+
session.metadata?.vendure_payment_method === method.code &&
|
|
105
|
+
session.expires_at - now > REUSE_MIN_SECONDS;
|
|
106
|
+
if (same && !reuse) {
|
|
107
|
+
reuse = session;
|
|
108
|
+
}
|
|
109
|
+
else if (session.payment_status === 'unpaid') {
|
|
110
|
+
// An older page for another total: closed, so it cannot be paid.
|
|
111
|
+
await this.call(() => client.checkout.sessions.expire(session.id)).catch((error) => core_1.Logger.warn(`Could not close ${session.id}: ${error.message}`, constants_1.loggerCtx));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (reuse) {
|
|
115
|
+
return { url: reuse.url, sessionId: reuse.id, expiresAt: new Date(reuse.expires_at * 1000) };
|
|
116
|
+
}
|
|
117
|
+
const params = {
|
|
118
|
+
amount,
|
|
119
|
+
currency: currency,
|
|
120
|
+
success_url: fill(text(input.successUrl) ?? text(args.successUrl), order.code),
|
|
121
|
+
cancel_url: fill(text(input.cancelUrl) ?? text(args.cancelUrl), order.code),
|
|
122
|
+
client_reference_id: order.code,
|
|
123
|
+
customer_email: order.customer.emailAddress,
|
|
124
|
+
description: describe(order),
|
|
125
|
+
details: `Order ${order.code}`,
|
|
126
|
+
locale: ctx.languageCode,
|
|
127
|
+
metadata: {
|
|
128
|
+
vendure_order_code: order.code,
|
|
129
|
+
vendure_order_id: String(order.id),
|
|
130
|
+
vendure_channel: ctx.channel.token,
|
|
131
|
+
vendure_payment_method: method.code,
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
// A second press within the same minute gets the same page back.
|
|
135
|
+
const key = `vendure-${ctx.channel.token}-${order.code}-${amount}${currency}-${Math.floor(now / 60)}`;
|
|
136
|
+
const session = await this.call(() => client.checkout.sessions.create(params, { idempotencyKey: key }));
|
|
137
|
+
return { url: session.url, sessionId: session.id, expiresAt: new Date(session.expires_at * 1000) };
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The handler's createPayment: records a payment only as Orboni has it,
|
|
141
|
+
* read back with the merchant's key. Called by the webhook, and by the
|
|
142
|
+
* storefront's `addPaymentToOrder` with `{ sessionId }` when the buyer is
|
|
143
|
+
* back. A session not paid yet records nothing.
|
|
144
|
+
*/
|
|
145
|
+
async createPayment(ctx, order, amount, args, metadata) {
|
|
146
|
+
const sessionId = typeof metadata?.sessionId === 'string' ? metadata.sessionId : '';
|
|
147
|
+
if (!/^cs_(live|test)_\w+$/.test(sessionId)) {
|
|
148
|
+
throw new core_1.UserInputError('Orboni needs the payment page\'s session: pass { sessionId } in the metadata.');
|
|
149
|
+
}
|
|
150
|
+
let session;
|
|
151
|
+
try {
|
|
152
|
+
session = await this.client(args).checkout.sessions.retrieve(sessionId);
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
return { amount, state: 'Error', errorMessage: `Orboni: ${error.message}` };
|
|
156
|
+
}
|
|
157
|
+
if (session.client_reference_id !== order.code || session.metadata?.vendure_channel !== ctx.channel.token) {
|
|
158
|
+
throw new core_1.UserInputError('This Orboni payment is not this order\'s.');
|
|
159
|
+
}
|
|
160
|
+
if (session.currency !== order.currencyCode.toLowerCase() || session.amount_total !== (0, money_1.toOrboni)(amount, order.currencyCode)) {
|
|
161
|
+
return {
|
|
162
|
+
amount,
|
|
163
|
+
state: 'Declined',
|
|
164
|
+
errorMessage: 'The order\'s total changed after its payment page was opened, so this payment does not pay it. The store will be in touch about it.',
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
// The webhook, the check and the buyer's return may come at once, in other processes.
|
|
168
|
+
await this.lockOrder(ctx, order.id);
|
|
169
|
+
if (await this.recorded(ctx, order, session.id)) {
|
|
170
|
+
throw new core_1.UserInputError('This payment is already recorded on the order.');
|
|
171
|
+
}
|
|
172
|
+
const state = (0, status_1.paymentState)(session);
|
|
173
|
+
if (!state) {
|
|
174
|
+
throw new core_1.UserInputError((0, status_1.notPaidReason)(session));
|
|
175
|
+
}
|
|
176
|
+
return { amount, state, transactionId: session.id, metadata: paymentMetadata(session) };
|
|
177
|
+
}
|
|
178
|
+
/** The handler's settlePayment: an authorized payment is settled once Orboni says it is paid. */
|
|
179
|
+
async settlePayment(payment, args) {
|
|
180
|
+
const session = await this.client(args).checkout.sessions.retrieve(payment.transactionId);
|
|
181
|
+
if ((0, status_1.paymentState)(session) === 'Settled') {
|
|
182
|
+
return { success: true, metadata: paymentMetadata(session) };
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
success: false,
|
|
186
|
+
state: 'Authorized',
|
|
187
|
+
errorMessage: `Orboni session ${session.id} is not paid yet (${session.status}, ${session.payment_status}).`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The handler's createRefund. Orboni holds no money, so nothing is sent:
|
|
192
|
+
* the refund you sent from your own wallet is recorded against the
|
|
193
|
+
* session, where the dashboard shows it. Send the money first.
|
|
194
|
+
*/
|
|
195
|
+
async createRefund(ctx, reason, amount, order, payment, args) {
|
|
196
|
+
try {
|
|
197
|
+
const refund = await this.client(args).refunds.create({
|
|
198
|
+
checkout_session: payment.transactionId,
|
|
199
|
+
amount: (0, money_1.toOrboni)(amount, order.currencyCode),
|
|
200
|
+
reason: 'requested_by_customer',
|
|
201
|
+
note: (reason ? `Recorded from Vendure: ${reason}` : 'Recorded from Vendure').slice(0, 500),
|
|
202
|
+
});
|
|
203
|
+
return { state: 'Settled', transactionId: refund.id, metadata: { orboniRefund: refund.id } };
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
core_1.Logger.warn(`Refund of ${payment.transactionId} was not recorded: ${error.message}`, constants_1.loggerCtx);
|
|
207
|
+
return { state: 'Failed', transactionId: payment.transactionId, metadata: { message: `Orboni: ${error.message}` } };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Orboni's webhook, at /payments/orboni/<channel token>. Events of
|
|
212
|
+
* sessions this channel did not make (another store on the same Orboni
|
|
213
|
+
* project) are answered 200 and left alone. Every change is made from the
|
|
214
|
+
* session as Orboni has it now, so an event sent twice, late or out of
|
|
215
|
+
* order changes nothing.
|
|
216
|
+
*/
|
|
217
|
+
async handleWebhook(channelToken, rawBody, signature) {
|
|
218
|
+
if (!rawBody?.length) {
|
|
219
|
+
return { status: 400, body: 'No body.' };
|
|
220
|
+
}
|
|
221
|
+
let unverified;
|
|
222
|
+
try {
|
|
223
|
+
unverified = JSON.parse(rawBody.toString('utf8'));
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return { status: 400, body: 'Not JSON.' };
|
|
227
|
+
}
|
|
228
|
+
const unverifiedSession = unverified?.data?.object;
|
|
229
|
+
if (unverifiedSession?.object !== 'checkout.session' || unverifiedSession.metadata?.vendure_channel !== channelToken) {
|
|
230
|
+
return { status: 200, body: 'Not this store\'s.' };
|
|
231
|
+
}
|
|
232
|
+
let ctx;
|
|
233
|
+
try {
|
|
234
|
+
ctx = await this.requestContextService.create({ apiType: 'admin', channelOrToken: channelToken });
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return { status: 404, body: 'No such channel.' };
|
|
238
|
+
}
|
|
239
|
+
// An unknown token falls back to the default channel: it is not that channel.
|
|
240
|
+
if (ctx.channel.token !== channelToken) {
|
|
241
|
+
return { status: 404, body: 'No such channel.' };
|
|
242
|
+
}
|
|
243
|
+
const methodCode = String(unverifiedSession.metadata?.vendure_payment_method ?? '');
|
|
244
|
+
const method = (await this.paymentMethodService.findAll(ctx)).items.find((m) => m.code === methodCode && m.handler.code === constants_1.HANDLER_CODE);
|
|
245
|
+
if (!method) {
|
|
246
|
+
return { status: 404, body: 'No Orboni payment method with that code in this channel.' };
|
|
247
|
+
}
|
|
248
|
+
const args = this.argsOf(method);
|
|
249
|
+
if (!text(args.webhookSecret)) {
|
|
250
|
+
core_1.Logger.warn(`A webhook came, but the payment method ${method.code} has no webhook signing secret: it was not read.`, constants_1.loggerCtx);
|
|
251
|
+
return { status: 503, body: 'No webhook signing secret is set.' };
|
|
252
|
+
}
|
|
253
|
+
const client = this.client(args);
|
|
254
|
+
let event;
|
|
255
|
+
try {
|
|
256
|
+
event = await client.webhooks.constructEvent(rawBody, signature, args.webhookSecret.trim());
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
core_1.Logger.warn(`A webhook was refused: ${error.message}`, constants_1.loggerCtx);
|
|
260
|
+
return { status: 401, body: 'Bad signature.' };
|
|
261
|
+
}
|
|
262
|
+
const sent = event.data?.object;
|
|
263
|
+
if (!sent?.id) {
|
|
264
|
+
return { status: 200, body: 'Nothing to do.' };
|
|
265
|
+
}
|
|
266
|
+
let session;
|
|
267
|
+
try {
|
|
268
|
+
session = await client.checkout.sessions.retrieve(sent.id);
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
const status = error instanceof orboni_1.OrboniError ? error.statusCode : undefined;
|
|
272
|
+
if (status === undefined || status >= 500 || status === 429) {
|
|
273
|
+
return { status: 503, body: 'Orboni could not be read; send it again.' };
|
|
274
|
+
}
|
|
275
|
+
return { status: 200, body: 'Not a session of this key.' };
|
|
276
|
+
}
|
|
277
|
+
const code = session.client_reference_id;
|
|
278
|
+
if (!code || session.metadata?.vendure_channel !== channelToken) {
|
|
279
|
+
return { status: 200, body: 'Not this store\'s.' };
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
const found = await this.record(ctx, code, method, event.type, session);
|
|
283
|
+
return { status: 200, body: found ? 'Ok' : 'No such order.' };
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
// Nothing of it was kept (one transaction): Orboni sends the event again.
|
|
287
|
+
core_1.Logger.error(`Session ${session.id} of order ${code} was not recorded, Orboni sends it again: ${error.message}`, constants_1.loggerCtx);
|
|
288
|
+
return { status: 503, body: 'Not recorded; send it again.' };
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Payments whose webhook was lost or failed, read back from Orboni: every
|
|
293
|
+
* Orboni payment method of every channel lists its sessions paid, on their
|
|
294
|
+
* way or held in the last three days, and records those Vendure does not
|
|
295
|
+
* have; an authorized payment is read again until it is settled, a
|
|
296
|
+
* settled one every six hours for two days (money that left the chain).
|
|
297
|
+
* Run by the plugin's scheduled task (Vendure 3.3+, with a scheduler such
|
|
298
|
+
* as DefaultSchedulerPlugin); call it from a job of your own otherwise.
|
|
299
|
+
* One session that cannot be recorded stops no other.
|
|
300
|
+
*/
|
|
301
|
+
async checkPayments() {
|
|
302
|
+
const now = Date.now();
|
|
303
|
+
const tally = { read: 0, recorded: 0, retry: 0 };
|
|
304
|
+
const base = await this.requestContextService.create({ apiType: 'admin' });
|
|
305
|
+
for (const channel of (await this.channelService.findAll(base)).items) {
|
|
306
|
+
const ctx = await this.requestContextService.create({ apiType: 'admin', channelOrToken: channel.token });
|
|
307
|
+
if (ctx.channel.token !== channel.token) {
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
const methods = (await this.paymentMethodService.findAll(ctx)).items.filter((m) => m.handler.code === constants_1.HANDLER_CODE && m.enabled);
|
|
311
|
+
for (const method of methods) {
|
|
312
|
+
let client;
|
|
313
|
+
try {
|
|
314
|
+
client = this.client(this.argsOf(method));
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
await this.checkListed(ctx, client, method, now, tally);
|
|
320
|
+
await this.checkRecorded(ctx, client, method, now, tally);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
for (const [key, at] of this.lastRead) {
|
|
324
|
+
if (now - at > SETTLED_DAYS * 24 * 3600 * 1000 + SETTLED_RECHECK_MS) {
|
|
325
|
+
this.lastRead.delete(key);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return `read ${tally.read}, recorded ${tally.recorded}, ${tally.retry} to try again`;
|
|
329
|
+
}
|
|
330
|
+
/** Sessions of this method paid, on their way or held lately that Vendure has not recorded as Orboni has them. */
|
|
331
|
+
async checkListed(ctx, client, method, now, tally) {
|
|
332
|
+
const since = Math.floor(now / 1000) - LISTED_SECONDS;
|
|
333
|
+
for (const paymentStatus of ['paid', 'processing', 'held']) {
|
|
334
|
+
let sessions;
|
|
335
|
+
try {
|
|
336
|
+
sessions = await client.checkout.sessions
|
|
337
|
+
.list({ payment_status: paymentStatus, created: { gte: since }, limit: 100 })
|
|
338
|
+
.autoPagingToArray({ limit: 300 });
|
|
339
|
+
tally.read++;
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
core_1.Logger.warn(`The check could not list ${paymentStatus} sessions of ${method.code}: ${error.message}`, constants_1.loggerCtx);
|
|
343
|
+
tally.retry++;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
for (const session of sessions) {
|
|
347
|
+
const code = session.client_reference_id;
|
|
348
|
+
if (!code || session.metadata?.vendure_channel !== ctx.channel.token || session.metadata?.vendure_payment_method !== method.code) {
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const payments = await this.connection
|
|
352
|
+
.getRepository(ctx, core_1.Payment)
|
|
353
|
+
.find({ where: { transactionId: session.id, method: method.code } });
|
|
354
|
+
const live = payments.find((p) => LIVE_PAYMENT_STATES.includes(p.state));
|
|
355
|
+
if (live) {
|
|
356
|
+
if (live.state === 'Settled' || (0, status_1.paymentState)(session) !== 'Settled') {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
else if (payments.some((p) => p.state === 'Declined') || (await this.refused(ctx, code, session.id))) {
|
|
361
|
+
// Vendure said no once, and the order says why: asking again every run changes nothing.
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
await this.checkOne(ctx, code, method, session, tally);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/** This method's payments in Vendure: authorized ones until settled, settled ones for two days. */
|
|
369
|
+
async checkRecorded(ctx, client, method, now, tally) {
|
|
370
|
+
const payments = await this.connection
|
|
371
|
+
.getRepository(ctx, core_1.Payment)
|
|
372
|
+
.createQueryBuilder('payment')
|
|
373
|
+
.innerJoinAndSelect('payment.order', 'order')
|
|
374
|
+
.innerJoin('order.channels', 'channel', 'channel.id = :channelId', { channelId: ctx.channelId })
|
|
375
|
+
.where('payment.method = :method', { method: method.code })
|
|
376
|
+
.andWhere('((payment.state = :authorized AND payment.createdAt > :authorizedSince) OR (payment.state = :settled AND payment.updatedAt > :settledSince))', {
|
|
377
|
+
authorized: 'Authorized',
|
|
378
|
+
authorizedSince: new Date(now - AUTHORIZED_DAYS * 24 * 3600 * 1000),
|
|
379
|
+
settled: 'Settled',
|
|
380
|
+
settledSince: new Date(now - SETTLED_DAYS * 24 * 3600 * 1000),
|
|
381
|
+
})
|
|
382
|
+
.orderBy('payment.id', 'ASC')
|
|
383
|
+
.getMany();
|
|
384
|
+
for (const payment of payments) {
|
|
385
|
+
if (!/^cs_(live|test)_\w+$/.test(payment.transactionId ?? '')) {
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
const key = `${ctx.channel.token}:${payment.id}`;
|
|
389
|
+
const every = payment.state === 'Authorized' ? AUTHORIZED_RECHECK_MS : SETTLED_RECHECK_MS;
|
|
390
|
+
if (now - (this.lastRead.get(key) ?? 0) < every) {
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
if (tally.read >= CHECK_READS) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
this.lastRead.set(key, now);
|
|
397
|
+
let session;
|
|
398
|
+
try {
|
|
399
|
+
session = await client.checkout.sessions.retrieve(payment.transactionId);
|
|
400
|
+
tally.read++;
|
|
401
|
+
}
|
|
402
|
+
catch (error) {
|
|
403
|
+
core_1.Logger.warn(`The check could not read ${payment.transactionId}: ${error.message}`, constants_1.loggerCtx);
|
|
404
|
+
this.lastRead.delete(key);
|
|
405
|
+
tally.retry++;
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
await this.checkOne(ctx, payment.order.code, method, session, tally);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/** Whether the order's newest note about this session says Vendure would not take its payment. */
|
|
412
|
+
async refused(ctx, code, sessionId) {
|
|
413
|
+
const order = await this.orderService.findOneByCode(ctx, code, []);
|
|
414
|
+
return !!order && !!(await this.lastNote(ctx, order, sessionId))?.startsWith(`Orboni: session ${sessionId} is paid, but`);
|
|
415
|
+
}
|
|
416
|
+
async checkOne(ctx, code, method, session, tally) {
|
|
417
|
+
try {
|
|
418
|
+
if (await this.record(ctx, code, method, '', session)) {
|
|
419
|
+
tally.recorded++;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
core_1.Logger.error(`The check could not record ${session.id} on order ${code}; the next check tries again: ${error.message}`, constants_1.loggerCtx);
|
|
424
|
+
tally.retry++;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Applies a session to its order in one transaction, the order's row
|
|
429
|
+
* locked: all of it is kept, or none. False when the channel has no such
|
|
430
|
+
* order; throws when it is to be tried again.
|
|
431
|
+
*/
|
|
432
|
+
async record(ctx, code, method, type, session) {
|
|
433
|
+
return this.locked(code, async () => {
|
|
434
|
+
const found = await this.orderService.findOneByCode(ctx, code, []);
|
|
435
|
+
if (!found) {
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
await this.connection.withTransaction(ctx, async (tx) => {
|
|
439
|
+
// First in the transaction: what is read after it is what the other processes committed.
|
|
440
|
+
await this.lockOrder(tx, found.id);
|
|
441
|
+
const order = (await this.orderService.findOne(tx, found.id, [])) ?? found;
|
|
442
|
+
await this.apply(tx, order, method, type, session);
|
|
443
|
+
});
|
|
444
|
+
return true;
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
async apply(ctx, order, method, type, session) {
|
|
448
|
+
const paidNow = session.status === 'complete' && session.payment_status === 'paid';
|
|
449
|
+
const existing = await this.recorded(ctx, order, session.id);
|
|
450
|
+
if (!paidNow && (type === REVERSED_EVENT || session.review_reason === 'reversed')) {
|
|
451
|
+
if (existing || type === REVERSED_EVENT) {
|
|
452
|
+
await this.noteOnce(ctx, order, session.id, `${LEFT_THE_CHAIN} (session ${session.id}). Do not ship it until the Orboni dashboard shows it paid again.`);
|
|
453
|
+
}
|
|
454
|
+
if (existing) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (existing && paidNow && (await this.lastNote(ctx, order, session.id))?.startsWith(LEFT_THE_CHAIN)) {
|
|
459
|
+
await this.note(ctx, order, `Orboni: session ${session.id} is paid in full again.`);
|
|
460
|
+
}
|
|
461
|
+
const state = (0, status_1.paymentState)(session);
|
|
462
|
+
if (!state) {
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
if (existing) {
|
|
466
|
+
if (existing.state === 'Authorized' && state === 'Settled') {
|
|
467
|
+
const settled = await this.orderService.settlePayment(ctx, existing.id);
|
|
468
|
+
if (!(settled instanceof core_1.Payment)) {
|
|
469
|
+
if (String(settled.errorCode) === 'SETTLE_PAYMENT_ERROR') {
|
|
470
|
+
// Orboni read it otherwise just then: the whole of it is tried again.
|
|
471
|
+
throw new Error(`payment ${existing.id} was not settled: ${settled.message}`);
|
|
472
|
+
}
|
|
473
|
+
const reason = ('transitionError' in settled && settled.transitionError) || settled.message;
|
|
474
|
+
core_1.Logger.error(`Payment ${existing.id} of order ${order.code} was not settled: ${reason}`, constants_1.loggerCtx);
|
|
475
|
+
await this.noteOnce(ctx, order, session.id, `Orboni: session ${session.id} is paid, but its payment could not be settled: ${reason}`);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
if (order.state === 'AddingItems' || order.state === 'ArrangingShipping') {
|
|
481
|
+
const moved = await this.orderService.transitionToState(ctx, order.id, 'ArrangingPayment');
|
|
482
|
+
if (moved instanceof core_1.OrderStateTransitionError) {
|
|
483
|
+
await this.noteOnce(ctx, order, session.id, `Orboni: session ${session.id} is paid, but the order could not take the payment: ${moved.transitionError || moved.message}`);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const added = await this.orderService.addPaymentToOrder(ctx, order.id, { method: method.code, metadata: { sessionId: session.id } });
|
|
488
|
+
if (!(added instanceof core_1.Order)) {
|
|
489
|
+
const reason = 'paymentErrorMessage' in added && added.paymentErrorMessage ? added.paymentErrorMessage : added.message;
|
|
490
|
+
if (String(added.errorCode) === 'PAYMENT_FAILED_ERROR') {
|
|
491
|
+
// Orboni could not be read just then: the whole of it is tried again.
|
|
492
|
+
throw new Error(`not recorded on order ${order.code}: ${reason}`);
|
|
493
|
+
}
|
|
494
|
+
core_1.Logger.error(`Session ${session.id} was not recorded on order ${order.code}: ${reason}`, constants_1.loggerCtx);
|
|
495
|
+
await this.noteOnce(ctx, order, session.id, `Orboni: session ${session.id} is paid, but it was not recorded on the order: ${reason}`);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* The payment of this session already on the order, if any, as the other
|
|
500
|
+
* processes committed it. Called with the order's row locked: where rows
|
|
501
|
+
* can be locked it is read outside this transaction, since MySQL's
|
|
502
|
+
* repeatable read would show the snapshot Vendure's first read of the
|
|
503
|
+
* request took, before the lock. A locking read would see it too, but
|
|
504
|
+
* locks the gaps of the payments' index, where two new orders' payments
|
|
505
|
+
* wait on each other.
|
|
506
|
+
*/
|
|
507
|
+
async recorded(ctx, order, sessionId) {
|
|
508
|
+
const repository = this.rowLocks() ? this.connection.rawConnection.getRepository(core_1.Payment) : this.connection.getRepository(ctx, core_1.Payment);
|
|
509
|
+
const payments = await repository.find({ where: { order: { id: order.id }, transactionId: sessionId } });
|
|
510
|
+
return payments.find((p) => LIVE_PAYMENT_STATES.includes(p.state));
|
|
511
|
+
}
|
|
512
|
+
/** Locks the order's row until the transaction ends, where the database can (a call outside a transaction locks nothing). */
|
|
513
|
+
async lockOrder(ctx, orderId) {
|
|
514
|
+
if (!this.rowLocks()) {
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
const query = this.connection
|
|
518
|
+
.getRepository(ctx, core_1.Order)
|
|
519
|
+
.createQueryBuilder('order')
|
|
520
|
+
.select('order.id')
|
|
521
|
+
.where('order.id = :orderId', { orderId })
|
|
522
|
+
.setLock('pessimistic_write');
|
|
523
|
+
await lockedOrPlain(() => query.getRawOne(), async () => undefined);
|
|
524
|
+
}
|
|
525
|
+
rowLocks() {
|
|
526
|
+
return ROW_LOCKS.includes(String(this.connection.rawConnection.options.type));
|
|
527
|
+
}
|
|
528
|
+
/** What payments already cover of the order. */
|
|
529
|
+
async coveredAmount(ctx, order) {
|
|
530
|
+
const payments = await this.connection.getRepository(ctx, core_1.Payment).find({ where: { order: { id: order.id } } });
|
|
531
|
+
return payments.filter((p) => p.state === 'Authorized' || p.state === 'Settled').reduce((sum, p) => sum + p.amount, 0);
|
|
532
|
+
}
|
|
533
|
+
async methodFor(ctx, order, code) {
|
|
534
|
+
const quotes = await this.paymentMethodService.getEligiblePaymentMethods(ctx, order);
|
|
535
|
+
const quote = quotes.find((q) => q.code === code);
|
|
536
|
+
if (!quote || !quote.isEligible) {
|
|
537
|
+
throw new core_1.UserInputError(quote?.eligibilityMessage || `The payment method ${code} cannot pay this order.`);
|
|
538
|
+
}
|
|
539
|
+
const method = (await this.paymentMethodService.findAll(ctx)).items.find((m) => m.code === code);
|
|
540
|
+
if (!method || method.handler.code !== constants_1.HANDLER_CODE) {
|
|
541
|
+
throw new core_1.UserInputError(`The payment method ${code} is not an Orboni one.`);
|
|
542
|
+
}
|
|
543
|
+
return method;
|
|
544
|
+
}
|
|
545
|
+
argsOf(method) {
|
|
546
|
+
const args = {};
|
|
547
|
+
for (const arg of method.handler.args) {
|
|
548
|
+
args[arg.name] = arg.value;
|
|
549
|
+
}
|
|
550
|
+
return args;
|
|
551
|
+
}
|
|
552
|
+
client(args) {
|
|
553
|
+
const key = String(args.apiKey ?? '').trim();
|
|
554
|
+
if (!/^sk_(live|test)_/.test(key)) {
|
|
555
|
+
throw new core_1.UserInputError('The Orboni payment method has no secret key: set sk_live_… or sk_test_… in its settings.');
|
|
556
|
+
}
|
|
557
|
+
return new orboni_1.Orboni(key, this.options.apiUrl ? { baseUrl: this.options.apiUrl } : {});
|
|
558
|
+
}
|
|
559
|
+
/** The newest of the order's notes that names this session. */
|
|
560
|
+
async lastNote(ctx, order, sessionId) {
|
|
561
|
+
const history = await this.historyService.getHistoryForOrder(ctx, order.id, false, { sort: { createdAt: generated_types_1.SortOrder.DESC }, take: 100 });
|
|
562
|
+
for (const entry of history.items) {
|
|
563
|
+
const note = entry.data?.note;
|
|
564
|
+
if (entry.type === generated_types_1.HistoryEntryType.ORDER_NOTE && typeof note === 'string' && note.includes(sessionId)) {
|
|
565
|
+
return note;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
/** A note, unless the order's newest note about this session says the same: the check and the webhook come again. */
|
|
571
|
+
async noteOnce(ctx, order, sessionId, note) {
|
|
572
|
+
if ((await this.lastNote(ctx, order, sessionId)) !== note) {
|
|
573
|
+
await this.note(ctx, order, note);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
async note(ctx, order, note) {
|
|
577
|
+
await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: generated_types_1.HistoryEntryType.ORDER_NOTE, data: { note } }, false);
|
|
578
|
+
}
|
|
579
|
+
/** An Orboni call, its refusal turned into an error with Orboni's own words. */
|
|
580
|
+
async call(fn) {
|
|
581
|
+
try {
|
|
582
|
+
return await fn();
|
|
583
|
+
}
|
|
584
|
+
catch (error) {
|
|
585
|
+
if (error instanceof orboni_1.OrboniError) {
|
|
586
|
+
core_1.Logger.warn(`Orboni refused: ${error.message}`, constants_1.loggerCtx);
|
|
587
|
+
throw new core_1.UserInputError(`Orboni: ${error.message}`);
|
|
588
|
+
}
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
async locked(key, fn) {
|
|
593
|
+
const before = this.locks.get(key) ?? Promise.resolve();
|
|
594
|
+
const run = before.catch(() => undefined).then(fn);
|
|
595
|
+
this.locks.set(key, run);
|
|
596
|
+
try {
|
|
597
|
+
return await run;
|
|
598
|
+
}
|
|
599
|
+
finally {
|
|
600
|
+
if (this.locks.get(key) === run) {
|
|
601
|
+
this.locks.delete(key);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
exports.OrboniService = OrboniService;
|
|
607
|
+
exports.OrboniService = OrboniService = __decorate([
|
|
608
|
+
(0, common_1.Injectable)(),
|
|
609
|
+
__param(0, (0, common_1.Inject)(constants_1.ORBONI_PLUGIN_OPTIONS)),
|
|
610
|
+
__metadata("design:paramtypes", [Object, core_1.ActiveOrderService,
|
|
611
|
+
core_1.OrderService,
|
|
612
|
+
core_1.PaymentMethodService,
|
|
613
|
+
core_1.HistoryService,
|
|
614
|
+
core_1.RequestContextService,
|
|
615
|
+
core_1.TransactionalConnection,
|
|
616
|
+
core_1.ChannelService])
|
|
617
|
+
], OrboniService);
|
|
618
|
+
/** A locking read; outside a transaction TypeORM refuses the lock, and the plain read is made instead. */
|
|
619
|
+
async function lockedOrPlain(locked, plain) {
|
|
620
|
+
try {
|
|
621
|
+
return await locked();
|
|
622
|
+
}
|
|
623
|
+
catch (error) {
|
|
624
|
+
if (error?.name === 'PessimisticLockTransactionRequiredError') {
|
|
625
|
+
return plain();
|
|
626
|
+
}
|
|
627
|
+
throw error;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
/** What the payment keeps: `public` is what the Shop API shows. */
|
|
631
|
+
function paymentMetadata(session) {
|
|
632
|
+
return {
|
|
633
|
+
sessionId: session.id,
|
|
634
|
+
livemode: session.livemode,
|
|
635
|
+
public: {
|
|
636
|
+
asset: session.payment?.asset ?? null,
|
|
637
|
+
coin: session.payment?.coin ?? null,
|
|
638
|
+
network: session.payment?.chain ?? null,
|
|
639
|
+
amount: session.payment?.amount ?? null,
|
|
640
|
+
},
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
/** The order's lines, as "Blue mug × 2, Tea × 1", cut to Orboni's 250 characters. */
|
|
644
|
+
function describe(order) {
|
|
645
|
+
const lines = (order.lines ?? [])
|
|
646
|
+
.map((line) => `${line.productVariant?.name ?? 'Item'} × ${line.quantity}`)
|
|
647
|
+
.join(', ');
|
|
648
|
+
if (lines === '') {
|
|
649
|
+
return null;
|
|
650
|
+
}
|
|
651
|
+
return lines.length > 250 ? `${lines.slice(0, 249)}…` : lines;
|
|
652
|
+
}
|
|
653
|
+
function fill(url, code) {
|
|
654
|
+
return url ? url.replace(/\{ORDER_CODE\}/g, encodeURIComponent(code)) : null;
|
|
655
|
+
}
|
|
656
|
+
function text(value) {
|
|
657
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : null;
|
|
658
|
+
}
|
package/dist/status.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How an Orboni checkout session reads in Vendure's terms. Kept apart from
|
|
3
|
+
* the service so it is tested without Vendure.
|
|
4
|
+
*
|
|
5
|
+
* A session is `open`, `complete` or `expired`; its money is `unpaid`,
|
|
6
|
+
* `processing` (seen on the chain, not final), `partially_paid` (final but
|
|
7
|
+
* short), `held` (for the merchant to review in Orboni) or `paid` (final:
|
|
8
|
+
* only with `complete`).
|
|
9
|
+
*/
|
|
10
|
+
export interface SessionState {
|
|
11
|
+
status: 'open' | 'complete' | 'expired';
|
|
12
|
+
payment_status: 'unpaid' | 'processing' | 'partially_paid' | 'paid' | 'held';
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* - paid: `Settled` — the order is paid;
|
|
16
|
+
* - on its way, or held for review: `Authorized` — the order is placed and
|
|
17
|
+
* waits for its payment, which is settled once Orboni says it is paid;
|
|
18
|
+
* - anything else: nothing to record yet (`null`).
|
|
19
|
+
*/
|
|
20
|
+
export declare function paymentState(session: SessionState): 'Settled' | 'Authorized' | null;
|
|
21
|
+
/** What the buyer is told when a session has nothing to record yet. */
|
|
22
|
+
export declare function notPaidReason(session: SessionState): string;
|