@orboni/vendure-plugin 1.0.0 → 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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.1 - 2026-11-30
4
+
5
+ - A payment Vendure could not save whole is saved on the next try: the payment, the order's state and its history are saved in one transaction, and the webhook is answered 503 until they are, so Orboni sends it again. Before, a payment Vendure refused, or one Orboni could not be read for just then, was answered 200 and lost.
6
+ - A scheduled task, `orboni-check-payments`, every 15 minutes in the worker (Vendure 3.3 and later, with a scheduler such as `DefaultSchedulerPlugin`): it records a payment whose webhook was lost or failed, settles one that became final without its webhook, and for two days checks that a paid order is still paid on the chain. On older Vendure, call `OrboniService.checkPayments()` from a job of your own.
7
+ - Money that left the chain leaves its note once, whether its webhook or the check sees it first, and a second note when the order is paid in full again.
8
+ - The order's row is locked while a payment is recorded, so the webhook on two servers and the buyer's return at once record it once (PostgreSQL, MySQL and MariaDB; SQLite writes one transaction at a time).
9
+ - A payment Vendure declines (the order's total changed after its page opened) or cannot take (the order was cancelled) leaves one note, however often it is read again.
10
+
3
11
  ## 1.0.0 - 2026-11-23
4
12
 
5
13
  - First release: Orboni as a Vendure 3 payment method. `createOrboniPaymentIntent` in the Shop API opens the order's payment page; the payment is recorded by Orboni's signed webhook at `/payments/orboni/<channel token>`, or by `addPaymentToOrder` with `{ sessionId }` when the buyer is back — always read back from Orboni first.
package/README.md CHANGED
@@ -23,6 +23,8 @@ export const config: VendureConfig = {
23
23
  };
24
24
  ```
25
25
 
26
+ The plugin adds a scheduled task, `orboni-check-payments`, that records what a lost or failed webhook left out (below). Vendure 3.3 and later run it in the worker every 15 minutes when a scheduler is set up, as new projects have it: `DefaultSchedulerPlugin.init()` among the plugins. On Vendure before 3.3, call `OrboniService.checkPayments()` every 15 minutes from a job of your own.
27
+
26
28
  ## Set it up
27
29
 
28
30
  1. In the Orboni dashboard, set the wallets you want to be paid to under Wallets, and copy a secret key under Developers → API keys — a test key (`sk_test_…`) first.
@@ -63,16 +65,18 @@ mutation {
63
65
  | Part paid | `partially_paid` | Nothing recorded; the payment page asks the buyer for the rest |
64
66
  | Back before paying | `open, unpaid` | Nothing recorded, the buyer told so |
65
67
  | Ran out unpaid | `expired` | Nothing recorded |
66
- | Money that paid it left the chain | `payment_reversed` | A private note on the order not to ship it until the dashboard shows it paid again |
68
+ | Money that paid it left the chain | `payment_reversed` | A private note on the order not to ship it until the dashboard shows it paid again, and another when it is paid in full again; the scheduled task sees it too when its webhook is lost |
67
69
 
68
70
  The plugin reads every payment back from Orboni with your key before Vendure records it, so a webhook sent twice, late or out of order changes nothing, and a storefront cannot record a payment that is not there. An order taken back to AddingItems and changed gets a new page for its new total, and the old one is closed.
69
71
 
72
+ A payment Vendure could not save whole is saved on the next try: the payment, the order's state and its history are saved together, and the webhook is answered 503 until they are, so Orboni sends it again. Every 15 minutes the scheduled task lists the sessions paid, on their way or held in the last three days and records those Vendure does not have, settles an Authorized payment that became final, and for two days reads a paid order again, so money that left the chain is seen without its webhook. One order it cannot save keeps no other waiting. A payment Vendure declines (the order's total changed after its page opened) or cannot take (the order was cancelled) gets one note on the order, however often it is read again.
73
+
70
74
  ## Good to know
71
75
 
72
76
  - The currency: the order's own — US dollars, euros, pounds, yen and 30-odd more. In a currency Orboni does not take, the intent fails with a reason.
73
77
  - The least an order may be is worth $1.00; below it the intent fails with Orboni's reason.
74
78
  - Refunds: the money is in your wallet, so send it back from there, then refund the payment in Vendure: it is recorded in Orboni, and nothing moves by itself.
75
- - Several channels, or several Vendure servers, can share one Orboni project: each channel adds its own endpoint and acts only on its own orders.
79
+ - Several channels, or several Vendure servers, can share one Orboni project: each channel adds its own endpoint and acts only on its own orders. While a payment is recorded the order's row is locked (PostgreSQL, MySQL, MariaDB), so the webhook on two servers and the buyer's return at once record it once.
76
80
  - What is sent: the order's outstanding amount and currency, its code, id and lines, the customer's email and the request's language. No address or phone number.
77
81
 
78
82
  ## Licence
@@ -8,7 +8,9 @@ import { OrboniPluginOptions } from './constants';
8
8
  * ```
9
9
  *
10
10
  * Then add a payment method with the Orboni handler in the dashboard, and an
11
- * Orboni webhook endpoint at /payments/orboni/<channel token>.
11
+ * Orboni webhook endpoint at /payments/orboni/<channel token>. On Vendure 3.3+
12
+ * with a scheduler (DefaultSchedulerPlugin) the plugin's task records what a
13
+ * lost or failed webhook left out, every 15 minutes in the worker.
12
14
  */
13
15
  export declare class OrboniPlugin {
14
16
  static options: OrboniPluginOptions;
@@ -1,13 +1,47 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
2
18
  var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
19
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
20
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
21
  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
22
  return c > 3 && r && Object.defineProperty(target, key, r), r;
7
23
  };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
8
41
  var OrboniPlugin_1;
9
42
  Object.defineProperty(exports, "__esModule", { value: true });
10
43
  exports.OrboniPlugin = void 0;
44
+ const core = __importStar(require("@vendure/core"));
11
45
  const core_1 = require("@vendure/core");
12
46
  const body_parser_1 = require("body-parser");
13
47
  const graphql_tag_1 = require("graphql-tag");
@@ -24,6 +58,30 @@ const rawBody = (0, body_parser_1.raw)({
24
58
  request.rawBody = Buffer.from(buffer);
25
59
  },
26
60
  });
