@serge-pro-dev/payload-payment-yookassa 0.0.0-stage → 0.1.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +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/dist/status.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { applyPayment } from './finalize.js';
|
|
2
|
+
import { getRelationshipID, isRecord, normalizeEmail } from './utils.js';
|
|
3
|
+
const toCancellation = (value)=>isRecord(value) ? {
|
|
4
|
+
...typeof value.party === 'string' ? {
|
|
5
|
+
party: value.party
|
|
6
|
+
} : {},
|
|
7
|
+
...typeof value.reason === 'string' ? {
|
|
8
|
+
reason: value.reason
|
|
9
|
+
} : {}
|
|
10
|
+
} : undefined;
|
|
11
|
+
/**
|
|
12
|
+
* GET /api/payments/yookassa/status?transaction=<id>&email=<guest email>
|
|
13
|
+
*
|
|
14
|
+
* For the page the buyer returns to: `succeeded`, `canceled` (with the reason) or `pending`.
|
|
15
|
+
* It lets the page stop waiting at once when the payment failed, and say why. The ecommerce
|
|
16
|
+
* confirm-order endpoint cannot do that: it answers any failure with a generic error.
|
|
17
|
+
*
|
|
18
|
+
* Only the buyer gets an answer: a logged-in buyer must own the transaction, a guest must send
|
|
19
|
+
* the email of the order. Anything else is `not_found`, the same as a missing transaction.
|
|
20
|
+
*/ export const statusEndpoint = (config, transactionsSlug = 'transactions')=>({
|
|
21
|
+
path: '/status',
|
|
22
|
+
method: 'get',
|
|
23
|
+
handler: async (req)=>{
|
|
24
|
+
const payload = req.payload;
|
|
25
|
+
const params = req.searchParams ?? new URL(req.url ?? 'http://localhost').searchParams;
|
|
26
|
+
const transactionID = params.get('transaction');
|
|
27
|
+
const email = normalizeEmail(params.get('email'));
|
|
28
|
+
const notFound = ()=>Response.json({
|
|
29
|
+
status: 'not_found'
|
|
30
|
+
}, {
|
|
31
|
+
status: 404
|
|
32
|
+
});
|
|
33
|
+
if (!transactionID) return notFound();
|
|
34
|
+
try {
|
|
35
|
+
const transaction = await payload.findByID({
|
|
36
|
+
collection: transactionsSlug,
|
|
37
|
+
id: transactionID,
|
|
38
|
+
depth: 0,
|
|
39
|
+
disableErrors: true,
|
|
40
|
+
overrideAccess: true
|
|
41
|
+
});
|
|
42
|
+
if (!transaction || transaction.paymentMethod !== 'yookassa') return notFound();
|
|
43
|
+
const customerID = getRelationshipID(transaction.customer);
|
|
44
|
+
const isBuyer = req.user ? customerID !== undefined && customerID === getRelationshipID(req.user.id) : customerID === undefined && email !== undefined && email === normalizeEmail(transaction.customerEmail);
|
|
45
|
+
if (!isBuyer) return notFound();
|
|
46
|
+
const provider = isRecord(transaction.yookassa) ? transaction.yookassa : {};
|
|
47
|
+
if (transaction.order || transaction.status === 'succeeded') {
|
|
48
|
+
return Response.json({
|
|
49
|
+
status: 'succeeded'
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
if (transaction.status === 'cancelled') {
|
|
53
|
+
return Response.json({
|
|
54
|
+
status: 'canceled',
|
|
55
|
+
cancellation: toCancellation(provider.cancellation)
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const paymentID = provider.paymentID;
|
|
59
|
+
if (typeof paymentID !== 'string' || !paymentID) return notFound();
|
|
60
|
+
// Ask YooKassa: the notification may not have arrived yet.
|
|
61
|
+
const payment = await config.client.getPayment(paymentID);
|
|
62
|
+
await applyPayment({
|
|
63
|
+
config,
|
|
64
|
+
payment,
|
|
65
|
+
req,
|
|
66
|
+
transaction,
|
|
67
|
+
transactionsSlug
|
|
68
|
+
});
|
|
69
|
+
if (payment.status === 'canceled') {
|
|
70
|
+
return Response.json({
|
|
71
|
+
status: 'canceled',
|
|
72
|
+
cancellation: toCancellation(payment.cancellation_details)
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return Response.json({
|
|
76
|
+
status: payment.status === 'succeeded' && payment.paid ? 'succeeded' : 'pending'
|
|
77
|
+
});
|
|
78
|
+
} catch (error) {
|
|
79
|
+
payload.logger.error({
|
|
80
|
+
err: error,
|
|
81
|
+
msg: 'Error checking the YooKassa payment status'
|
|
82
|
+
});
|
|
83
|
+
return Response.json({
|
|
84
|
+
status: 'unknown'
|
|
85
|
+
}, {
|
|
86
|
+
status: 500
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=status.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/status.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\nimport { applyPayment } from './finalize.js'\nimport type { ResolvedConfig } from './types.js'\nimport { getRelationshipID, isRecord, normalizeEmail } from './utils.js'\n\ntype Cancellation = { party?: string; reason?: string }\n\nconst toCancellation = (value: unknown): Cancellation | undefined =>\n isRecord(value)\n ? {\n ...(typeof value.party === 'string' ? { party: value.party } : {}),\n ...(typeof value.reason === 'string' ? { reason: value.reason } : {}),\n }\n : undefined\n\n/**\n * GET /api/payments/yookassa/status?transaction=<id>&email=<guest email>\n *\n * For the page the buyer returns to: `succeeded`, `canceled` (with the reason) or `pending`.\n * It lets the page stop waiting at once when the payment failed, and say why. The ecommerce\n * confirm-order endpoint cannot do that: it answers any failure with a generic error.\n *\n * Only the buyer gets an answer: a logged-in buyer must own the transaction, a guest must send\n * the email of the order. Anything else is `not_found`, the same as a missing transaction.\n */\nexport const statusEndpoint = (\n config: ResolvedConfig,\n transactionsSlug = 'transactions',\n): Endpoint => ({\n path: '/status',\n method: 'get',\n handler: async (req) => {\n const payload = req.payload\n const params = req.searchParams ?? new URL(req.url ?? 'http://localhost').searchParams\n const transactionID = params.get('transaction')\n const email = normalizeEmail(params.get('email'))\n\n const notFound = () => Response.json({ status: 'not_found' }, { status: 404 })\n\n if (!transactionID) return notFound()\n\n try {\n const transaction = (await payload.findByID({\n collection: transactionsSlug as never,\n id: transactionID,\n depth: 0,\n disableErrors: true,\n overrideAccess: true,\n })) as unknown as Record<string, unknown> | null\n\n if (!transaction || transaction.paymentMethod !== 'yookassa') return notFound()\n\n const customerID = getRelationshipID(transaction.customer)\n\n const isBuyer = req.user\n ? customerID !== undefined && customerID === getRelationshipID(req.user.id)\n : customerID === undefined && email !== undefined && email === normalizeEmail(transaction.customerEmail)\n\n if (!isBuyer) return notFound()\n\n const provider = isRecord(transaction.yookassa) ? transaction.yookassa : {}\n\n if (transaction.order || transaction.status === 'succeeded') {\n return Response.json({ status: 'succeeded' })\n }\n\n if (transaction.status === 'cancelled') {\n return Response.json({ status: 'canceled', cancellation: toCancellation(provider.cancellation) })\n }\n\n const paymentID = provider.paymentID\n\n if (typeof paymentID !== 'string' || !paymentID) return notFound()\n\n // Ask YooKassa: the notification may not have arrived yet.\n const payment = await config.client.getPayment(paymentID)\n\n await applyPayment({ config, payment, req, transaction, transactionsSlug })\n\n if (payment.status === 'canceled') {\n return Response.json({\n status: 'canceled',\n cancellation: toCancellation(payment.cancellation_details),\n })\n }\n\n return Response.json({\n status: payment.status === 'succeeded' && payment.paid ? 'succeeded' : 'pending',\n })\n } catch (error) {\n payload.logger.error({ err: error, msg: 'Error checking the YooKassa payment status' })\n\n return Response.json({ status: 'unknown' }, { status: 500 })\n }\n },\n})\n"],"names":["applyPayment","getRelationshipID","isRecord","normalizeEmail","toCancellation","value","party","reason","undefined","statusEndpoint","config","transactionsSlug","path","method","handler","req","payload","params","searchParams","URL","url","transactionID","get","email","notFound","Response","json","status","transaction","findByID","collection","id","depth","disableErrors","overrideAccess","paymentMethod","customerID","customer","isBuyer","user","customerEmail","provider","yookassa","order","cancellation","paymentID","payment","client","getPayment","cancellation_details","paid","error","logger","err","msg"],"mappings":"AAEA,SAASA,YAAY,QAAQ,gBAAe;AAE5C,SAASC,iBAAiB,EAAEC,QAAQ,EAAEC,cAAc,QAAQ,aAAY;AAIxE,MAAMC,iBAAiB,CAACC,QACtBH,SAASG,SACL;QACE,GAAI,OAAOA,MAAMC,KAAK,KAAK,WAAW;YAAEA,OAAOD,MAAMC,KAAK;QAAC,IAAI,CAAC,CAAC;QACjE,GAAI,OAAOD,MAAME,MAAM,KAAK,WAAW;YAAEA,QAAQF,MAAME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ASC,IAAI,CAAC;wBAAEC,QAAQ;wBAAYiB,cAAcxC,eAAeqC,SAASG,YAAY;oBAAE;gBACjG;gBAEA,MAAMC,YAAYJ,SAASI,SAAS;gBAEpC,IAAI,OAAOA,cAAc,YAAY,CAACA,WAAW,OAAOrB;gBAExD,2DAA2D;gBAC3D,MAAMsB,UAAU,MAAMpC,OAAOqC,MAAM,CAACC,UAAU,CAACH;gBAE/C,MAAM7C,aAAa;oBAAEU;oBAAQoC;oBAAS/B;oBAAKa;oBAAajB;gBAAiB;gBAEzE,IAAImC,QAAQnB,MAAM,KAAK,YAAY;oBACjC,OAAOF,SAASC,IAAI,CAAC;wBACnBC,QAAQ;wBACRiB,cAAcxC,eAAe0C,QAAQG,oBAAoB;oBAC3D;gBACF;gBAEA,OAAOxB,SAASC,IAAI,CAAC;oBACnBC,QAAQmB,QAAQnB,MAAM,KAAK,eAAemB,QAAQI,IAAI,GAAG,cAAc;gBACzE;YACF,EAAE,OAAOC,OAAO;gBACdnC,QAAQoC,MAAM,CAACD,KAAK,CAAC;oBAAEE,KAAKF;oBAAOG,KAAK;gBAA6C;gBAErF,OAAO7B,SAASC,IAAI,CAAC;oBAAEC,QAAQ;gBAAU,GAAG;oBAAEA,QAAQ;gBAAI;YAC5D;QACF;IACF,CAAA,EAAE"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { PaymentAdapterArgs } from '@payloadcms/plugin-ecommerce/types';
|
|
2
|
+
import type { YooKassaClient } from './api.js';
|
|
3
|
+
import type { PayloadRequest } from 'payload';
|
|
4
|
+
import type { ReceiptOptions } from './receipt.js';
|
|
5
|
+
/**
|
|
6
|
+
* Decides the receipt options for every payment. See `receiptFromSettings`, which reads
|
|
7
|
+
* them from a global editable in the admin panel.
|
|
8
|
+
*/
|
|
9
|
+
export type ReceiptResolver = (args: {
|
|
10
|
+
req: PayloadRequest;
|
|
11
|
+
}) => false | ReceiptOptions | Promise<false | ReceiptOptions>;
|
|
12
|
+
/** The chosen delivery with its price in minor units. It becomes part of the payment amount. */
|
|
13
|
+
export type DeliveryQuote = {
|
|
14
|
+
methodID: string;
|
|
15
|
+
title: string;
|
|
16
|
+
amount: number;
|
|
17
|
+
details?: Record<string, unknown>;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Prices the delivery for a payment: return `null` when the shop has no delivery, a quote
|
|
21
|
+
* otherwise, and throw when the buyer's choice is invalid. The buyer's data is in `req.data`.
|
|
22
|
+
* See `deliveryResolver` of @serge-pro-dev/payload-ecommerce-delivery.
|
|
23
|
+
*/
|
|
24
|
+
export type DeliveryResolver = (args: {
|
|
25
|
+
req: PayloadRequest;
|
|
26
|
+
currency: string;
|
|
27
|
+
/** Cost of the goods, minor units. */
|
|
28
|
+
subtotal: number;
|
|
29
|
+
shippingAddress?: Record<string, unknown>;
|
|
30
|
+
}) => DeliveryQuote | null | Promise<DeliveryQuote | null>;
|
|
31
|
+
export type YooKassaAdapterProps = PaymentAdapterArgs & {
|
|
32
|
+
/** Shop id from the YooKassa dashboard (test shops have their own). */
|
|
33
|
+
shopId: string;
|
|
34
|
+
/** Secret key of the shop. Keep it in the environment, never in the database or the repo. */
|
|
35
|
+
secretKey: string;
|
|
36
|
+
/**
|
|
37
|
+
* Public address of the site, used for the return link after payment,
|
|
38
|
+
* e.g. https://shop.example.com. For local tests use your tunnel address.
|
|
39
|
+
*/
|
|
40
|
+
returnBaseUrl: string;
|
|
41
|
+
/** Page that confirms the order after the buyer returns. Default "/checkout/confirm-order". */
|
|
42
|
+
returnPath?: string;
|
|
43
|
+
/**
|
|
44
|
+
* 54-FZ receipts sent with the payment ("Receipts from YooKassa").
|
|
45
|
+
* Pass `false` (default) when receipts are not connected in your YooKassa shop,
|
|
46
|
+
* fixed options, or `receiptFromSettings()` to edit them in the admin panel.
|
|
47
|
+
*/
|
|
48
|
+
receipt?: false | ReceiptOptions | ReceiptResolver;
|
|
49
|
+
/**
|
|
50
|
+
* Optional delivery: its cost is added to the payment amount and to the receipt.
|
|
51
|
+
* Pass `deliveryResolver()` from @serge-pro-dev/payload-ecommerce-delivery.
|
|
52
|
+
*/
|
|
53
|
+
delivery?: DeliveryResolver;
|
|
54
|
+
/** Name of the product/variant select field with the VAT code. Default "vatCode". */
|
|
55
|
+
vatCodeField?: string;
|
|
56
|
+
/** Default "products". */
|
|
57
|
+
productsSlug?: string;
|
|
58
|
+
/** Default "variants". */
|
|
59
|
+
variantsSlug?: string;
|
|
60
|
+
/** Default "orders". The webhook creates orders here. */
|
|
61
|
+
ordersSlug?: string;
|
|
62
|
+
/** Default "carts". */
|
|
63
|
+
cartsSlug?: string;
|
|
64
|
+
/** The only currency this adapter accepts. Default "RUB". */
|
|
65
|
+
currency?: string;
|
|
66
|
+
/** Decimal places of that currency. Default 2. */
|
|
67
|
+
decimals?: number;
|
|
68
|
+
/** Timeout of every YooKassa API request, ms. Default 15000. */
|
|
69
|
+
timeoutMs?: number;
|
|
70
|
+
};
|
|
71
|
+
export type ResolvedConfig = {
|
|
72
|
+
client: YooKassaClient;
|
|
73
|
+
returnBaseUrl: string;
|
|
74
|
+
returnPath: string;
|
|
75
|
+
receipt: false | ReceiptOptions | ReceiptResolver;
|
|
76
|
+
delivery?: DeliveryResolver;
|
|
77
|
+
vatCodeField: string;
|
|
78
|
+
productsSlug: string;
|
|
79
|
+
variantsSlug: string;
|
|
80
|
+
ordersSlug: string;
|
|
81
|
+
cartsSlug: string;
|
|
82
|
+
currency: string;
|
|
83
|
+
decimals: number;
|
|
84
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { PaymentAdapterArgs } from '@payloadcms/plugin-ecommerce/types'\n\nimport type { YooKassaClient } from './api.js'\nimport type { PayloadRequest } from 'payload'\n\nimport type { ReceiptOptions } from './receipt.js'\n\n/**\n * Decides the receipt options for every payment. See `receiptFromSettings`, which reads\n * them from a global editable in the admin panel.\n */\nexport type ReceiptResolver = (args: {\n req: PayloadRequest\n}) => false | ReceiptOptions | Promise<false | ReceiptOptions>\n\n/** The chosen delivery with its price in minor units. It becomes part of the payment amount. */\nexport type DeliveryQuote = {\n methodID: string\n title: string\n amount: number\n details?: Record<string, unknown>\n}\n\n/**\n * Prices the delivery for a payment: return `null` when the shop has no delivery, a quote\n * otherwise, and throw when the buyer's choice is invalid. The buyer's data is in `req.data`.\n * See `deliveryResolver` of @serge-pro-dev/payload-ecommerce-delivery.\n */\nexport type DeliveryResolver = (args: {\n req: PayloadRequest\n currency: string\n /** Cost of the goods, minor units. */\n subtotal: number\n shippingAddress?: Record<string, unknown>\n}) => DeliveryQuote | null | Promise<DeliveryQuote | null>\n\nexport type YooKassaAdapterProps = PaymentAdapterArgs & {\n /** Shop id from the YooKassa dashboard (test shops have their own). */\n shopId: string\n /** Secret key of the shop. Keep it in the environment, never in the database or the repo. */\n secretKey: string\n /**\n * Public address of the site, used for the return link after payment,\n * e.g. https://shop.example.com. For local tests use your tunnel address.\n */\n returnBaseUrl: string\n /** Page that confirms the order after the buyer returns. Default \"/checkout/confirm-order\". */\n returnPath?: string\n /**\n * 54-FZ receipts sent with the payment (\"Receipts from YooKassa\").\n * Pass `false` (default) when receipts are not connected in your YooKassa shop,\n * fixed options, or `receiptFromSettings()` to edit them in the admin panel.\n */\n receipt?: false | ReceiptOptions | ReceiptResolver\n /**\n * Optional delivery: its cost is added to the payment amount and to the receipt.\n * Pass `deliveryResolver()` from @serge-pro-dev/payload-ecommerce-delivery.\n */\n delivery?: DeliveryResolver\n /** Name of the product/variant select field with the VAT code. Default \"vatCode\". */\n vatCodeField?: string\n /** Default \"products\". */\n productsSlug?: string\n /** Default \"variants\". */\n variantsSlug?: string\n /** Default \"orders\". The webhook creates orders here. */\n ordersSlug?: string\n /** Default \"carts\". */\n cartsSlug?: string\n /** The only currency this adapter accepts. Default \"RUB\". */\n currency?: string\n /** Decimal places of that currency. Default 2. */\n decimals?: number\n /** Timeout of every YooKassa API request, ms. Default 15000. */\n timeoutMs?: number\n}\n\nexport type ResolvedConfig = {\n client: YooKassaClient\n returnBaseUrl: string\n returnPath: string\n receipt: false | ReceiptOptions | ReceiptResolver\n delivery?: DeliveryResolver\n vatCodeField: string\n productsSlug: string\n variantsSlug: string\n ordersSlug: string\n cartsSlug: string\n currency: string\n decimals: number\n}\n"],"names":[],"mappings":"AA6EA,WAaC"}
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
2
|
+
/** Raw id of a relationship value (populated document or plain id). Keeps the id type. */
|
|
3
|
+
export declare const getDocumentID: (value: unknown) => number | string | undefined;
|
|
4
|
+
/** Relationship id as a string, for comparisons. */
|
|
5
|
+
export declare const getRelationshipID: (value: unknown) => string | undefined;
|
|
6
|
+
export declare const normalizeEmail: (value: unknown) => string | undefined;
|
|
7
|
+
/** `base` + `path` with query parameters; empty values are skipped. */
|
|
8
|
+
export declare const buildReturnUrl: (base: string, path: string, params: Record<string, string | undefined>) => string;
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export const isRecord = (value)=>typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2
|
+
/** Raw id of a relationship value (populated document or plain id). Keeps the id type. */ export const getDocumentID = (value)=>{
|
|
3
|
+
const id = isRecord(value) ? value.id : value;
|
|
4
|
+
if (typeof id === 'number' && Number.isFinite(id)) return id;
|
|
5
|
+
if (typeof id === 'string' && id.trim()) return id;
|
|
6
|
+
return undefined;
|
|
7
|
+
};
|
|
8
|
+
/** Relationship id as a string, for comparisons. */ export const getRelationshipID = (value)=>{
|
|
9
|
+
const id = getDocumentID(value);
|
|
10
|
+
return id === undefined ? undefined : String(id);
|
|
11
|
+
};
|
|
12
|
+
export const normalizeEmail = (value)=>{
|
|
13
|
+
if (typeof value !== 'string') return undefined;
|
|
14
|
+
const email = value.trim().toLowerCase();
|
|
15
|
+
return email || undefined;
|
|
16
|
+
};
|
|
17
|
+
/** `base` + `path` with query parameters; empty values are skipped. */ export const buildReturnUrl = (base, path, params)=>{
|
|
18
|
+
const url = new URL(path, base);
|
|
19
|
+
for (const [key, value] of Object.entries(params)){
|
|
20
|
+
if (value) url.searchParams.set(key, value);
|
|
21
|
+
}
|
|
22
|
+
return url.toString();
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts"],"sourcesContent":["export const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Raw id of a relationship value (populated document or plain id). Keeps the id type. */\nexport const getDocumentID = (value: unknown): number | string | undefined => {\n const id = isRecord(value) ? value.id : value\n\n if (typeof id === 'number' && Number.isFinite(id)) return id\n\n if (typeof id === 'string' && id.trim()) return id\n\n return undefined\n}\n\n/** Relationship id as a string, for comparisons. */\nexport const getRelationshipID = (value: unknown): string | undefined => {\n const id = getDocumentID(value)\n\n return id === undefined ? undefined : String(id)\n}\n\nexport const normalizeEmail = (value: unknown): string | undefined => {\n if (typeof value !== 'string') return undefined\n\n const email = value.trim().toLowerCase()\n\n return email || undefined\n}\n\n/** `base` + `path` with query parameters; empty values are skipped. */\nexport const buildReturnUrl = (\n base: string,\n path: string,\n params: Record<string, string | undefined>,\n): string => {\n const url = new URL(path, base)\n\n for (const [key, value] of Object.entries(params)) {\n if (value) url.searchParams.set(key, value)\n }\n\n return url.toString()\n}\n"],"names":["isRecord","value","Array","isArray","getDocumentID","id","Number","isFinite","trim","undefined","getRelationshipID","String","normalizeEmail","email","toLowerCase","buildReturnUrl","base","path","params","url","URL","key","Object","entries","searchParams","set","toString"],"mappings":"AAAA,OAAO,MAAMA,WAAW,CAACC,QACvB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF,OAAM;AAEtE,wFAAwF,GACxF,OAAO,MAAMG,gBAAgB,CAACH;IAC5B,MAAMI,KAAKL,SAASC,SAASA,MAAMI,EAAE,GAAGJ;IAExC,IAAI,OAAOI,OAAO,YAAYC,OAAOC,QAAQ,CAACF,KAAK,OAAOA;IAE1D,IAAI,OAAOA,OAAO,YAAYA,GAAGG,IAAI,IAAI,OAAOH;IAEhD,OAAOI;AACT,EAAC;AAED,kDAAkD,GAClD,OAAO,MAAMC,oBAAoB,CAACT;IAChC,MAAMI,KAAKD,cAAcH;IAEzB,OAAOI,OAAOI,YAAYA,YAAYE,OAAON;AAC/C,EAAC;AAED,OAAO,MAAMO,iBAAiB,CAACX;IAC7B,IAAI,OAAOA,UAAU,UAAU,OAAOQ;IAEtC,MAAMI,QAAQZ,MAAMO,IAAI,GAAGM,WAAW;IAEtC,OAAOD,SAASJ;AAClB,EAAC;AAED,qEAAqE,GACrE,OAAO,MAAMM,iBAAiB,CAC5BC,MACAC,MACAC;IAEA,MAAMC,MAAM,IAAIC,IAAIH,MAAMD;IAE1B,KAAK,MAAM,CAACK,KAAKpB,MAAM,IAAIqB,OAAOC,OAAO,CAACL,QAAS;QACjD,IAAIjB,OAAOkB,IAAIK,YAAY,CAACC,GAAG,CAACJ,KAAKpB;IACvC;IAEA,OAAOkB,IAAIO,QAAQ;AACrB,EAAC"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Endpoint } from 'payload';
|
|
2
|
+
import type { ResolvedConfig } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* POST /api/payments/yookassa/webhooks
|
|
5
|
+
*
|
|
6
|
+
* Set this address in the YooKassa dashboard (Integration -> HTTP notifications) for
|
|
7
|
+
* payment.succeeded and payment.canceled. YooKassa does not sign notifications, so the body
|
|
8
|
+
* is never trusted: the payment is fetched again by id.
|
|
9
|
+
*
|
|
10
|
+
* The webhook records the status and, once the payment has succeeded, creates the order
|
|
11
|
+
* itself (see applyPayment), so the buyer closing the payment page loses nothing. If the
|
|
12
|
+
* buyer's return page gets there first, the atomic claim makes this a no-op, and the reverse
|
|
13
|
+
* is handled by the ecommerce confirm-order endpoint. A missed notification is caught by the
|
|
14
|
+
* reconcile job.
|
|
15
|
+
*/
|
|
16
|
+
export declare const webhooksEndpoint: (config: ResolvedConfig, transactionsSlug?: string) => Endpoint;
|
package/dist/webhooks.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { applyPayment } from './finalize.js';
|
|
2
|
+
import { isRecord } from './utils.js';
|
|
3
|
+
/**
|
|
4
|
+
* POST /api/payments/yookassa/webhooks
|
|
5
|
+
*
|
|
6
|
+
* Set this address in the YooKassa dashboard (Integration -> HTTP notifications) for
|
|
7
|
+
* payment.succeeded and payment.canceled. YooKassa does not sign notifications, so the body
|
|
8
|
+
* is never trusted: the payment is fetched again by id.
|
|
9
|
+
*
|
|
10
|
+
* The webhook records the status and, once the payment has succeeded, creates the order
|
|
11
|
+
* itself (see applyPayment), so the buyer closing the payment page loses nothing. If the
|
|
12
|
+
* buyer's return page gets there first, the atomic claim makes this a no-op, and the reverse
|
|
13
|
+
* is handled by the ecommerce confirm-order endpoint. A missed notification is caught by the
|
|
14
|
+
* reconcile job.
|
|
15
|
+
*/ export const webhooksEndpoint = (config, transactionsSlug = 'transactions')=>({
|
|
16
|
+
path: '/webhooks',
|
|
17
|
+
method: 'post',
|
|
18
|
+
handler: async (req)=>{
|
|
19
|
+
const payload = req.payload;
|
|
20
|
+
let body;
|
|
21
|
+
try {
|
|
22
|
+
body = req.json ? await req.json() : undefined;
|
|
23
|
+
} catch {
|
|
24
|
+
return Response.json({
|
|
25
|
+
received: false
|
|
26
|
+
}, {
|
|
27
|
+
status: 400
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
const paymentID = isRecord(body) && isRecord(body.object) ? body.object.id : undefined;
|
|
31
|
+
if (!isRecord(body) || body.type !== 'notification' || typeof paymentID !== 'string') {
|
|
32
|
+
return Response.json({
|
|
33
|
+
received: false
|
|
34
|
+
}, {
|
|
35
|
+
status: 400
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const payment = await config.client.getPayment(paymentID);
|
|
40
|
+
const found = await payload.find({
|
|
41
|
+
collection: transactionsSlug,
|
|
42
|
+
depth: 0,
|
|
43
|
+
limit: 1,
|
|
44
|
+
pagination: false,
|
|
45
|
+
overrideAccess: true,
|
|
46
|
+
where: {
|
|
47
|
+
'yookassa.paymentID': {
|
|
48
|
+
equals: payment.id
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
const transaction = found.docs[0];
|
|
53
|
+
// Not ours (another shop on the same account, or a deleted test transaction).
|
|
54
|
+
if (!transaction) return Response.json({
|
|
55
|
+
received: true
|
|
56
|
+
});
|
|
57
|
+
const result = await applyPayment({
|
|
58
|
+
config,
|
|
59
|
+
payment,
|
|
60
|
+
req,
|
|
61
|
+
transaction,
|
|
62
|
+
transactionsSlug
|
|
63
|
+
});
|
|
64
|
+
payload.logger.info(`YooKassa payment ${payment.id}: ${result}`);
|
|
65
|
+
return Response.json({
|
|
66
|
+
received: true
|
|
67
|
+
});
|
|
68
|
+
} catch (error) {
|
|
69
|
+
payload.logger.error({
|
|
70
|
+
err: error,
|
|
71
|
+
msg: 'Error handling YooKassa notification'
|
|
72
|
+
});
|
|
73
|
+
// A non-200 answer makes YooKassa retry the notification later.
|
|
74
|
+
return Response.json({
|
|
75
|
+
received: false
|
|
76
|
+
}, {
|
|
77
|
+
status: 500
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
//# sourceMappingURL=webhooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhooks.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\nimport { applyPayment } from './finalize.js'\nimport type { ResolvedConfig } from './types.js'\nimport { isRecord } from './utils.js'\n\n/**\n * POST /api/payments/yookassa/webhooks\n *\n * Set this address in the YooKassa dashboard (Integration -> HTTP notifications) for\n * payment.succeeded and payment.canceled. YooKassa does not sign notifications, so the body\n * is never trusted: the payment is fetched again by id.\n *\n * The webhook records the status and, once the payment has succeeded, creates the order\n * itself (see applyPayment), so the buyer closing the payment page loses nothing. If the\n * buyer's return page gets there first, the atomic claim makes this a no-op, and the reverse\n * is handled by the ecommerce confirm-order endpoint. A missed notification is caught by the\n * reconcile job.\n */\nexport const webhooksEndpoint = (\n config: ResolvedConfig,\n transactionsSlug = 'transactions',\n): Endpoint => ({\n path: '/webhooks',\n method: 'post',\n handler: async (req) => {\n const payload = req.payload\n\n let body: unknown\n\n try {\n body = req.json ? await req.json() : undefined\n } catch {\n return Response.json({ received: false }, { status: 400 })\n }\n\n const paymentID = isRecord(body) && isRecord(body.object) ? body.object.id : undefined\n\n if (!isRecord(body) || body.type !== 'notification' || typeof paymentID !== 'string') {\n return Response.json({ received: false }, { status: 400 })\n }\n\n try {\n const payment = await config.client.getPayment(paymentID)\n\n const found = await payload.find({\n collection: transactionsSlug as never,\n depth: 0,\n limit: 1,\n pagination: false,\n overrideAccess: true,\n where: { 'yookassa.paymentID': { equals: payment.id } } as never,\n })\n\n const transaction = found.docs[0] as unknown as Record<string, unknown> | undefined\n\n // Not ours (another shop on the same account, or a deleted test transaction).\n if (!transaction) return Response.json({ received: true })\n\n const result = await applyPayment({ config, payment, req, transaction, transactionsSlug })\n\n payload.logger.info(`YooKassa payment ${payment.id}: ${result}`)\n\n return Response.json({ received: true })\n } catch (error) {\n payload.logger.error({ err: error, msg: 'Error handling YooKassa notification' })\n\n // A non-200 answer makes YooKassa retry the notification later.\n return Response.json({ received: false }, { status: 500 })\n }\n },\n})\n"],"names":["applyPayment","isRecord","webhooksEndpoint","config","transactionsSlug","path","method","handler","req","payload","body","json","undefined","Response","received","status","paymentID","object","id","type","payment","client","getPayment","found","find","collection","depth","limit","pagination","overrideAccess","where","equals","transaction","docs","result","logger","info","error","err","msg"],"mappings":"AAEA,SAASA,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,iBAAiB,EAAEhB,QAAQF,EAAE,CAAC,EAAE,EAAEgB,QAAQ;gBAE/D,OAAOrB,SAASF,IAAI,CAAC;oBAAEG,UAAU;gBAAK;YACxC,EAAE,OAAOuB,OAAO;gBACd5B,QAAQ0B,MAAM,CAACE,KAAK,CAAC;oBAAEC,KAAKD;oBAAOE,KAAK;gBAAuC;gBAE/E,gEAAgE;gBAChE,OAAO1B,SAASF,IAAI,CAAC;oBAAEG,UAAU;gBAAM,GAAG;oBAAEC,QAAQ;gBAAI;YAC1D;QACF;IACF,CAAA,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@serge-pro-dev/payload-payment-yookassa",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-beta.0",
|
|
4
|
+
"description": "YooKassa payment adapter for @payloadcms/plugin-ecommerce (Payload CMS 4): redirect payments, 54-FZ receipts, webhook, UTM on the transaction.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"payload",
|
|
7
|
+
"payloadcms",
|
|
8
|
+
"payload-plugin",
|
|
9
|
+
"ecommerce",
|
|
10
|
+
"payments",
|
|
11
|
+
"yookassa",
|
|
12
|
+
"yookassa-api"
|
|
13
|
+
],
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"type": "module",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/serge-pro-dev/payload-plugins.git",
|
|
19
|
+
"directory": "packages/payment-yookassa"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"README.ru.md"
|
|
28
|
+
],
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./client": {
|
|
35
|
+
"types": "./dist/client.d.ts",
|
|
36
|
+
"default": "./dist/client.js"
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@serge-pro-dev/payload-plugins-shared": "^0.1.0-beta.1"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@payloadcms/plugin-ecommerce": "4.0.0-beta.12"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@payloadcms/plugin-ecommerce": "^4.0.0-beta.12",
|
|
48
|
+
"payload": "^4.0.0-beta.12"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"clean": "node ../../scripts/clean.mjs",
|
|
52
|
+
"build": "pnpm clean && pnpm build:types && pnpm build:swc && node ../../scripts/copy-assets.mjs",
|
|
53
|
+
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
|
54
|
+
"build:types": "tsc --emitDeclarationOnly --outDir dist",
|
|
55
|
+
"typecheck": "tsc --noEmit"
|
|
56
|
+
}
|
|
6
57
|
}
|