@serge-pro-dev/payload-payment-yookassa 0.0.0-stage → 0.1.0-beta.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/LICENSE +21 -0
- package/README.md +146 -2
- package/README.ru.md +148 -0
- package/dist/amount.d.ts +11 -0
- package/dist/amount.js +29 -0
- package/dist/amount.js.map +1 -0
- package/dist/api.d.ts +51 -0
- package/dist/api.js +58 -0
- package/dist/api.js.map +1 -0
- package/dist/client.d.ts +49 -0
- package/dist/client.js +61 -0
- package/dist/client.js.map +1 -0
- package/dist/confirm.d.ts +4 -0
- package/dist/confirm.js +95 -0
- package/dist/confirm.js.map +1 -0
- package/dist/fields.d.ts +13 -0
- package/dist/fields.js +68 -0
- package/dist/fields.js.map +1 -0
- package/dist/finalize.d.ts +45 -0
- package/dist/finalize.js +207 -0
- package/dist/finalize.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +164 -0
- package/dist/index.js.map +1 -0
- package/dist/initiate.d.ts +3 -0
- package/dist/initiate.js +221 -0
- package/dist/initiate.js.map +1 -0
- package/dist/messages.d.ts +3 -0
- package/dist/messages.js +77 -0
- package/dist/messages.js.map +1 -0
- package/dist/receipt.d.ts +57 -0
- package/dist/receipt.js +43 -0
- package/dist/receipt.js.map +1 -0
- package/dist/reconcile.d.ts +35 -0
- package/dist/reconcile.js +125 -0
- package/dist/reconcile.js.map +1 -0
- package/dist/settings.d.ts +29 -0
- package/dist/settings.js +207 -0
- package/dist/settings.js.map +1 -0
- package/dist/settlement.d.ts +25 -0
- package/dist/settlement.js +62 -0
- package/dist/settlement.js.map +1 -0
- package/dist/status.d.ts +13 -0
- package/dist/status.js +92 -0
- package/dist/status.js.map +1 -0
- package/dist/types.d.ts +84 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/utils.d.ts +8 -0
- package/dist/utils.js +25 -0
- package/dist/utils.js.map +1 -0
- package/dist/webhooks.d.ts +16 -0
- package/dist/webhooks.js +83 -0
- package/dist/webhooks.js.map +1 -0
- package/package.json +54 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 serge-pro-dev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,147 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @serge-pro-dev/payload-payment-yookassa
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Русская версия](./README.ru.md)
|
|
4
|
+
|
|
5
|
+
Accept payments with YooKassa in a Payload CMS 4 online shop (`@payloadcms/plugin-ecommerce`).
|
|
6
|
+
The buyer pays on the YooKassa page and returns to your site. The order is created as soon as the payment goes through, even if the buyer closes the page. Includes 54-FZ receipts, delivery and a check for stuck payments.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pnpm add @serge-pro-dev/payload-payment-yookassa
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Server
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { ecommercePlugin } from '@payloadcms/plugin-ecommerce'
|
|
18
|
+
import { yookassaAdapter } from '@serge-pro-dev/payload-payment-yookassa'
|
|
19
|
+
|
|
20
|
+
ecommercePlugin({
|
|
21
|
+
currencies: {
|
|
22
|
+
defaultCurrency: 'RUB',
|
|
23
|
+
supportedCurrencies: [{ code: 'RUB', decimals: 2, label: 'Russian ruble', symbol: '₽' }],
|
|
24
|
+
},
|
|
25
|
+
payments: {
|
|
26
|
+
paymentMethods: [
|
|
27
|
+
yookassaAdapter({
|
|
28
|
+
shopId: process.env.YOOKASSA_SHOP_ID!,
|
|
29
|
+
secretKey: process.env.YOOKASSA_SECRET_KEY!,
|
|
30
|
+
returnBaseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,
|
|
31
|
+
// receipts (54-FZ) are off by default; see "Receipt settings" below
|
|
32
|
+
receipt: false,
|
|
33
|
+
}),
|
|
34
|
+
],
|
|
35
|
+
},
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Keys live only in environment variables. Never commit them.
|
|
40
|
+
|
|
41
|
+
### Options
|
|
42
|
+
|
|
43
|
+
| Option | Default | Description |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| `shopId`, `secretKey` | required | Shop credentials |
|
|
46
|
+
| `returnBaseUrl` | required | Public site address (ngrok in development) |
|
|
47
|
+
| `returnPath` | `/checkout/confirm-order` | Where the buyer returns |
|
|
48
|
+
| `receipt` | `false` | `false`, `{ taxSystemCode?, defaultVatCode?, deliveryVatCode?, paymentSubject?, paymentMode? }` or `receiptFromSettings()` |
|
|
49
|
+
| `delivery` | none | `deliveryResolver()` of `@serge-pro-dev/payload-ecommerce-delivery`, see "Delivery" |
|
|
50
|
+
| `vatCodeField` | `vatCode` | Product field with the VAT code |
|
|
51
|
+
| `productsSlug`, `variantsSlug` | `products`, `variants` | Collections |
|
|
52
|
+
| `currency` | `RUB` | Payment currency |
|
|
53
|
+
| `decimals` | `2` | Minor units |
|
|
54
|
+
| `timeoutMs` | | Request timeout |
|
|
55
|
+
|
|
56
|
+
Add `vatCodeField()` to your products collection to set VAT per product (codes 1–12, 11 = 22%, 12 = 22/122).
|
|
57
|
+
|
|
58
|
+
## Receipt settings (54-FZ)
|
|
59
|
+
|
|
60
|
+
`receipt` takes `false`, fixed options, or `receiptFromSettings()`, which reads them from a global edited in the admin panel (a change applies to the next payment, no restart).
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { receiptFromSettings, yookassaAdapter, yookassaSettingsGlobal } from '@serge-pro-dev/payload-payment-yookassa'
|
|
64
|
+
|
|
65
|
+
buildConfig({
|
|
66
|
+
// access is required: customers are users too, pass your admin-only function
|
|
67
|
+
globals: [yookassaSettingsGlobal({ access: { read: isAdmin, update: isAdmin } })],
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
yookassaAdapter({ /* ... */ receipt: receiptFromSettings() })
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The global (`Ecommerce → YooKassa settings`) has: send receipts on/off, tax system, default VAT rate, subject and method of payment. A product (or variant) can override the VAT rate with `vatCodeField()`. Turn receipts on only when "Receipts from YooKassa" is connected in the shop, otherwise YooKassa rejects the payment.
|
|
74
|
+
|
|
75
|
+
## Delivery
|
|
76
|
+
|
|
77
|
+
Optional. Pass `delivery: deliveryResolver()` from [`@serge-pro-dev/payload-ecommerce-delivery`](../ecommerce-delivery/README.md). The delivery cost is added to the payment amount and becomes a line of the receipt (subject "service", VAT rate `deliveryVatCode` of the receipt settings). The order gets `delivery { methodID, title, amount }` and its `amount` includes the delivery. Without the option nothing changes.
|
|
78
|
+
|
|
79
|
+
## Client
|
|
80
|
+
|
|
81
|
+
```tsx
|
|
82
|
+
import { yookassaAdapterClient, getConfirmationUrl, confirmWithRetry } from '@serge-pro-dev/payload-payment-yookassa/client'
|
|
83
|
+
|
|
84
|
+
<EcommerceProvider paymentMethods={[yookassaAdapterClient()]} />
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
1. Call `initiatePayment('yookassa', ...)` and redirect to `getConfirmationUrl(result)`.
|
|
88
|
+
2. On the return page, call `confirmWithRetry(() => confirmOrder('yookassa', { additionalData: { transactionID, email } }))`.
|
|
89
|
+
|
|
90
|
+
## Webhook
|
|
91
|
+
|
|
92
|
+
In the YooKassa dashboard (Integration → HTTP notifications) set:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
<site>/api/payments/yookassa/webhooks
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Events: `payment.succeeded`, `payment.canceled`. Notifications are not signed, so the payment is always re-fetched from the API by id.
|
|
99
|
+
|
|
100
|
+
On `payment.succeeded` the webhook creates the order itself, so a buyer who closes the payment page still gets an order. The return page does the same when it gets there first; whichever comes second finds the finished order (the transaction is claimed atomically, so there is never a duplicate). If the webhook fails it answers 500 and YooKassa retries.
|
|
101
|
+
|
|
102
|
+
The webhook repeats the steps of the plugin's order finalizer (claim the transaction, create the order, mark the cart purchased, decrement inventory) because the plugin does not export it. Options `ordersSlug` and `cartsSlug` (defaults `orders`, `carts`) are needed only if you renamed those collections.
|
|
103
|
+
|
|
104
|
+
## Unpaid transactions (reconcile job)
|
|
105
|
+
|
|
106
|
+
A safety net for missed notifications. Every 5 minutes the job takes transactions that are still `pending` after 10 minutes, asks YooKassa for each payment, creates the order of a paid one and cancels the transaction of a canceled one (YooKassa cancels an unpaid payment by itself after its timeout). It is safe next to the webhook and the return page.
|
|
107
|
+
|
|
108
|
+
Use `createYooKassa` instead of `yookassaAdapter` so the adapter and the job share one configuration:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const yookassa = createYooKassa({ /* same options as yookassaAdapter */ })
|
|
112
|
+
|
|
113
|
+
ecommercePlugin({ payments: { paymentMethods: [yookassa.adapter] } })
|
|
114
|
+
|
|
115
|
+
buildConfig({
|
|
116
|
+
jobs: {
|
|
117
|
+
access: { run: ({ req }) => Boolean(req.user) || req.headers.get('authorization') === `Bearer ${process.env.CRON_SECRET}` },
|
|
118
|
+
// VPS: run the jobs inside the server process
|
|
119
|
+
autoRun: [{ cron: '* * * * *', limit: 20 }],
|
|
120
|
+
tasks: [yookassa.reconcileTask({ cron: '*/5 * * * *', minAgeMinutes: 10, limit: 50 })],
|
|
121
|
+
},
|
|
122
|
+
})
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
On serverless hosting leave out `autoRun` and call `GET /api/payload-jobs/handle-schedules` and then `GET /api/payload-jobs/run` from a cron with `Authorization: Bearer <CRON_SECRET>`. The task adds a task slug, so a database that uses migrations needs a new migration.
|
|
126
|
+
|
|
127
|
+
## Canceled payments
|
|
128
|
+
|
|
129
|
+
`GET /api/payments/yookassa/status?transaction=<id>&email=<guest email>` answers `{ status: 'succeeded' | 'canceled' | 'pending', cancellation?: { reason, party } }` and is available only to the buyer of the transaction. The reason is also saved in the transaction (`yookassa.cancellation`). On the client:
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { cancellationMessage, getPaymentStatus } from '@serge-pro-dev/payload-payment-yookassa/client'
|
|
133
|
+
|
|
134
|
+
const { status, cancellation } = await getPaymentStatus({ transaction, email })
|
|
135
|
+
if (status === 'canceled') show(cancellationMessage(cancellation?.reason, 'en')) // or 'ru'
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`confirmWithRetry(run, { shouldStop })` stops retrying as soon as `shouldStop()` returns true (for example when the payment is canceled). Show the message with a "Try again" link to the checkout.
|
|
139
|
+
|
|
140
|
+
## Security
|
|
141
|
+
|
|
142
|
+
- The amount is computed from database prices (plus the delivery priced on the server) and the goods must equal `cart.subtotal`.
|
|
143
|
+
- On confirmation, the transaction, cart, customer, amount, currency and payment status are all validated.
|
|
144
|
+
|
|
145
|
+
## Not yet supported
|
|
146
|
+
|
|
147
|
+
Refunds, two-stage payments.
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# @serge-pro-dev/payload-payment-yookassa
|
|
2
|
+
|
|
3
|
+
[English version](./README.md)
|
|
4
|
+
|
|
5
|
+
Приём платежей через ЮKassa для интернет-магазина на Payload CMS 4 (плагин `@payloadcms/plugin-ecommerce`).
|
|
6
|
+
Покупатель оплачивает заказ на странице ЮKassa и возвращается на сайт. Заказ создаётся сразу после оплаты, даже если покупатель закрыл страницу. Есть чеки по 54-ФЗ, доставка и проверка зависших платежей.
|
|
7
|
+
|
|
8
|
+
## Установка
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pnpm add @serge-pro-dev/payload-payment-yookassa
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Сервер
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { ecommercePlugin } from '@payloadcms/plugin-ecommerce'
|
|
18
|
+
import { yookassaAdapter } from '@serge-pro-dev/payload-payment-yookassa'
|
|
19
|
+
|
|
20
|
+
ecommercePlugin({
|
|
21
|
+
currencies: {
|
|
22
|
+
defaultCurrency: 'RUB',
|
|
23
|
+
supportedCurrencies: [{ code: 'RUB', decimals: 2, label: 'Российский рубль', symbol: '₽' }],
|
|
24
|
+
},
|
|
25
|
+
payments: {
|
|
26
|
+
paymentMethods: [
|
|
27
|
+
yookassaAdapter({
|
|
28
|
+
shopId: process.env.YOOKASSA_SHOP_ID!,
|
|
29
|
+
secretKey: process.env.YOOKASSA_SECRET_KEY!,
|
|
30
|
+
returnBaseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,
|
|
31
|
+
// чеки (54-ФЗ) по умолчанию выключены; см. «Настройки чеков» ниже
|
|
32
|
+
receipt: false,
|
|
33
|
+
}),
|
|
34
|
+
],
|
|
35
|
+
},
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Ключи храните только в переменных окружения и никогда не коммитьте.
|
|
40
|
+
|
|
41
|
+
### Параметры
|
|
42
|
+
|
|
43
|
+
| Параметр | По умолчанию | Описание |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| `shopId`, `secretKey` | обязательны | Данные магазина |
|
|
46
|
+
| `returnBaseUrl` | обязателен | Публичный адрес сайта (в разработке — адрес ngrok) |
|
|
47
|
+
| `returnPath` | `/checkout/confirm-order` | Куда возвращается покупатель |
|
|
48
|
+
| `receipt` | `false` | `false`, `{ taxSystemCode?, defaultVatCode?, deliveryVatCode?, paymentSubject?, paymentMode? }` или `receiptFromSettings()` |
|
|
49
|
+
| `delivery` | нет | `deliveryResolver()` из `@serge-pro-dev/payload-ecommerce-delivery`, см. «Доставка» |
|
|
50
|
+
| `vatCodeField` | `vatCode` | Поле товара со ставкой НДС |
|
|
51
|
+
| `productsSlug`, `variantsSlug` | `products`, `variants` | Коллекции |
|
|
52
|
+
| `ordersSlug`, `cartsSlug` | `orders`, `carts` | Нужны, только если вы переименовали коллекции |
|
|
53
|
+
| `currency` | `RUB` | Валюта платежа |
|
|
54
|
+
| `decimals` | `2` | Минимальные единицы |
|
|
55
|
+
| `timeoutMs` | | Таймаут запросов |
|
|
56
|
+
|
|
57
|
+
Добавьте `vatCodeField()` в коллекцию товаров, чтобы задавать НДС у каждого товара (коды 1–12, 11 = 22%, 12 = 22/122).
|
|
58
|
+
|
|
59
|
+
## Настройки чеков (54-ФЗ)
|
|
60
|
+
|
|
61
|
+
`receipt` принимает `false`, фиксированные параметры или `receiptFromSettings()`: тогда параметры читаются из глобала, который редактируется в админке (изменение действует со следующего платежа, перезапуск не нужен).
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { receiptFromSettings, yookassaAdapter, yookassaSettingsGlobal } from '@serge-pro-dev/payload-payment-yookassa'
|
|
65
|
+
|
|
66
|
+
buildConfig({
|
|
67
|
+
// access обязателен: покупатели тоже пользователи, передайте функцию «только админ»
|
|
68
|
+
globals: [yookassaSettingsGlobal({ access: { read: isAdmin, update: isAdmin } })],
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
yookassaAdapter({ /* ... */ receipt: receiptFromSettings() })
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
В глобале (`Ecommerce → Настройки ЮKassa`): отправлять ли чеки, система налогообложения, ставка НДС по умолчанию, ставка НДС доставки, признак предмета расчёта и признак способа расчёта. Для товара (или вариации) ставку НДС можно переопределить через `vatCodeField()`. Включайте чеки, только если в магазине ЮKassa подключены «Чеки от ЮKassa», иначе ЮKassa отклонит платёж.
|
|
75
|
+
|
|
76
|
+
## Доставка
|
|
77
|
+
|
|
78
|
+
Опционально. Передайте `delivery: deliveryResolver()` из [`@serge-pro-dev/payload-ecommerce-delivery`](../ecommerce-delivery/README.ru.md). Стоимость доставки прибавляется к сумме платежа и становится строкой чека (предмет расчёта «услуга», ставка НДС `deliveryVatCode` из настроек чеков). В заказ записывается `delivery { methodID, title, amount }`, а его `amount` включает доставку. Без этого параметра ничего не меняется.
|
|
79
|
+
|
|
80
|
+
## Клиент
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
import { yookassaAdapterClient, getConfirmationUrl, confirmWithRetry } from '@serge-pro-dev/payload-payment-yookassa/client'
|
|
84
|
+
|
|
85
|
+
<EcommerceProvider paymentMethods={[yookassaAdapterClient()]} />
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
1. Вызовите `initiatePayment('yookassa', ...)` и перенаправьте покупателя на `getConfirmationUrl(result)`.
|
|
89
|
+
2. На странице возврата вызовите `confirmWithRetry(() => confirmOrder('yookassa', { additionalData: { transactionID, email } }))`.
|
|
90
|
+
|
|
91
|
+
## Вебхук
|
|
92
|
+
|
|
93
|
+
В личном кабинете ЮKassa (Интеграция → HTTP-уведомления) укажите:
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
<сайт>/api/payments/yookassa/webhooks
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
События: `payment.succeeded`, `payment.canceled`. Уведомления не подписываются, поэтому платёж всегда заново запрашивается через API по id.
|
|
100
|
+
|
|
101
|
+
На `payment.succeeded` вебхук сам создаёт заказ, так что покупатель, закрывший страницу оплаты, всё равно получит заказ. Страница возврата делает то же самое, если успела раньше; кто пришёл вторым, находит готовый заказ (транзакция захватывается атомарно, дубля не будет). Если вебхук упал, он отвечает 500, и ЮKassa повторит уведомление.
|
|
102
|
+
|
|
103
|
+
Вебхук повторяет шаги «закрытия» заказа из плагина (захват транзакции, создание заказа, корзина «куплена», списание остатков), потому что плагин не отдаёт эту функцию наружу.
|
|
104
|
+
|
|
105
|
+
## Зависшие платежи (задача сверки)
|
|
106
|
+
|
|
107
|
+
Страховка на случай пропущенного уведомления. Каждые 5 минут задача берёт транзакции, которые остались `pending` дольше 10 минут, запрашивает платёж в ЮKassa, создаёт заказ для оплаченного и отменяет транзакцию отменённого (неоплаченный платёж ЮKassa отменяет сама по своему таймауту). Работает безопасно вместе с вебхуком и страницей возврата.
|
|
108
|
+
|
|
109
|
+
Используйте `createYooKassa` вместо `yookassaAdapter`, чтобы адаптер и задача делили одну конфигурацию:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
const yookassa = createYooKassa({ /* те же параметры, что у yookassaAdapter */ })
|
|
113
|
+
|
|
114
|
+
ecommercePlugin({ payments: { paymentMethods: [yookassa.adapter] } })
|
|
115
|
+
|
|
116
|
+
buildConfig({
|
|
117
|
+
jobs: {
|
|
118
|
+
access: { run: ({ req }) => Boolean(req.user) || req.headers.get('authorization') === `Bearer ${process.env.CRON_SECRET}` },
|
|
119
|
+
// VPS: задачи выполняются внутри процесса сервера
|
|
120
|
+
autoRun: [{ cron: '* * * * *', limit: 20 }],
|
|
121
|
+
tasks: [yookassa.reconcileTask({ cron: '*/5 * * * *', minAgeMinutes: 10, limit: 50 })],
|
|
122
|
+
},
|
|
123
|
+
})
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
На serverless-хостинге уберите `autoRun` и вызывайте по крону `GET /api/payload-jobs/handle-schedules`, а затем `GET /api/payload-jobs/run` с заголовком `Authorization: Bearer <CRON_SECRET>`. Задача добавляет новый slug, поэтому для базы с миграциями нужна новая миграция.
|
|
127
|
+
|
|
128
|
+
## Отменённые платежи
|
|
129
|
+
|
|
130
|
+
`GET /api/payments/yookassa/status?transaction=<id>&email=<email гостя>` отвечает `{ status: 'succeeded' | 'canceled' | 'pending', cancellation?: { reason, party } }` и доступен только покупателю этой транзакции. Причина также сохраняется в транзакции (`yookassa.cancellation`). На клиенте:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
import { cancellationMessage, getPaymentStatus } from '@serge-pro-dev/payload-payment-yookassa/client'
|
|
134
|
+
|
|
135
|
+
const { status, cancellation } = await getPaymentStatus({ transaction, email })
|
|
136
|
+
if (status === 'canceled') show(cancellationMessage(cancellation?.reason, 'ru')) // или 'en'
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`confirmWithRetry(run, { shouldStop })` перестаёт повторять попытки, как только `shouldStop()` вернёт true (например, платёж отменён). Покажите сообщение и ссылку «Попробовать снова» на оформление заказа.
|
|
140
|
+
|
|
141
|
+
## Безопасность
|
|
142
|
+
|
|
143
|
+
- Сумма считается по ценам из базы (плюс доставка, рассчитанная на сервере), а товары должны совпасть с `cart.subtotal`.
|
|
144
|
+
- При подтверждении проверяются транзакция, корзина, покупатель, сумма, валюта и статус платежа.
|
|
145
|
+
|
|
146
|
+
## Пока не поддерживается
|
|
147
|
+
|
|
148
|
+
Возвраты, двухстадийные платежи.
|
package/dist/amount.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ecommerce amounts are integers in minor units (kopecks for RUB).
|
|
3
|
+
* YooKassa wants a decimal string with a dot: "1500.00".
|
|
4
|
+
*/
|
|
5
|
+
export declare const formatAmount: (minor: number, decimals?: number) => string;
|
|
6
|
+
/**
|
|
7
|
+
* Parses a YooKassa amount string back into minor units.
|
|
8
|
+
* Returns null for anything that is not a plain non-negative decimal or has
|
|
9
|
+
* more precision than `decimals` (so "10.005" never rounds silently).
|
|
10
|
+
*/
|
|
11
|
+
export declare const parseAmount: (value: unknown, decimals?: number) => number | null;
|
package/dist/amount.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ecommerce amounts are integers in minor units (kopecks for RUB).
|
|
3
|
+
* YooKassa wants a decimal string with a dot: "1500.00".
|
|
4
|
+
*/ export const formatAmount = (minor, decimals = 2)=>{
|
|
5
|
+
if (!Number.isSafeInteger(minor) || minor < 0) {
|
|
6
|
+
throw new Error('Amount must be a non-negative integer in minor units');
|
|
7
|
+
}
|
|
8
|
+
if (decimals === 0) return String(minor);
|
|
9
|
+
const factor = 10 ** decimals;
|
|
10
|
+
const whole = Math.floor(minor / factor);
|
|
11
|
+
const fraction = String(minor % factor).padStart(decimals, '0');
|
|
12
|
+
return `${whole}.${fraction}`;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Parses a YooKassa amount string back into minor units.
|
|
16
|
+
* Returns null for anything that is not a plain non-negative decimal or has
|
|
17
|
+
* more precision than `decimals` (so "10.005" never rounds silently).
|
|
18
|
+
*/ export const parseAmount = (value, decimals = 2)=>{
|
|
19
|
+
if (typeof value !== 'string') return null;
|
|
20
|
+
const match = /^(\d+)(?:\.(\d+))?$/.exec(value.trim());
|
|
21
|
+
if (!match) return null;
|
|
22
|
+
const whole = match[1] ?? '0';
|
|
23
|
+
const fraction = (match[2] ?? '').padEnd(decimals, '0');
|
|
24
|
+
if (/[1-9]/.test(fraction.slice(decimals))) return null;
|
|
25
|
+
const minor = Number(whole) * 10 ** decimals + Number(fraction.slice(0, decimals) || '0');
|
|
26
|
+
return Number.isSafeInteger(minor) ? minor : null;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=amount.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/amount.ts"],"sourcesContent":["/**\n * Ecommerce amounts are integers in minor units (kopecks for RUB).\n * YooKassa wants a decimal string with a dot: \"1500.00\".\n */\nexport const formatAmount = (minor: number, decimals = 2): string => {\n if (!Number.isSafeInteger(minor) || minor < 0) {\n throw new Error('Amount must be a non-negative integer in minor units')\n }\n\n if (decimals === 0) return String(minor)\n\n const factor = 10 ** decimals\n const whole = Math.floor(minor / factor)\n const fraction = String(minor % factor).padStart(decimals, '0')\n\n return `${whole}.${fraction}`\n}\n\n/**\n * Parses a YooKassa amount string back into minor units.\n * Returns null for anything that is not a plain non-negative decimal or has\n * more precision than `decimals` (so \"10.005\" never rounds silently).\n */\nexport const parseAmount = (value: unknown, decimals = 2): number | null => {\n if (typeof value !== 'string') return null\n\n const match = /^(\\d+)(?:\\.(\\d+))?$/.exec(value.trim())\n\n if (!match) return null\n\n const whole = match[1] ?? '0'\n const fraction = (match[2] ?? '').padEnd(decimals, '0')\n\n if (/[1-9]/.test(fraction.slice(decimals))) return null\n\n const minor = Number(whole) * 10 ** decimals + Number(fraction.slice(0, decimals) || '0')\n\n return Number.isSafeInteger(minor) ? minor : null\n}\n"],"names":["formatAmount","minor","decimals","Number","isSafeInteger","Error","String","factor","whole","Math","floor","fraction","padStart","parseAmount","value","match","exec","trim","padEnd","test","slice"],"mappings":"AAAA;;;CAGC,GACD,OAAO,MAAMA,eAAe,CAACC,OAAeC,WAAW,CAAC;IACtD,IAAI,CAACC,OAAOC,aAAa,CAACH,UAAUA,QAAQ,GAAG;QAC7C,MAAM,IAAII,MAAM;IAClB;IAEA,IAAIH,aAAa,GAAG,OAAOI,OAAOL;IAElC,MAAMM,SAAS,MAAML;IACrB,MAAMM,QAAQC,KAAKC,KAAK,CAACT,QAAQM;IACjC,MAAMI,WAAWL,OAAOL,QAAQM,QAAQK,QAAQ,CAACV,UAAU;IAE3D,OAAO,GAAGM,MAAM,CAAC,EAAEG,UAAU;AAC/B,EAAC;AAED;;;;CAIC,GACD,OAAO,MAAME,cAAc,CAACC,OAAgBZ,WAAW,CAAC;IACtD,IAAI,OAAOY,UAAU,UAAU,OAAO;IAEtC,MAAMC,QAAQ,sBAAsBC,IAAI,CAACF,MAAMG,IAAI;IAEnD,IAAI,CAACF,OAAO,OAAO;IAEnB,MAAMP,QAAQO,KAAK,CAAC,EAAE,IAAI;IAC1B,MAAMJ,WAAW,AAACI,CAAAA,KAAK,CAAC,EAAE,IAAI,EAAC,EAAGG,MAAM,CAAChB,UAAU;IAEnD,IAAI,QAAQiB,IAAI,CAACR,SAASS,KAAK,CAAClB,YAAY,OAAO;IAEnD,MAAMD,QAAQE,OAAOK,SAAS,MAAMN,WAAWC,OAAOQ,SAASS,KAAK,CAAC,GAAGlB,aAAa;IAErF,OAAOC,OAAOC,aAAa,CAACH,SAASA,QAAQ;AAC/C,EAAC"}
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export type YooKassaPaymentStatus = 'pending' | 'waiting_for_capture' | 'succeeded' | 'canceled';
|
|
2
|
+
export type YooKassaPayment = {
|
|
3
|
+
id: string;
|
|
4
|
+
status: YooKassaPaymentStatus;
|
|
5
|
+
paid: boolean;
|
|
6
|
+
amount: {
|
|
7
|
+
value: string;
|
|
8
|
+
currency: string;
|
|
9
|
+
};
|
|
10
|
+
confirmation?: {
|
|
11
|
+
type: string;
|
|
12
|
+
confirmation_url?: string;
|
|
13
|
+
};
|
|
14
|
+
metadata?: Record<string, string>;
|
|
15
|
+
cancellation_details?: {
|
|
16
|
+
party?: string;
|
|
17
|
+
reason?: string;
|
|
18
|
+
};
|
|
19
|
+
test?: boolean;
|
|
20
|
+
};
|
|
21
|
+
export type CreatePaymentBody = {
|
|
22
|
+
amount: {
|
|
23
|
+
value: string;
|
|
24
|
+
currency: string;
|
|
25
|
+
};
|
|
26
|
+
capture: boolean;
|
|
27
|
+
confirmation: {
|
|
28
|
+
type: 'redirect';
|
|
29
|
+
return_url: string;
|
|
30
|
+
};
|
|
31
|
+
description?: string;
|
|
32
|
+
metadata?: Record<string, string>;
|
|
33
|
+
receipt?: Record<string, unknown>;
|
|
34
|
+
};
|
|
35
|
+
export declare class YooKassaApiError extends Error {
|
|
36
|
+
readonly status: number;
|
|
37
|
+
readonly code?: string;
|
|
38
|
+
constructor(message: string, status: number, code?: string);
|
|
39
|
+
}
|
|
40
|
+
export type YooKassaClientOptions = {
|
|
41
|
+
shopId: string;
|
|
42
|
+
secretKey: string;
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
baseUrl?: string;
|
|
45
|
+
};
|
|
46
|
+
export type YooKassaClient = ReturnType<typeof createYooKassaClient>;
|
|
47
|
+
/** Minimal YooKassa API v3 client: only what the adapter needs. */
|
|
48
|
+
export declare const createYooKassaClient: ({ shopId, secretKey, timeoutMs, baseUrl, }: YooKassaClientOptions) => {
|
|
49
|
+
createPayment: (body: CreatePaymentBody, idempotenceKey: string) => Promise<YooKassaPayment>;
|
|
50
|
+
getPayment: (id: string) => Promise<YooKassaPayment>;
|
|
51
|
+
};
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
const DEFAULT_BASE_URL = 'https://api.yookassa.ru/v3';
|
|
2
|
+
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
3
|
+
export class YooKassaApiError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
code;
|
|
6
|
+
constructor(message, status, code){
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'YooKassaApiError';
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Minimal YooKassa API v3 client: only what the adapter needs. */ export const createYooKassaClient = ({ shopId, secretKey, timeoutMs = DEFAULT_TIMEOUT_MS, baseUrl = DEFAULT_BASE_URL })=>{
|
|
14
|
+
const authorization = `Basic ${Buffer.from(`${shopId}:${secretKey}`).toString('base64')}`;
|
|
15
|
+
const request = async (method, path, options = {})=>{
|
|
16
|
+
const response = await fetch(`${baseUrl}${path}`, {
|
|
17
|
+
method,
|
|
18
|
+
headers: {
|
|
19
|
+
Authorization: authorization,
|
|
20
|
+
'Content-Type': 'application/json',
|
|
21
|
+
...options.idempotenceKey ? {
|
|
22
|
+
'Idempotence-Key': options.idempotenceKey
|
|
23
|
+
} : {}
|
|
24
|
+
},
|
|
25
|
+
...options.body === undefined ? {} : {
|
|
26
|
+
body: JSON.stringify(options.body)
|
|
27
|
+
},
|
|
28
|
+
redirect: 'error',
|
|
29
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
30
|
+
});
|
|
31
|
+
const text = await response.text();
|
|
32
|
+
let json;
|
|
33
|
+
try {
|
|
34
|
+
json = text ? JSON.parse(text) : undefined;
|
|
35
|
+
} catch {
|
|
36
|
+
json = undefined;
|
|
37
|
+
}
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
const error = json ?? {};
|
|
40
|
+
const details = [
|
|
41
|
+
error.code,
|
|
42
|
+
error.description,
|
|
43
|
+
error.parameter
|
|
44
|
+
].filter(Boolean).join(': ');
|
|
45
|
+
throw new YooKassaApiError(`YooKassa API ${response.status}${details ? ` (${details})` : ''}`, response.status, error.code);
|
|
46
|
+
}
|
|
47
|
+
return json;
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
createPayment: (body, idempotenceKey)=>request('POST', '/payments', {
|
|
51
|
+
body,
|
|
52
|
+
idempotenceKey
|
|
53
|
+
}),
|
|
54
|
+
getPayment: (id)=>request('GET', `/payments/${encodeURIComponent(id)}`)
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=api.js.map
|
package/dist/api.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/api.ts"],"sourcesContent":["const DEFAULT_BASE_URL = 'https://api.yookassa.ru/v3'\nconst DEFAULT_TIMEOUT_MS = 15_000\n\nexport type YooKassaPaymentStatus = 'pending' | 'waiting_for_capture' | 'succeeded' | 'canceled'\n\nexport type YooKassaPayment = {\n id: string\n status: YooKassaPaymentStatus\n paid: boolean\n amount: { value: string; currency: string }\n confirmation?: { type: string; confirmation_url?: string }\n metadata?: Record<string, string>\n cancellation_details?: { party?: string; reason?: string }\n test?: boolean\n}\n\nexport type CreatePaymentBody = {\n amount: { value: string; currency: string }\n capture: boolean\n confirmation: { type: 'redirect'; return_url: string }\n description?: string\n metadata?: Record<string, string>\n receipt?: Record<string, unknown>\n}\n\nexport class YooKassaApiError extends Error {\n readonly status: number\n readonly code?: string\n\n constructor(message: string, status: number, code?: string) {\n super(message)\n this.name = 'YooKassaApiError'\n this.status = status\n this.code = code\n }\n}\n\nexport type YooKassaClientOptions = {\n shopId: string\n secretKey: string\n timeoutMs?: number\n baseUrl?: string\n}\n\nexport type YooKassaClient = ReturnType<typeof createYooKassaClient>\n\n/** Minimal YooKassa API v3 client: only what the adapter needs. */\nexport const createYooKassaClient = ({\n shopId,\n secretKey,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n baseUrl = DEFAULT_BASE_URL,\n}: YooKassaClientOptions) => {\n const authorization = `Basic ${Buffer.from(`${shopId}:${secretKey}`).toString('base64')}`\n\n const request = async <T>(\n method: 'GET' | 'POST',\n path: string,\n options: { body?: unknown; idempotenceKey?: string } = {},\n ): Promise<T> => {\n const response = await fetch(`${baseUrl}${path}`, {\n method,\n headers: {\n Authorization: authorization,\n 'Content-Type': 'application/json',\n ...(options.idempotenceKey ? { 'Idempotence-Key': options.idempotenceKey } : {}),\n },\n ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),\n redirect: 'error',\n signal: AbortSignal.timeout(timeoutMs),\n })\n\n const text = await response.text()\n let json: unknown\n\n try {\n json = text ? JSON.parse(text) : undefined\n } catch {\n json = undefined\n }\n\n if (!response.ok) {\n const error = (json ?? {}) as { code?: string; description?: string; parameter?: string }\n const details = [error.code, error.description, error.parameter].filter(Boolean).join(': ')\n\n throw new YooKassaApiError(\n `YooKassa API ${response.status}${details ? ` (${details})` : ''}`,\n response.status,\n error.code,\n )\n }\n\n return json as T\n }\n\n return {\n createPayment: (body: CreatePaymentBody, idempotenceKey: string) =>\n request<YooKassaPayment>('POST', '/payments', { body, idempotenceKey }),\n\n getPayment: (id: string) => request<YooKassaPayment>('GET', `/payments/${encodeURIComponent(id)}`),\n }\n}\n"],"names":["DEFAULT_BASE_URL","DEFAULT_TIMEOUT_MS","YooKassaApiError","Error","status","code","message","name","createYooKassaClient","shopId","secretKey","timeoutMs","baseUrl","authorization","Buffer","from","toString","request","method","path","options","response","fetch","headers","Authorization","idempotenceKey","body","undefined","JSON","stringify","redirect","signal","AbortSignal","timeout","text","json","parse","ok","error","details","description","parameter","filter","Boolean","join","createPayment","getPayment","id","encodeURIComponent"],"mappings":"AAAA,MAAMA,mBAAmB;AACzB,MAAMC,qBAAqB;AAwB3B,OAAO,MAAMC,yBAAyBC;IAC3BC,OAAc;IACdC,KAAa;IAEtB,YAAYC,OAAe,EAAEF,MAAc,EAAEC,IAAa,CAAE;QAC1D,KAAK,CAACC;QACN,IAAI,CAACC,IAAI,GAAG;QACZ,IAAI,CAACH,MAAM,GAAGA;QACd,IAAI,CAACC,IAAI,GAAGA;IACd;AACF;AAWA,iEAAiE,GACjE,OAAO,MAAMG,uBAAuB,CAAC,EACnCC,MAAM,EACNC,SAAS,EACTC,YAAYV,kBAAkB,EAC9BW,UAAUZ,gBAAgB,EACJ;IACtB,MAAMa,gBAAgB,CAAC,MAAM,EAAEC,OAAOC,IAAI,CAAC,GAAGN,OAAO,CAAC,EAAEC,WAAW,EAAEM,QAAQ,CAAC,WAAW;IAEzF,MAAMC,UAAU,OACdC,QACAC,MACAC,UAAuD,CAAC,CAAC;QAEzD,MAAMC,WAAW,MAAMC,MAAM,GAAGV,UAAUO,MAAM,EAAE;YAChDD;YACAK,SAAS;gBACPC,eAAeX;gBACf,gBAAgB;gBAChB,GAAIO,QAAQK,cAAc,GAAG;oBAAE,mBAAmBL,QAAQK,cAAc;gBAAC,IAAI,CAAC,CAAC;YACjF;YACA,GAAIL,QAAQM,IAAI,KAAKC,YAAY,CAAC,IAAI;gBAAED,MAAME,KAAKC,SAAS,CAACT,QAAQM,IAAI;YAAE,CAAC;YAC5EI,UAAU;YACVC,QAAQC,YAAYC,OAAO,CAACtB;QAC9B;QAEA,MAAMuB,OAAO,MAAMb,SAASa,IAAI;QAChC,IAAIC;QAEJ,IAAI;YACFA,OAAOD,OAAON,KAAKQ,KAAK,CAACF,QAAQP;QACnC,EAAE,OAAM;YACNQ,OAAOR;QACT;QAEA,IAAI,CAACN,SAASgB,EAAE,EAAE;YAChB,MAAMC,QAASH,QAAQ,CAAC;YACxB,MAAMI,UAAU;gBAACD,MAAMjC,IAAI;gBAAEiC,MAAME,WAAW;gBAAEF,MAAMG,SAAS;aAAC,CAACC,MAAM,CAACC,SAASC,IAAI,CAAC;YAEtF,MAAM,IAAI1C,iBACR,CAAC,aAAa,EAAEmB,SAASjB,MAAM,GAAGmC,UAAU,CAAC,EAAE,EAAEA,QAAQ,CAAC,CAAC,GAAG,IAAI,EAClElB,SAASjB,MAAM,EACfkC,MAAMjC,IAAI;QAEd;QAEA,OAAO8B;IACT;IAEA,OAAO;QACLU,eAAe,CAACnB,MAAyBD,iBACvCR,QAAyB,QAAQ,aAAa;gBAAES;gBAAMD;YAAe;QAEvEqB,YAAY,CAACC,KAAe9B,QAAyB,OAAO,CAAC,UAAU,EAAE+B,mBAAmBD,KAAK;IACnG;AACF,EAAC"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { PaymentAdapterClient, PaymentAdapterClientArgs } from '@payloadcms/plugin-ecommerce/types';
|
|
2
|
+
export { cancellationMessage } from './messages.js';
|
|
3
|
+
export type { MessageLanguage } from './messages.js';
|
|
4
|
+
/** Client side of the adapter, for `<EcommerceProvider paymentMethods={[...]} />`. */
|
|
5
|
+
export declare const yookassaAdapterClient: (props?: PaymentAdapterClientArgs) => PaymentAdapterClient;
|
|
6
|
+
/**
|
|
7
|
+
* The address of the YooKassa payment page from the result of `initiatePayment('yookassa')`.
|
|
8
|
+
* Send the buyer there: `window.location.assign(url)`.
|
|
9
|
+
*/
|
|
10
|
+
export declare const getConfirmationUrl: (result: unknown) => string | null;
|
|
11
|
+
export type PaymentStatus = {
|
|
12
|
+
/** `not_found` also covers "not your transaction"; `unknown` is a server error. */
|
|
13
|
+
status: 'canceled' | 'not_found' | 'pending' | 'succeeded' | 'unknown';
|
|
14
|
+
cancellation?: {
|
|
15
|
+
party?: string;
|
|
16
|
+
reason?: string;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Asks the server how the payment ended, for the return page. Never throws: a network
|
|
21
|
+
* failure is `unknown`.
|
|
22
|
+
*/
|
|
23
|
+
export declare const getPaymentStatus: ({ transaction, email, apiRoute, }: {
|
|
24
|
+
transaction: string;
|
|
25
|
+
/** Required for guests: the email of the order. */
|
|
26
|
+
email?: string;
|
|
27
|
+
apiRoute?: string;
|
|
28
|
+
}) => Promise<PaymentStatus>;
|
|
29
|
+
type RetryOptions = {
|
|
30
|
+
/** Default 8. */
|
|
31
|
+
attempts?: number;
|
|
32
|
+
/** Default 2000 ms. */
|
|
33
|
+
delayMs?: number;
|
|
34
|
+
/**
|
|
35
|
+
* Checked after each failed attempt; return true to stop retrying and throw the last error
|
|
36
|
+
* (for example when the payment is known to be canceled).
|
|
37
|
+
*/
|
|
38
|
+
shouldStop?: () => boolean | Promise<boolean>;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Confirms the order on the return page. Some payment methods (for example SBP) become
|
|
42
|
+
* final a few seconds after the buyer returns, so a failed confirmation is retried.
|
|
43
|
+
*
|
|
44
|
+
* const result = await confirmWithRetry(() =>
|
|
45
|
+
* confirmOrder('yookassa', { additionalData: { transactionID, customerEmail } }),
|
|
46
|
+
* { shouldStop: async () => (await getPaymentStatus({ transaction })).status === 'canceled' },
|
|
47
|
+
* )
|
|
48
|
+
*/
|
|
49
|
+
export declare const confirmWithRetry: <T>(run: () => Promise<T>, { attempts, delayMs, shouldStop }?: RetryOptions) => Promise<T>;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export { cancellationMessage } from './messages.js';
|
|
2
|
+
/** Client side of the adapter, for `<EcommerceProvider paymentMethods={[...]} />`. */ export const yookassaAdapterClient = (props)=>({
|
|
3
|
+
name: 'yookassa',
|
|
4
|
+
label: props?.label ?? 'ЮKassa',
|
|
5
|
+
initiatePayment: true,
|
|
6
|
+
confirmOrder: true
|
|
7
|
+
});
|
|
8
|
+
/**
|
|
9
|
+
* The address of the YooKassa payment page from the result of `initiatePayment('yookassa')`.
|
|
10
|
+
* Send the buyer there: `window.location.assign(url)`.
|
|
11
|
+
*/ export const getConfirmationUrl = (result)=>{
|
|
12
|
+
if (typeof result !== 'object' || result === null) return null;
|
|
13
|
+
const url = result.confirmationUrl;
|
|
14
|
+
return typeof url === 'string' && url.startsWith('https://') ? url : null;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Asks the server how the payment ended, for the return page. Never throws: a network
|
|
18
|
+
* failure is `unknown`.
|
|
19
|
+
*/ export const getPaymentStatus = async ({ transaction, email, apiRoute = '/api' })=>{
|
|
20
|
+
const params = new URLSearchParams({
|
|
21
|
+
transaction
|
|
22
|
+
});
|
|
23
|
+
if (email) params.set('email', email);
|
|
24
|
+
try {
|
|
25
|
+
const response = await fetch(`${apiRoute}/payments/yookassa/status?${params.toString()}`, {
|
|
26
|
+
credentials: 'include'
|
|
27
|
+
});
|
|
28
|
+
const body = await response.json();
|
|
29
|
+
return typeof body?.status === 'string' ? body : {
|
|
30
|
+
status: 'unknown'
|
|
31
|
+
};
|
|
32
|
+
} catch {
|
|
33
|
+
return {
|
|
34
|
+
status: 'unknown'
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Confirms the order on the return page. Some payment methods (for example SBP) become
|
|
40
|
+
* final a few seconds after the buyer returns, so a failed confirmation is retried.
|
|
41
|
+
*
|
|
42
|
+
* const result = await confirmWithRetry(() =>
|
|
43
|
+
* confirmOrder('yookassa', { additionalData: { transactionID, customerEmail } }),
|
|
44
|
+
* { shouldStop: async () => (await getPaymentStatus({ transaction })).status === 'canceled' },
|
|
45
|
+
* )
|
|
46
|
+
*/ export const confirmWithRetry = async (run, { attempts = 8, delayMs = 2000, shouldStop } = {})=>{
|
|
47
|
+
let lastError;
|
|
48
|
+
for(let attempt = 1; attempt <= attempts; attempt += 1){
|
|
49
|
+
try {
|
|
50
|
+
return await run();
|
|
51
|
+
} catch (error) {
|
|
52
|
+
lastError = error;
|
|
53
|
+
if (attempt >= attempts) break;
|
|
54
|
+
if (shouldStop && await shouldStop()) break;
|
|
55
|
+
await new Promise((resolve)=>setTimeout(resolve, delayMs));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
throw lastError;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type { PaymentAdapterClient, PaymentAdapterClientArgs } from '@payloadcms/plugin-ecommerce/types'\n\nexport { cancellationMessage } from './messages.js'\nexport type { MessageLanguage } from './messages.js'\n\n/** Client side of the adapter, for `<EcommerceProvider paymentMethods={[...]} />`. */\nexport const yookassaAdapterClient = (props?: PaymentAdapterClientArgs): PaymentAdapterClient => ({\n name: 'yookassa',\n label: props?.label ?? 'ЮKassa',\n initiatePayment: true,\n confirmOrder: true,\n})\n\n/**\n * The address of the YooKassa payment page from the result of `initiatePayment('yookassa')`.\n * Send the buyer there: `window.location.assign(url)`.\n */\nexport const getConfirmationUrl = (result: unknown): string | null => {\n if (typeof result !== 'object' || result === null) return null\n\n const url = (result as { confirmationUrl?: unknown }).confirmationUrl\n\n return typeof url === 'string' && url.startsWith('https://') ? url : null\n}\n\nexport type PaymentStatus = {\n /** `not_found` also covers \"not your transaction\"; `unknown` is a server error. */\n status: 'canceled' | 'not_found' | 'pending' | 'succeeded' | 'unknown'\n cancellation?: { party?: string; reason?: string }\n}\n\n/**\n * Asks the server how the payment ended, for the return page. Never throws: a network\n * failure is `unknown`.\n */\nexport const getPaymentStatus = async ({\n transaction,\n email,\n apiRoute = '/api',\n}: {\n transaction: string\n /** Required for guests: the email of the order. */\n email?: string\n apiRoute?: string\n}): Promise<PaymentStatus> => {\n const params = new URLSearchParams({ transaction })\n\n if (email) params.set('email', email)\n\n try {\n const response = await fetch(`${apiRoute}/payments/yookassa/status?${params.toString()}`, {\n credentials: 'include',\n })\n const body = (await response.json()) as PaymentStatus\n\n return typeof body?.status === 'string' ? body : { status: 'unknown' }\n } catch {\n return { status: 'unknown' }\n }\n}\n\ntype RetryOptions = {\n /** Default 8. */\n attempts?: number\n /** Default 2000 ms. */\n delayMs?: number\n /**\n * Checked after each failed attempt; return true to stop retrying and throw the last error\n * (for example when the payment is known to be canceled).\n */\n shouldStop?: () => boolean | Promise<boolean>\n}\n\n/**\n * Confirms the order on the return page. Some payment methods (for example SBP) become\n * final a few seconds after the buyer returns, so a failed confirmation is retried.\n *\n * const result = await confirmWithRetry(() =>\n * confirmOrder('yookassa', { additionalData: { transactionID, customerEmail } }),\n * { shouldStop: async () => (await getPaymentStatus({ transaction })).status === 'canceled' },\n * )\n */\nexport const confirmWithRetry = async <T>(\n run: () => Promise<T>,\n { attempts = 8, delayMs = 2000, shouldStop }: RetryOptions = {},\n): Promise<T> => {\n let lastError: unknown\n\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n try {\n return await run()\n } catch (error) {\n lastError = error\n\n if (attempt >= attempts) break\n\n if (shouldStop && (await shouldStop())) break\n\n await new Promise((resolve) => setTimeout(resolve, delayMs))\n }\n }\n\n throw lastError\n}\n"],"names":["cancellationMessage","yookassaAdapterClient","props","name","label","initiatePayment","confirmOrder","getConfirmationUrl","result","url","confirmationUrl","startsWith","getPaymentStatus","transaction","email","apiRoute","params","URLSearchParams","set","response","fetch","toString","credentials","body","json","status","confirmWithRetry","run","attempts","delayMs","shouldStop","lastError","attempt","error","Promise","resolve","setTimeout"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,gBAAe;AAGnD,oFAAoF,GACpF,OAAO,MAAMC,wBAAwB,CAACC,QAA4D,CAAA;QAChGC,MAAM;QACNC,OAAOF,OAAOE,SAAS;QACvBC,iBAAiB;QACjBC,cAAc;IAChB,CAAA,EAAE;AAEF;;;CAGC,GACD,OAAO,MAAMC,qBAAqB,CAACC;IACjC,IAAI,OAAOA,WAAW,YAAYA,WAAW,MAAM,OAAO;IAE1D,MAAMC,MAAM,AAACD,OAAyCE,eAAe;IAErE,OAAO,OAAOD,QAAQ,YAAYA,IAAIE,UAAU,CAAC,cAAcF,MAAM;AACvE,EAAC;AAQD;;;CAGC,GACD,OAAO,MAAMG,mBAAmB,OAAO,EACrCC,WAAW,EACXC,KAAK,EACLC,WAAW,MAAM,EAMlB;IACC,MAAMC,SAAS,IAAIC,gBAAgB;QAAEJ;IAAY;IAEjD,IAAIC,OAAOE,OAAOE,GAAG,CAAC,SAASJ;IAE/B,IAAI;QACF,MAAMK,WAAW,MAAMC,MAAM,GAAGL,SAAS,0BAA0B,EAAEC,OAAOK,QAAQ,IAAI,EAAE;YACxFC,aAAa;QACf;QACA,MAAMC,OAAQ,MAAMJ,SAASK,IAAI;QAEjC,OAAO,OAAOD,MAAME,WAAW,WAAWF,OAAO;YAAEE,QAAQ;QAAU;IACvE,EAAE,OAAM;QACN,OAAO;YAAEA,QAAQ;QAAU;IAC7B;AACF,EAAC;AAcD;;;;;;;;CAQC,GACD,OAAO,MAAMC,mBAAmB,OAC9BC,KACA,EAAEC,WAAW,CAAC,EAAEC,UAAU,IAAI,EAAEC,UAAU,EAAgB,GAAG,CAAC,CAAC;IAE/D,IAAIC;IAEJ,IAAK,IAAIC,UAAU,GAAGA,WAAWJ,UAAUI,WAAW,EAAG;QACvD,IAAI;YACF,OAAO,MAAML;QACf,EAAE,OAAOM,OAAO;YACdF,YAAYE;YAEZ,IAAID,WAAWJ,UAAU;YAEzB,IAAIE,cAAe,MAAMA,cAAe;YAExC,MAAM,IAAII,QAAQ,CAACC,UAAYC,WAAWD,SAASN;QACrD;IACF;IAEA,MAAME;AACR,EAAC"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { PaymentAdapter } from '@payloadcms/plugin-ecommerce/types';
|
|
2
|
+
import type { ResolvedConfig } from './types.js';
|
|
3
|
+
export declare const snapshotItems: (items: unknown) => Record<string, unknown>[];
|
|
4
|
+
export declare const confirmOrder: (config: ResolvedConfig) => PaymentAdapter["confirmOrder"];
|