61
+ /**
62
+ * Vendure's scheduled task (3.3+): payments whose webhook was lost or failed,
63
+ * and paid ones checked for two days, every 15 minutes in the worker. Older
64
+ * Vendure has no tasks: there `OrboniService.checkPayments()` is the merchant's
65
+ * to call.
66
+ */
67
+ function checkTask() {
68
+ const ScheduledTask = core.ScheduledTask;
69
+ if (typeof ScheduledTask !== 'function') {
70
+ return null;
71
+ }
72
+ return new ScheduledTask({
73
+ id: 'orboni-check-payments',
74
+ description: 'Orboni: records payments whose webhook was lost or failed, and checks paid ones for two days',
75
+ schedule: (cron) => cron.every(15).minutes(),
76
+ timeout: '10m',
77
+ preventOverlap: true,
78
+ async execute({ injector }) {
79
+ const result = await injector.get(orboni_service_1.OrboniService).checkPayments();
80
+ core_1.Logger.verbose(`Payments checked: ${result}`, constants_1.loggerCtx);
81
+ return result;
82
+ },
83
+ });
84
+ }
27
85
  const shopSchema = (0, graphql_tag_1.gql) `
28
86
  input OrboniPaymentIntentInput {
29
87
  "The code of an Orboni payment method eligible for the order."
@@ -55,7 +113,9 @@ const shopSchema = (0, graphql_tag_1.gql) `
55
113
  * ```
56
114
  *
57
115
  * Then add a payment method with the Orboni handler in the dashboard, and an
58
- * Orboni webhook endpoint at /payments/orboni/<channel token>.
116
+ * Orboni webhook endpoint at /payments/orboni/<channel token>. On Vendure 3.3+
117
+ * with a scheduler (DefaultSchedulerPlugin) the plugin's task records what a
118
+ * lost or failed webhook left out, every 15 minutes in the worker.
59
119
  */
60
120
  let OrboniPlugin = class OrboniPlugin {
61
121
  static { OrboniPlugin_1 = this; }
@@ -74,6 +134,11 @@ exports.OrboniPlugin = OrboniPlugin = OrboniPlugin_1 = __decorate([
74
134
  configuration: (config) => {
75
135
  config.paymentOptions.paymentMethodHandlers.push(orboni_handler_1.orboniPaymentHandler);
76
136
  config.apiOptions.middleware.push({ route: `/${constants_1.WEBHOOK_ROUTE}`, handler: rawBody, beforeListen: true });
137
+ const task = checkTask();
138
+ const scheduler = config.schedulerOptions;
139
+ if (task && scheduler) {
140
+ scheduler.tasks = [...(scheduler.tasks ?? []), task];
141
+ }
77
142
  return config;
78
143
  },
79
144
  shopApiExtensions: { schema: shopSchema, resolvers: [orboni_resolver_1.OrboniShopResolver] },
@@ -1,4 +1,4 @@
1
- import { ActiveOrderService, CreatePaymentErrorResult, CreatePaymentResult, CreateRefundResult, HistoryService, Order, OrderService, Payment, PaymentMethodService, PaymentMetadata, RequestContext, RequestContextService, SettlePaymentErrorResult, SettlePaymentResult, TransactionalConnection } from '@vendure/core';
1
+ import { ActiveOrderService, ChannelService, CreatePaymentErrorResult, CreatePaymentResult, CreateRefundResult, HistoryService, Order, OrderService, Payment, PaymentMethodService, PaymentMetadata, RequestContext, RequestContextService, SettlePaymentErrorResult, SettlePaymentResult, TransactionalConnection } from '@vendure/core';
2
2
  import { Orboni } from 'orboni';
3
3
  import { OrboniPluginOptions } from './constants';
4
4
  /** The payment method's settings, from the dashboard. */
@@ -30,9 +30,12 @@ export declare class OrboniService {
30
30
  private readonly historyService;
31
31
  private readonly requestContextService;
32
32
  private readonly connection;
33
- /** Work on one order at a time, so a webhook and the buyer's return never record one payment twice. */
33
+ private readonly channelService;
34
+ /** Work on one order at a time in this process; the order's row is locked too, for the other processes. */
34
35
  private readonly locks;
35
- constructor(options: OrboniPluginOptions, activeOrderService: ActiveOrderService, orderService: OrderService, paymentMethodService: PaymentMethodService, historyService: HistoryService, requestContextService: RequestContextService, connection: TransactionalConnection);
36
+ /** When the check last read each recorded payment, in this process. */
37
+ private readonly lastRead;
38
+ constructor(options: OrboniPluginOptions, activeOrderService: ActiveOrderService, orderService: OrderService, paymentMethodService: PaymentMethodService, historyService: HistoryService, requestContextService: RequestContextService, connection: TransactionalConnection, channelService: ChannelService);
36
39
  /**
37
40
  * The Shop API's `createOrboniPaymentIntent`: moves the active order to
38
41
  * ArrangingPayment and returns the payment page to send the buyer to.
@@ -63,14 +66,53 @@ export declare class OrboniService {
63
66
  * order changes nothing.
64
67
  */
65
68
  handleWebhook(channelToken: string, rawBody: Buffer | undefined, signature: string | undefined): Promise<WebhookAnswer>;
69
+ /**
70
+ * Payments whose webhook was lost or failed, read back from Orboni: every
71
+ * Orboni payment method of every channel lists its sessions paid, on their
72
+ * way or held in the last three days, and records those Vendure does not
73
+ * have; an authorized payment is read again until it is settled, a
74
+ * settled one every six hours for two days (money that left the chain).
75
+ * Run by the plugin's scheduled task (Vendure 3.3+, with a scheduler such
76
+ * as DefaultSchedulerPlugin); call it from a job of your own otherwise.
77
+ * One session that cannot be recorded stops no other.
78
+ */
79
+ checkPayments(): Promise<string>;
80
+ /** Sessions of this method paid, on their way or held lately that Vendure has not recorded as Orboni has them. */
81
+ private checkListed;
82
+ /** This method's payments in Vendure: authorized ones until settled, settled ones for two days. */
83
+ private checkRecorded;
84
+ /** Whether the order's newest note about this session says Vendure would not take its payment. */
85
+ private refused;
86
+ private checkOne;
87
+ /**
88
+ * Applies a session to its order in one transaction, the order's row
89
+ * locked: all of it is kept, or none. False when the channel has no such
90
+ * order; throws when it is to be tried again.
91
+ */
92
+ private record;
66
93
  private apply;
67
- /** The payment of this session already on the order, if any. */
94
+ /**
95
+ * The payment of this session already on the order, if any, as the other
96
+ * processes committed it. Called with the order's row locked: where rows
97
+ * can be locked it is read outside this transaction, since MySQL's
98
+ * repeatable read would show the snapshot Vendure's first read of the
99
+ * request took, before the lock. A locking read would see it too, but
100
+ * locks the gaps of the payments' index, where two new orders' payments
101
+ * wait on each other.
102
+ */
68
103
  private recorded;
104
+ /** Locks the order's row until the transaction ends, where the database can (a call outside a transaction locks nothing). */
105
+ private lockOrder;
106
+ private rowLocks;
69
107
  /** What payments already cover of the order. */
70
108
  private coveredAmount;
71
109
  private methodFor;
72
110
  private argsOf;
73
111
  client(args: OrboniArgs): Orboni;
112
+ /** The newest of the order's notes that names this session. */
113
+ private lastNote;
114
+ /** A note, unless the order's newest note about this session says the same: the check and the webhook come again. */
115
+ private noteOnce;
74
116
  private note;
75
117
  /** An Orboni call, its refusal turned into an error with Orboni's own words. */
76
118
  private call;
@@ -24,6 +24,21 @@ const status_1 = require("./status");
24
24
  const LIVE_PAYMENT_STATES = ['Created', 'Authorized', 'Settled'];
25
25
  /** An open page is sent again only with this long still to run (seconds). */
26
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';
27
42
  let OrboniService = class OrboniService {
28
43
  options;
29
44
  activeOrderService;
@@ -32,9 +47,12 @@ let OrboniService = class OrboniService {
32
47
  historyService;
33
48
  requestContextService;
34
49
  connection;
35
- /** Work on one order at a time, so a webhook and the buyer's return never record one payment twice. */
50
+ channelService;
51
+ /** Work on one order at a time in this process; the order's row is locked too, for the other processes. */
36
52
  locks = new Map();
37
- constructor(options, activeOrderService, orderService, paymentMethodService, historyService, requestContextService, connection) {
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) {
38
56
  this.options = options;
39
57
  this.activeOrderService = activeOrderService;
40
58
  this.orderService = orderService;
@@ -42,6 +60,7 @@ let OrboniService = class OrboniService {
42
60
  this.historyService = historyService;
43
61
  this.requestContextService = requestContextService;
44
62
  this.connection = connection;
63
+ this.channelService = channelService;
45
64
  }
46
65
  /**
47
66
  * The Shop API's `createOrboniPaymentIntent`: moves the active order to
@@ -145,6 +164,8 @@ let OrboniService = class OrboniService {
145
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.',
146
165
  };
147
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);
148
169
  if (await this.recorded(ctx, order, session.id)) {
149
170
  throw new core_1.UserInputError('This payment is already recorded on the order.');
150
171
  }
@@ -257,30 +278,201 @@ let OrboniService = class OrboniService {
257
278
  if (!code || session.metadata?.vendure_channel !== channelToken) {
258
279
  return { status: 200, body: 'Not this store\'s.' };
259
280
  }
260
- return this.locked(code, () => this.connection.withTransaction(ctx, async (tx) => {
261
- const order = await this.orderService.findOneByCode(tx, code);
262
- if (!order) {
263
- return { status: 200, body: 'No such order.' };
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++;
264
420
  }
265
- await this.apply(tx, order, method, event.type, session);
266
- return { status: 200, body: 'Ok' };
267
- }));
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
+ });
268
446
  }
269
447
  async apply(ctx, order, method, type, session) {
270
- if (type === 'checkout.session.payment_reversed') {
271
- await this.note(ctx, order, `Orboni: money that paid this order left the chain (session ${session.id}). Do not ship it until the Orboni dashboard shows it paid again.`);
272
- return;
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.`);
273
460
  }
