work-license-server 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Интеграция платёжного шлюза ЮKassa (API v3: https://api.yookassa.ru/v3/payments)
3
+ * для продажи ПАК WORK и дополнительных годовых пользовательских лицензий (Start / Business / Enterprise).
4
+ *
5
+ * Поддерживает:
6
+ * - Боевой режим ЮKassa (Basic Auth shopId:secretKey, Idempotence-Key, 54-ФЗ чек receipt, metadata);
7
+ * - Встроенный песочный режим (когда боевые ключи не заданы в окружении) со страницей тестовой оплаты
8
+ * /pay/sandbox/:orderId, эмулирующей полный цикл ЮKassa вплоть до webhook payment.succeeded;
9
+ * - Обработку входящих webhook-уведомлений ЮKassa (payment.succeeded, payment.canceled, refund.succeeded).
10
+ */
11
+ import crypto from 'node:crypto';
12
+
13
+ const YOOKASSA_API_URL = 'https://api.yookassa.ru/v3/payments';
14
+
15
+ export class YooKassaService {
16
+ constructor({
17
+ store,
18
+ shopId = process.env.YOOKASSA_SHOP_ID || '',
19
+ secretKey = process.env.YOOKASSA_SECRET_KEY || '',
20
+ publicOrigin = process.env.PUBLIC_ORIGIN || 'https://work.odant.org',
21
+ onOrderPaid = null,
22
+ fetchImpl = globalThis.fetch,
23
+ } = {}) {
24
+ this.store = store;
25
+ this.shopId = shopId;
26
+ this.secretKey = secretKey;
27
+ this.publicOrigin = String(publicOrigin).replace(/\/+$/, '');
28
+ this.onOrderPaid = onOrderPaid;
29
+ this.fetchImpl = fetchImpl;
30
+ }
31
+
32
+ get isLiveMode() {
33
+ return Boolean(this.shopId && this.secretKey);
34
+ }
35
+
36
+ /**
37
+ * Сформировать тело запроса к ЮKassa v3 (/v3/payments) с чеком по 54-ФЗ.
38
+ */
39
+ buildYooKassaPaymentPayload(order) {
40
+ const valueStr = Number(order.amountRub || 0).toFixed(2);
41
+ const description = order.includeBasePak
42
+ ? `Заказ ${order.orderId}: ПАК WORK (5 вечных мест) + доп. лицензии (${order.addonSeats} мест, ${order.tierName})`
43
+ : `Заказ ${order.orderId}: Годовая лицензия WORK (${order.addonSeats} польз., уровень ${order.tierName}, ${order.years} г.)`;
44
+
45
+ return {
46
+ amount: {
47
+ value: valueStr,
48
+ currency: 'RUB',
49
+ },
50
+ capture: true,
51
+ confirmation: {
52
+ type: 'redirect',
53
+ return_url: order.returnUrl || `${this.publicOrigin}/?order=${encodeURIComponent(order.orderId)}`,
54
+ },
55
+ description: description.slice(0, 128),
56
+ metadata: {
57
+ orderId: order.orderId,
58
+ licenseId: order.licenseId,
59
+ tier: order.tier,
60
+ addonSeats: String(order.addonSeats),
61
+ years: String(order.years),
62
+ includeBasePak: String(!!order.includeBasePak),
63
+ },
64
+ receipt: {
65
+ customer: {
66
+ email: order.customer?.email || 'billing@odant.org',
67
+ ...(order.customer?.inn ? { inn: String(order.customer.inn) } : {}),
68
+ ...(order.customer?.name ? { full_name: String(order.customer.name) } : {}),
69
+ },
70
+ items: (order.items || []).map(item => ({
71
+ description: String(item.title || 'Лицензия WORK').slice(0, 128),
72
+ quantity: String(item.quantity || 1),
73
+ amount: {
74
+ value: Number(item.unitPriceRub || order.amountRub).toFixed(2),
75
+ currency: 'RUB',
76
+ },
77
+ vat_code: 1,
78
+ payment_mode: 'full_payment',
79
+ payment_subject: 'intellectual_activity',
80
+ })),
81
+ },
82
+ };
83
+ }
84
+
85
+ /**
86
+ * Создать платёж в ЮKassa (или в локальной песочнице, если не заданы боевые ключи).
87
+ */
88
+ async createPaymentForOrder(order, { originOverride = '' } = {}) {
89
+ const baseOrigin = String(originOverride || this.publicOrigin).replace(/\/+$/, '');
90
+ const body = this.buildYooKassaPaymentPayload(order);
91
+
92
+ if (this.isLiveMode && typeof this.fetchImpl === 'function') {
93
+ const idempotenceKey = crypto.randomUUID();
94
+ const basicCreds = Buffer.from(`${this.shopId}:${this.secretKey}`, 'utf8').toString('base64');
95
+ const res = await this.fetchImpl(YOOKASSA_API_URL, {
96
+ method: 'POST',
97
+ headers: {
98
+ 'Authorization': `Basic ${basicCreds}`,
99
+ 'Idempotence-Key': idempotenceKey,
100
+ 'Content-Type': 'application/json',
101
+ },
102
+ body: JSON.stringify(body),
103
+ });
104
+ if (!res.ok) {
105
+ const errText = await res.text().catch(() => '');
106
+ throw new Error(`ЮKassa API вернула HTTP ${res.status}: ${errText.slice(0, 240)}`);
107
+ }
108
+ const payment = await res.json();
109
+ const paymentId = payment.id;
110
+ const confirmationUrl = payment.confirmation?.confirmation_url || '';
111
+ this.store.updateOrder(order.orderId, {
112
+ paymentId,
113
+ confirmationUrl,
114
+ yookassaMode: 'live',
115
+ });
116
+ return {
117
+ orderId: order.orderId,
118
+ licenseId: order.licenseId,
119
+ amountRub: order.amountRub,
120
+ paymentId,
121
+ confirmationUrl,
122
+ mode: 'live',
123
+ };
124
+ }
125
+
126
+ // Песочница ЮKassa (для локального запуска и демонстрации без боевых ключей)
127
+ const paymentId = 'yk_sandbox_' + crypto.randomBytes(8).toString('hex');
128
+ const confirmationUrl = `${baseOrigin}/pay/sandbox/${encodeURIComponent(order.orderId)}`;
129
+ this.store.updateOrder(order.orderId, {
130
+ paymentId,
131
+ confirmationUrl,
132
+ yookassaMode: 'sandbox',
133
+ });
134
+ return {
135
+ orderId: order.orderId,
136
+ licenseId: order.licenseId,
137
+ amountRub: order.amountRub,
138
+ paymentId,
139
+ confirmationUrl,
140
+ mode: 'sandbox',
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Обработать входящий HTTP Webhook от ЮKassa (/api/payments/yookassa/webhook).
146
+ */
147
+ async handleWebhook(notification = {}) {
148
+ const event = String(notification.event || '');
149
+ const obj = notification.object || {};
150
+ const paymentId = String(obj.id || '');
151
+ const orderId = String(obj.metadata?.orderId || '');
152
+
153
+ let order = orderId ? this.store.getOrder(orderId) : null;
154
+ if (!order && paymentId)
155
+ order = this.store.findOrderByPaymentId(paymentId);
156
+
157
+ if (!order) {
158
+ return { ok: false, reason: 'order_not_found', event, orderId, paymentId };
159
+ }
160
+
161
+ if (event === 'payment.succeeded' || obj.status === 'succeeded') {
162
+ const result = this.store.completePaidOrder(order.orderId, { paymentId });
163
+ if (!result.alreadyProcessed && typeof this.onOrderPaid === 'function') {
164
+ await Promise.resolve(this.onOrderPaid(result.order, result.license)).catch(() => {});
165
+ }
166
+ return {
167
+ ok: true,
168
+ status: 'paid',
169
+ orderId: result.order.orderId,
170
+ licenseId: result.license.licenseId,
171
+ totalSeats: result.license.totalSeats,
172
+ tier: result.license.support.tierName,
173
+ alreadyProcessed: result.alreadyProcessed,
174
+ };
175
+ }
176
+
177
+ if (event === 'payment.canceled' || obj.status === 'canceled') {
178
+ this.store.updateOrder(order.orderId, { status: 'canceled' });
179
+ return { ok: true, status: 'canceled', orderId: order.orderId };
180
+ }
181
+
182
+ return { ok: true, status: obj.status || 'ignored', orderId: order.orderId };
183
+ }
184
+ }