274
461
  const state = (0, status_1.paymentState)(session);
275
462
  if (!state) {
276
463
  return;
277
464
  }
278
- const existing = await this.recorded(ctx, order, session.id);
279
465
  if (existing) {
280
466
  if (existing.state === 'Authorized' && state === 'Settled') {
281
467
  const settled = await this.orderService.settlePayment(ctx, existing.id);
282
468
  if (!(settled instanceof core_1.Payment)) {
283
- core_1.Logger.error(`Payment ${existing.id} of order ${order.code} was not settled: ${settled.message}`, constants_1.loggerCtx);
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}`);
284
476
  }
285
477
  }
286
478
  return;
@@ -288,24 +480,51 @@ let OrboniService = class OrboniService {
288
480
  if (order.state === 'AddingItems' || order.state === 'ArrangingShipping') {
289
481
  const moved = await this.orderService.transitionToState(ctx, order.id, 'ArrangingPayment');
290
482
  if (moved instanceof core_1.OrderStateTransitionError) {
291
- await this.note(ctx, order, `Orboni: session ${session.id} is paid, but the order could not take the payment: ${moved.transitionError || moved.message}`);
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}`);
292
484
  return;
293
485
  }
294
486
  }
295
487
  const added = await this.orderService.addPaymentToOrder(ctx, order.id, { method: method.code, metadata: { sessionId: session.id } });
296
488
  if (!(added instanceof core_1.Order)) {
297
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
+ }
298
494
  core_1.Logger.error(`Session ${session.id} was not recorded on order ${order.code}: ${reason}`, constants_1.loggerCtx);
299
- await this.note(ctx, order, `Orboni: session ${session.id} is paid, but it was not recorded on the order: ${reason}`);
495
+ await this.noteOnce(ctx, order, session.id, `Orboni: session ${session.id} is paid, but it was not recorded on the order: ${reason}`);
300
496
  }
301
497
  }
302
- /** The payment of this session already on the order, if any. */
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
+ */
303
507
  async recorded(ctx, order, sessionId) {
304
- const payments = await this.connection
305
- .getRepository(ctx, core_1.Payment)
306
- .find({ where: { order: { id: order.id }, transactionId: 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 } });
307
510
  return payments.find((p) => LIVE_PAYMENT_STATES.includes(p.state));
308
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
+ }
309
528
  /** What payments already cover of the order. */
310
529
  async coveredAmount(ctx, order) {
311
530
  const payments = await this.connection.getRepository(ctx, core_1.Payment).find({ where: { order: { id: order.id } } });
@@ -337,6 +556,23 @@ let OrboniService = class OrboniService {
337
556
  }
338
557
  return new orboni_1.Orboni(key, this.options.apiUrl ? { baseUrl: this.options.apiUrl } : {});
339
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
+ }
340
576
  async note(ctx, order, note) {
341
577
  await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: generated_types_1.HistoryEntryType.ORDER_NOTE, data: { note } }, false);
342
578
  }
@@ -376,8 +612,21 @@ exports.OrboniService = OrboniService = __decorate([
376
612
  core_1.PaymentMethodService,
377
613
  core_1.HistoryService,
378
614
  core_1.RequestContextService,
379
- core_1.TransactionalConnection])
615
+ core_1.TransactionalConnection,
616
+ core_1.ChannelService])
380
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
+ }
381
630
  /** What the payment keeps: `public` is what the Shop API shows. */
382
631
  function paymentMetadata(session) {
383
632
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orboni/vendure-plugin",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Crypto payments for Vendure: USDT, USDC, Bitcoin and more, paid straight to your own wallets through Orboni's payment page.",
5
5
  "keywords": [
6
6
  "vendure",