@ghemrim/slickpay-bridge-studio 0.0.0-stage → 1.1.2

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,826 @@
1
+ /**
2
+ * SlickPay Gateway Core SDK (Node.js / Universal Fetch)
3
+ * Gère la création de factures SlickPay API v2, la vérification de statut,
4
+ * le verrouillage des prix (catalogue serveur ou signature HMAC-SHA256)
5
+ * et l'authentification cryptographique des webhooks.
6
+ */
7
+
8
+ import crypto from 'node:crypto';
9
+
10
+ export const SLICKPAY_ENDPOINTS = {
11
+ sandbox: 'https://devapi.slick-pay.com/api/v2',
12
+ production: 'https://prodapi.slick-pay.com/api/v2',
13
+ };
14
+
15
+ export const WILAYAS_58 = [
16
+ { code: '01', name: 'Adrar' },
17
+ { code: '02', name: 'Chlef' },
18
+ { code: '03', name: 'Laghouat' },
19
+ { code: '04', name: 'Oum El Bouaghi' },
20
+ { code: '05', name: 'Batna' },
21
+ { code: '06', name: 'Béjaïa' },
22
+ { code: '07', name: 'Biskra' },
23
+ { code: '08', name: 'Béchar' },
24
+ { code: '09', name: 'Blida' },
25
+ { code: '10', name: 'Bouira' },
26
+ { code: '11', name: 'Tamanrasset' },
27
+ { code: '12', name: 'Tébessa' },
28
+ { code: '13', name: 'Tlemcen' },
29
+ { code: '14', name: 'Tiaret' },
30
+ { code: '15', name: 'Tizi Ouzou' },
31
+ { code: '16', name: 'Alger' },
32
+ { code: '17', name: 'Djelfa' },
33
+ { code: '18', name: 'Jijel' },
34
+ { code: '19', name: 'Sétif' },
35
+ { code: '20', name: 'Saïda' },
36
+ { code: '21', name: 'Skikda' },
37
+ { code: '22', name: 'Sidi Bel Abbès' },
38
+ { code: '23', name: 'Annaba' },
39
+ { code: '24', name: 'Guelma' },
40
+ { code: '25', name: 'Constantine' },
41
+ { code: '26', name: 'Médéa' },
42
+ { code: '27', name: 'Mostaganem' },
43
+ { code: '28', name: "M'Sila" },
44
+ { code: '29', name: 'Mascara' },
45
+ { code: '30', name: 'Ouargla' },
46
+ { code: '31', name: 'Oran' },
47
+ { code: '32', name: 'El Bayadh' },
48
+ { code: '33', name: 'Illizi' },
49
+ { code: '34', name: 'Bordj Bou Arréridj' },
50
+ { code: '35', name: 'Boumerdès' },
51
+ { code: '36', name: 'El Tarf' },
52
+ { code: '37', name: 'Tindouf' },
53
+ { code: '38', name: 'Tissemsilt' },
54
+ { code: '39', name: 'El Oued' },
55
+ { code: '40', name: 'Khenchela' },
56
+ { code: '41', name: 'Souk Ahras' },
57
+ { code: '42', name: 'Tipaza' },
58
+ { code: '43', name: 'Mila' },
59
+ { code: '44', name: 'Aïn Defla' },
60
+ { code: '45', name: 'Naâma' },
61
+ { code: '46', name: 'Aïn Témouchent' },
62
+ { code: '47', name: 'Ghardaïa' },
63
+ { code: '48', name: 'Relizane' },
64
+ { code: '49', 'name': 'Timimoun' },
65
+ { code: '50', name: 'Bordj Badji Mokhtar' },
66
+ { code: '51', name: 'Ouled Djellal' },
67
+ { code: '52', name: 'Béni Abbès' },
68
+ { code: '53', name: 'In Salah' },
69
+ { code: '54', name: 'In Guezzam' },
70
+ { code: '55', name: 'Touggourt' },
71
+ { code: '56', name: 'Djanet' },
72
+ { code: '57', name: "El M'Ghair" },
73
+ { code: '58', name: 'El Meniaa' },
74
+ ];
75
+
76
+ const VALID_WILAYA_CODES = new Set(WILAYAS_58.map((w) => w.code));
77
+ const CUSTOM_FIELD_KEY_REGEX = /^[a-z0-9_]{1,32}$/i;
78
+
79
+ export class SlickPayGateway {
80
+ /**
81
+ * @param {Object} config
82
+ * @param {string} [config.publicKey] - Clé publique SlickPay (Bearer Token)
83
+ * @param {'sandbox'|'production'|'mock'} [config.mode='mock'] - Mode d'exécution
84
+ * @param {'users'|'merchants'} [config.accountType='users'] - Route API v2
85
+ * @param {string} [config.defaultReturnUrl] - URL de retour après paiement SATIM
86
+ * @param {string[]} [config.allowedReturnHosts] - Domaines autorisés pour returnUrl
87
+ * @param {string} [config.webhookUrl] - URL serveur de notification Webhook (SLICKPAY_WEBHOOK_URL)
88
+ * @param {string} [config.contactUuid] - UUID contact serveur (SLICKPAY_CONTACT_UUID)
89
+ * @param {string} [config.accountUuid] - UUID compte de réception serveur (SLICKPAY_ACCOUNT_UUID)
90
+ * @param {boolean} [config.qrcode] - Activer le QR code mobile SlickPay côté serveur (SLICKPAY_QRCODE)
91
+ * @param {string} [config.webhookSecret] - Secret HMAC pour signer les webhooks et les prix
92
+ * @param {boolean} [config.allowClientConfigOverride=false] - Autoriser le navigateur à surcharger mode/publicKey (Studio de démo uniquement)
93
+ * @param {boolean} [config.requirePriceSignature] - Exiger un productId du catalogue ou une signature HMAC du prix (true par défaut en production)
94
+ * @param {Object<string,{name:string,unitPrice:number,deliveryFee?:number}>} [config.catalog] - Catalogue de prix côté serveur
95
+ * @param {typeof fetch} [config.fetchImpl] - Implémentation fetch injectable pour les tests
96
+ * @param {number} [config.timeoutMs=15000] - Timeout réseau en ms
97
+ * @param {number} [config.maxStoreSize=1000] - Taille maximale du cache mémoire des sessions
98
+ */
99
+ constructor(config = {}) {
100
+ this.publicKey = config.publicKey || process.env.SLICKPAY_PUBLIC_KEY || '';
101
+ this.mode = config.mode || process.env.SLICKPAY_MODE || (this.publicKey ? 'sandbox' : 'mock');
102
+ this.accountType = config.accountType || process.env.SLICKPAY_ACCOUNT_TYPE || 'users';
103
+ this.defaultReturnUrl =
104
+ config.defaultReturnUrl ||
105
+ process.env.SLICKPAY_RETURN_URL ||
106
+ 'http://localhost:3400/payment-return';
107
+ this.allowedReturnHosts = Array.isArray(config.allowedReturnHosts)
108
+ ? config.allowedReturnHosts
109
+ : (process.env.SLICKPAY_ALLOWED_RETURN_HOSTS || 'localhost,127.0.0.1')
110
+ .split(',')
111
+ .map((h) => h.trim().toLowerCase())
112
+ .filter(Boolean);
113
+
114
+ // Paramètres métier sensibles pilotés exclusivement par le serveur
115
+ this.webhookUrl = config.webhookUrl || process.env.SLICKPAY_WEBHOOK_URL || '';
116
+ this.contactUuid = config.contactUuid || process.env.SLICKPAY_CONTACT_UUID || '';
117
+ this.accountUuid = config.accountUuid || process.env.SLICKPAY_ACCOUNT_UUID || '';
118
+ this.qrcode =
119
+ config.qrcode !== undefined
120
+ ? Boolean(config.qrcode)
121
+ : process.env.SLICKPAY_QRCODE === 'true';
122
+
123
+ this.webhookSecret = config.webhookSecret || process.env.SLICKPAY_WEBHOOK_SECRET || '';
124
+ if (this.mode === 'production' && !this.webhookSecret) {
125
+ throw new Error(
126
+ 'SLICKPAY_WEBHOOK_SECRET est obligatoire lorsque SLICKPAY_MODE=production.'
127
+ );
128
+ }
129
+ if (!this.webhookSecret) {
130
+ this.webhookSecret = 'slickpay-dev-only-secret-do-not-use-in-prod';
131
+ }
132
+
133
+ if (this.mode === 'production') {
134
+ this.validateReturnUrl(this.defaultReturnUrl);
135
+ if (this.webhookUrl && !this.webhookUrl.startsWith('https://')) {
136
+ throw new Error('En production, SLICKPAY_WEBHOOK_URL doit utiliser https://.');
137
+ }
138
+ }
139
+
140
+ this.allowClientConfigOverride =
141
+ config.allowClientConfigOverride !== undefined
142
+ ? Boolean(config.allowClientConfigOverride)
143
+ : process.env.SLICKPAY_ALLOW_CLIENT_OVERRIDE === 'true';
144
+
145
+ // Verrouillage des prix actif par défaut en production (ou si SLICKPAY_REQUIRE_PRICE_SIGNATURE !== 'false' en prod)
146
+ if (config.requirePriceSignature !== undefined) {
147
+ this.requirePriceSignature = Boolean(config.requirePriceSignature);
148
+ } else if (process.env.SLICKPAY_REQUIRE_PRICE_SIGNATURE !== undefined) {
149
+ this.requirePriceSignature = process.env.SLICKPAY_REQUIRE_PRICE_SIGNATURE === 'true';
150
+ } else {
151
+ this.requirePriceSignature = this.mode === 'production';
152
+ }
153
+
154
+ this.catalog = config.catalog || {};
155
+ this.fetchImpl = config.fetchImpl || globalThis.fetch;
156
+ this.timeoutMs = Number(config.timeoutMs || 15000);
157
+ this.maxStoreSize = Number(config.maxStoreSize || 1000);
158
+ this.invoicesStore = new Map();
159
+ this.localRefIndex = new Map();
160
+ }
161
+
162
+ get baseUrl() {
163
+ return this.mode === 'production'
164
+ ? SLICKPAY_ENDPOINTS.production
165
+ : SLICKPAY_ENDPOINTS.sandbox;
166
+ }
167
+
168
+ getBaseUrlForMode(effectiveMode) {
169
+ return effectiveMode === 'production'
170
+ ? SLICKPAY_ENDPOINTS.production
171
+ : SLICKPAY_ENDPOINTS.sandbox;
172
+ }
173
+
174
+ getInvoiceEndpoint(overrideAccountType) {
175
+ const type = overrideAccountType || this.accountType;
176
+ return type === 'merchants' ? 'merchants/invoices' : 'users/invoices';
177
+ }
178
+
179
+ /**
180
+ * Génère une signature HMAC-SHA256 pour verrouiller un produit et son prix côté marchand
181
+ */
182
+ signProductPrice(productName, unitPrice, deliveryFee = 0) {
183
+ const normalizedPrice = Math.round(Number(unitPrice) * 100) / 100;
184
+ const normalizedFee = Math.round(Number(deliveryFee) * 100) / 100;
185
+ const canonical = `price:${String(productName).trim()}:${normalizedPrice.toFixed(2)}:${normalizedFee.toFixed(2)}`;
186
+ return crypto
187
+ .createHmac('sha256', this.webhookSecret)
188
+ .update(canonical)
189
+ .digest('hex');
190
+ }
191
+
192
+ /**
193
+ * Génère et vérifie la signature HMAC canonique d'un événement Webhook
194
+ */
195
+ computeWebhookSignature(invoiceRef, totalChargeCentimes, status = 'paid') {
196
+ const canonical = `webhook:${String(invoiceRef)}:${Number(totalChargeCentimes)}:${String(status)}`;
197
+ return crypto
198
+ .createHmac('sha256', this.webhookSecret)
199
+ .update(canonical)
200
+ .digest('hex');
201
+ }
202
+
203
+ verifyWebhookSignature(invoiceRef, totalChargeCentimes, providedSignature, status = 'paid') {
204
+ if (!providedSignature || typeof providedSignature !== 'string') {
205
+ return false;
206
+ }
207
+ const expected = this.computeWebhookSignature(invoiceRef, totalChargeCentimes, status);
208
+ const expectedBuf = Buffer.from(expected, 'utf8');
209
+ const providedBuf = Buffer.from(providedSignature, 'utf8');
210
+ if (expectedBuf.length !== providedBuf.length) {
211
+ return false;
212
+ }
213
+ return crypto.timingSafeEqual(expectedBuf, providedBuf);
214
+ }
215
+
216
+ /**
217
+ * Enregistre la facture sous son ID distant ET sous sa référence locale (localInvoiceRef)
218
+ * afin que la vérification HMAC du webhook fonctionne de manière cohérente en Mock, Sandbox et Production.
219
+ */
220
+ storeInvoiceRecord(invoiceId, record) {
221
+ const key = String(invoiceId);
222
+ if (this.invoicesStore.size >= this.maxStoreSize && !this.invoicesStore.has(key)) {
223
+ const oldestKey = this.invoicesStore.keys().next().value;
224
+ if (oldestKey !== undefined) {
225
+ const oldRec = this.invoicesStore.get(oldestKey);
226
+ if (oldRec && oldRec.localInvoiceRef) {
227
+ this.localRefIndex.delete(oldRec.localInvoiceRef);
228
+ }
229
+ this.invoicesStore.delete(oldestKey);
230
+ }
231
+ }
232
+ this.invoicesStore.set(key, record);
233
+ if (record.localInvoiceRef) {
234
+ this.localRefIndex.set(String(record.localInvoiceRef), key);
235
+ }
236
+ }
237
+
238
+ resolveLocalRecord(idOrRef) {
239
+ const key = String(idOrRef);
240
+ if (this.invoicesStore.has(key)) {
241
+ return this.invoicesStore.get(key);
242
+ }
243
+ const mappedId = this.localRefIndex.get(key);
244
+ if (mappedId && this.invoicesStore.has(mappedId)) {
245
+ return this.invoicesStore.get(mappedId);
246
+ }
247
+ return null;
248
+ }
249
+
250
+ validateReturnUrl(candidateUrl) {
251
+ if (!candidateUrl) return this.defaultReturnUrl;
252
+ let parsed;
253
+ try {
254
+ parsed = new URL(String(candidateUrl));
255
+ } catch (_) {
256
+ const err = new Error('URL de retour (returnUrl) invalide.');
257
+ err.statusCode = 400;
258
+ throw err;
259
+ }
260
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
261
+ const err = new Error('Le protocole de returnUrl doit être https: ou http:.');
262
+ err.statusCode = 400;
263
+ throw err;
264
+ }
265
+ if (this.mode === 'production' && parsed.protocol !== 'https:') {
266
+ const err = new Error('En production, returnUrl doit obligatoirement utiliser https:.');
267
+ err.statusCode = 400;
268
+ throw err;
269
+ }
270
+ const host = parsed.hostname.toLowerCase();
271
+ const isAllowed = this.allowedReturnHosts.some(
272
+ (allowed) => host === allowed || host.endsWith(`.${allowed}`)
273
+ );
274
+ if (!isAllowed) {
275
+ const err = new Error(`Domaine returnUrl non autorisé : ${host}`);
276
+ err.statusCode = 400;
277
+ throw err;
278
+ }
279
+ return parsed.toString();
280
+ }
281
+
282
+ validateCheckoutUrl(urlStr) {
283
+ try {
284
+ const u = new URL(String(urlStr));
285
+ if (u.protocol !== 'https:') {
286
+ throw new Error('Protocole non HTTPS');
287
+ }
288
+ return u.toString();
289
+ } catch (_) {
290
+ const err = new Error('URL de paiement distante invalide ou non sécurisée.');
291
+ err.statusCode = 502;
292
+ throw err;
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Valide et normalise la charge utile d'une commande provenant du widget frontend
298
+ */
299
+ validateCheckoutPayload(payload = {}) {
300
+ const errors = [];
301
+
302
+ let productName = String(payload.productName || 'Commande Marchand').trim().slice(0, 180);
303
+ let unitPrice = Number(payload.amount ?? payload.unitPrice ?? NaN);
304
+ let deliveryFee = Number(payload.deliveryFee ?? 0);
305
+
306
+ if (payload.productId && this.catalog[payload.productId]) {
307
+ const item = this.catalog[payload.productId];
308
+ productName = item.name;
309
+ unitPrice = Number(item.unitPrice);
310
+ if (item.deliveryFee !== undefined) {
311
+ deliveryFee = Number(item.deliveryFee);
312
+ }
313
+ } else if (this.requirePriceSignature || payload.priceSignature) {
314
+ const expectedSig = this.signProductPrice(productName, unitPrice, deliveryFee);
315
+ const providedSig = String(payload.priceSignature || '');
316
+ const expBuf = Buffer.from(expectedSig, 'utf8');
317
+ const provBuf = Buffer.from(providedSig, 'utf8');
318
+ if (expBuf.length !== provBuf.length || !crypto.timingSafeEqual(expBuf, provBuf)) {
319
+ errors.push('Signature de prix (priceSignature) invalide ou absente.');
320
+ }
321
+ }
322
+
323
+ unitPrice = Math.round(unitPrice * 100) / 100;
324
+ deliveryFee = Math.round(Math.max(0, deliveryFee || 0) * 100) / 100;
325
+ const quantity = parseInt(payload.quantity ?? 1, 10);
326
+
327
+ if (!Number.isFinite(unitPrice) || unitPrice < 100 || unitPrice > 50_000_000) {
328
+ errors.push('Le montant unitaire doit être compris entre 100 DZD et 50 000 000 DZD.');
329
+ }
330
+ if (!Number.isInteger(quantity) || quantity < 1 || quantity > 1000) {
331
+ errors.push('La quantité doit être un entier compris entre 1 et 1000.');
332
+ }
333
+ if (!Number.isFinite(deliveryFee) || deliveryFee < 0 || deliveryFee > 1_000_000) {
334
+ errors.push('Les frais de livraison sont invalides.');
335
+ }
336
+
337
+ const fullName = String(payload.fullName || '').trim();
338
+ if (!fullName || fullName.length < 2 || fullName.length > 120) {
339
+ errors.push('Le nom complet du client est obligatoire.');
340
+ }
341
+
342
+ const email = String(payload.email || '').trim();
343
+ if (!email || email.length > 160 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
344
+ errors.push('Une adresse e-mail valide est obligatoire.');
345
+ }
346
+
347
+ const cleanPhone = String(payload.phone || '')
348
+ .trim()
349
+ .replace(/[\s\-\.\(\)]+/g, '');
350
+ if (!/^(\+?213|00213|0)[2-7][0-9]{7,8}$/.test(cleanPhone)) {
351
+ errors.push('Un numéro de téléphone algérien valide est obligatoire (ex: 0550123456).');
352
+ }
353
+
354
+ const wilaya = String(payload.wilaya || '16').padStart(2, '0');
355
+ if (!VALID_WILAYA_CODES.has(wilaya)) {
356
+ errors.push(`Code wilaya invalide : ${wilaya} (doit être entre 01 et 58).`);
357
+ }
358
+
359
+ const address = String(payload.address || 'Algérie').trim().slice(0, 300);
360
+
361
+ // Champs personnalisés B2B : validation stricte du format de clé et de la valeur scalaire
362
+ const customFields = {};
363
+ if (payload.customFields !== undefined && payload.customFields !== null) {
364
+ if (typeof payload.customFields !== 'object' || Array.isArray(payload.customFields)) {
365
+ errors.push('Le paramètre customFields doit être un objet clé-valeur.');
366
+ } else {
367
+ const entries = Object.entries(payload.customFields);
368
+ if (entries.length > 10) {
369
+ errors.push('Maximum 10 champs personnalisés autorisés.');
370
+ }
371
+ for (const [rawKey, rawVal] of entries) {
372
+ const key = String(rawKey).trim().toLowerCase();
373
+ if (!CUSTOM_FIELD_KEY_REGEX.test(key)) {
374
+ errors.push(`Nom de champ personnalisé invalide : ${rawKey} (caractères alphanumériques uniquement).`);
375
+ continue;
376
+ }
377
+ if (rawVal === null || rawVal === undefined || rawVal === '') continue;
378
+ if (typeof rawVal === 'object') {
379
+ errors.push(`Le champ personnalisé ${key} doit être une chaîne ou un nombre.`);
380
+ continue;
381
+ }
382
+ customFields[key] = String(rawVal).trim().slice(0, 120);
383
+ }
384
+ }
385
+ }
386
+
387
+ if (errors.length > 0) {
388
+ const err = new Error(errors.join(' '));
389
+ err.statusCode = 400;
390
+ err.validationErrors = errors;
391
+ throw err;
392
+ }
393
+
394
+ const returnUrl = this.validateReturnUrl(
395
+ this.allowClientConfigOverride ? payload.returnUrl : undefined
396
+ );
397
+
398
+ const baseAmountDzd = Math.round((unitPrice * quantity + deliveryFee) * 100) / 100;
399
+ const customerFeeDzd = 0;
400
+ const totalChargeDzd = baseAmountDzd;
401
+
402
+ const nameParts = fullName.split(/\s+/);
403
+ const firstname = nameParts[0] || 'Client';
404
+ const lastname = nameParts.slice(1).join(' ').trim() || firstname;
405
+
406
+ return {
407
+ productName,
408
+ unitPrice,
409
+ quantity,
410
+ deliveryFee,
411
+ fullName,
412
+ firstname,
413
+ lastname,
414
+ email,
415
+ phone: cleanPhone,
416
+ wilaya,
417
+ address,
418
+ customFields,
419
+ returnUrl,
420
+ shopSlug: payload.shopSlug || null,
421
+ totals: {
422
+ baseDzd: baseAmountDzd,
423
+ customerFeeDzd,
424
+ totalChargeDzd,
425
+ base: Math.round(baseAmountDzd * 100),
426
+ customerFee: Math.round(customerFeeDzd * 100),
427
+ totalCharge: Math.round(totalChargeDzd * 100),
428
+ },
429
+ };
430
+ }
431
+
432
+ /**
433
+ * Crée une session de paiement / facture SlickPay et retourne l'URL SATIM/CIB
434
+ */
435
+ async createCheckoutSession(rawPayload = {}) {
436
+ const clean = this.validateCheckoutPayload(rawPayload);
437
+ const localInvoiceRef = `sp_${crypto.randomBytes(8).toString('hex')}`;
438
+ const mdOrder = crypto.randomBytes(10).toString('base64url').slice(0, 20);
439
+
440
+ const effectiveMode =
441
+ this.allowClientConfigOverride && rawPayload.mode
442
+ ? rawPayload.mode
443
+ : this.mode;
444
+ const effectivePublicKey =
445
+ this.allowClientConfigOverride && rawPayload.publicKey
446
+ ? String(rawPayload.publicKey).trim()
447
+ : this.publicKey;
448
+ const effectiveAccountType =
449
+ this.allowClientConfigOverride && rawPayload.accountType
450
+ ? rawPayload.accountType
451
+ : this.accountType;
452
+
453
+ // La signature HMAC de webhook est toujours indexée sur localInvoiceRef
454
+ // (et stockée dans l'enregistrement pour une vérification cohérente quel que soit l'ID distant retourné par SlickPay)
455
+ const webhookSignature = this.computeWebhookSignature(
456
+ localInvoiceRef,
457
+ clean.totals.totalCharge,
458
+ 'paid'
459
+ );
460
+
461
+ if (effectiveMode === 'mock' || !effectivePublicKey) {
462
+ const satimPaymentUrl = `https://cib.satim.dz/payment/epg/merchants/merchantsatim/payment.html?mdOrder=${mdOrder}&language=fr`;
463
+ const record = {
464
+ ok: true,
465
+ mode: 'mock',
466
+ accountType: effectiveAccountType,
467
+ invoiceId: localInvoiceRef,
468
+ localInvoiceRef,
469
+ mdOrder,
470
+ status: 'pending',
471
+ createdAt: new Date().toISOString(),
472
+ expiresAt: new Date(Date.now() + 25 * 60 * 1000).toISOString(),
473
+ paymentUrl: satimPaymentUrl,
474
+ totals: clean.totals,
475
+ customer: {
476
+ fullName: clean.fullName,
477
+ email: clean.email,
478
+ phone: clean.phone,
479
+ wilaya: clean.wilaya,
480
+ address: clean.address,
481
+ customFields: clean.customFields,
482
+ },
483
+ item: {
484
+ name: clean.productName,
485
+ unitPrice: clean.unitPrice,
486
+ quantity: clean.quantity,
487
+ deliveryFee: clean.deliveryFee,
488
+ },
489
+ };
490
+ this.storeInvoiceRecord(localInvoiceRef, record);
491
+ return record;
492
+ }
493
+
494
+ const headers = {
495
+ Accept: 'application/json',
496
+ 'Content-Type': 'application/json',
497
+ Authorization: `Bearer ${effectivePublicKey}`,
498
+ 'User-Agent': 'SlickPayBridgeSDK/1.1 (+https://slick-pay.com)',
499
+ };
500
+
501
+ const items = [
502
+ {
503
+ name: clean.productName,
504
+ price: clean.unitPrice,
505
+ quantity: clean.quantity,
506
+ },
507
+ ];
508
+ if (clean.deliveryFee > 0) {
509
+ items.push({
510
+ name: 'Frais de livraison',
511
+ price: clean.deliveryFee,
512
+ quantity: 1,
513
+ });
514
+ }
515
+
516
+ // webhookUrl, contactUuid, accountUuid et qrcode proviennent exclusivement de la configuration serveur
517
+ const invoicePayload = {
518
+ amount: clean.totals.totalChargeDzd,
519
+ url: clean.returnUrl,
520
+ ...(this.contactUuid ? { contact: this.contactUuid } : {}),
521
+ ...(this.accountUuid ? { account: this.accountUuid } : {}),
522
+ ...(this.qrcode ? { qrcode: true } : {}),
523
+ name: `${clean.firstname} ${clean.lastname}`,
524
+ firstname: clean.firstname,
525
+ lastname: clean.lastname,
526
+ email: clean.email,
527
+ phone: clean.phone,
528
+ address: `${clean.address} (Wilaya ${clean.wilaya})`,
529
+ items,
530
+ note: Object.entries(clean.customFields)
531
+ .map(([k, v]) => `${k.toUpperCase()}: ${v}`)
532
+ .join(' | '),
533
+ ...(this.webhookUrl ? { webhook_url: this.webhookUrl } : {}),
534
+ webhook_signature: webhookSignature,
535
+ webhook_meta_data: [
536
+ {
537
+ invoice_ref: localInvoiceRef,
538
+ wilaya: clean.wilaya,
539
+ ...clean.customFields,
540
+ },
541
+ ],
542
+ };
543
+
544
+ const endpointPath = this.getInvoiceEndpoint(effectiveAccountType);
545
+ const targetUrl = `${this.getBaseUrlForMode(effectiveMode)}/${endpointPath}`;
546
+
547
+ const response = await this.fetchImpl(targetUrl, {
548
+ method: 'POST',
549
+ headers,
550
+ body: JSON.stringify(invoicePayload),
551
+ signal: AbortSignal.timeout(this.timeoutMs),
552
+ });
553
+
554
+ const data = await response.json().catch(() => ({}));
555
+ if (!response.ok || data.errors) {
556
+ const err = new Error(
557
+ data?.message || `Erreur API SlickPay (${response.status})`
558
+ );
559
+ err.statusCode = response.status || 502;
560
+ throw err;
561
+ }
562
+
563
+ const remoteId = String(data?.id || data?.data?.id || localInvoiceRef);
564
+ const rawPaymentUrl =
565
+ data?.url ||
566
+ data?.data?.url ||
567
+ `https://cib.satim.dz/payment/epg/merchants/merchantsatim/payment.html?mdOrder=${mdOrder}&language=fr`;
568
+ const paymentUrl = this.validateCheckoutUrl(rawPaymentUrl);
569
+
570
+ const record = {
571
+ ok: true,
572
+ mode: effectiveMode,
573
+ accountType: effectiveAccountType,
574
+ invoiceId: remoteId,
575
+ localInvoiceRef,
576
+ mdOrder,
577
+ status: 'pending',
578
+ createdAt: new Date().toISOString(),
579
+ expiresAt: new Date(Date.now() + 25 * 60 * 1000).toISOString(),
580
+ paymentUrl,
581
+ totals: clean.totals,
582
+ customer: {
583
+ fullName: clean.fullName,
584
+ email: clean.email,
585
+ phone: clean.phone,
586
+ wilaya: clean.wilaya,
587
+ address: clean.address,
588
+ customFields: clean.customFields,
589
+ },
590
+ item: {
591
+ name: clean.productName,
592
+ unitPrice: clean.unitPrice,
593
+ quantity: clean.quantity,
594
+ deliveryFee: clean.deliveryFee,
595
+ },
596
+ };
597
+
598
+ this.storeInvoiceRecord(remoteId, record);
599
+ return record;
600
+ }
601
+
602
+ /**
603
+ * Vérifie le statut d'une facture sans jamais exposer les données personnelles (PII)
604
+ */
605
+ async getInvoiceStatus(invoiceId, accountTypeOverride) {
606
+ const localRecord = this.resolveLocalRecord(invoiceId);
607
+
608
+ if (this.mode === 'mock' || !this.publicKey) {
609
+ if (!localRecord) {
610
+ const err = new Error(`Facture introuvable : ${invoiceId}`);
611
+ err.statusCode = 404;
612
+ throw err;
613
+ }
614
+ return {
615
+ invoiceId: localRecord.invoiceId,
616
+ mdOrder: localRecord.mdOrder,
617
+ status: localRecord.status,
618
+ paidAt: localRecord.paidAt || null,
619
+ totals: localRecord.totals,
620
+ item: localRecord.item,
621
+ };
622
+ }
623
+
624
+ const targetId = localRecord ? localRecord.invoiceId : String(invoiceId);
625
+ const endpointPath = this.getInvoiceEndpoint(accountTypeOverride);
626
+ const response = await this.fetchImpl(
627
+ `${this.baseUrl}/${endpointPath}/${encodeURIComponent(targetId)}`,
628
+ {
629
+ method: 'GET',
630
+ headers: {
631
+ Accept: 'application/json',
632
+ Authorization: `Bearer ${this.publicKey}`,
633
+ 'User-Agent': 'SlickPayBridgeSDK/1.1 (+https://slick-pay.com)',
634
+ },
635
+ signal: AbortSignal.timeout(this.timeoutMs),
636
+ }
637
+ );
638
+
639
+ const data = await response.json().catch(() => ({}));
640
+ if (!response.ok) {
641
+ const err = new Error(
642
+ data?.message || `Impossible de vérifier la facture ${targetId} (${response.status})`
643
+ );
644
+ err.statusCode = response.status || 502;
645
+ throw err;
646
+ }
647
+
648
+ const completed = Boolean(
649
+ data?.completed === 1 ||
650
+ data?.completed === true ||
651
+ data?.data?.completed === 1 ||
652
+ data?.data?.payment_status === 'paid' ||
653
+ data?.status === 'paid'
654
+ );
655
+
656
+ if (localRecord) {
657
+ localRecord.status = completed ? 'paid' : 'pending';
658
+ this.storeInvoiceRecord(localRecord.invoiceId, localRecord);
659
+ }
660
+
661
+ return {
662
+ invoiceId: targetId,
663
+ status: completed ? 'paid' : 'pending',
664
+ totals: localRecord ? localRecord.totals : undefined,
665
+ item: localRecord ? localRecord.item : undefined,
666
+ };
667
+ }
668
+
669
+ /**
670
+ * Calcule la commission SlickPay (`POST /api/v2/users/invoices/commission`)
671
+ */
672
+ async calculateInvoiceCommission(amountDzd) {
673
+ const amount = Number(amountDzd);
674
+ if (!Number.isFinite(amount) || amount < 100) {
675
+ const err = new Error('Le montant doit être >= 100 DZD');
676
+ err.statusCode = 400;
677
+ throw err;
678
+ }
679
+
680
+ if (this.mode === 'mock' || !this.publicKey) {
681
+ return {
682
+ success: 1,
683
+ mode: 'mock',
684
+ amount,
685
+ commission: 0,
686
+ total: amount,
687
+ };
688
+ }
689
+
690
+ const response = await this.fetchImpl(`${this.baseUrl}/users/invoices/commission`, {
691
+ method: 'POST',
692
+ headers: {
693
+ Accept: 'application/json',
694
+ 'Content-Type': 'application/json',
695
+ Authorization: `Bearer ${this.publicKey}`,
696
+ 'User-Agent': 'SlickPayBridgeSDK/1.1 (+https://slick-pay.com)',
697
+ },
698
+ body: JSON.stringify({ amount }),
699
+ signal: AbortSignal.timeout(this.timeoutMs),
700
+ });
701
+
702
+ const data = await response.json().catch(() => ({}));
703
+ if (!response.ok) {
704
+ const err = new Error(data?.message || `Erreur calcul commission (${response.status})`);
705
+ err.statusCode = response.status;
706
+ throw err;
707
+ }
708
+ return data;
709
+ }
710
+
711
+ async createShopLinkSession(shopSlug, rawPayload, locale = 'fr') {
712
+ const shopUrl = `https://app.slick-pay.com/${encodeURIComponent(locale)}/shop/${encodeURIComponent(shopSlug)}`;
713
+ const session = await this.createCheckoutSession({ ...rawPayload, shopSlug });
714
+ return {
715
+ ...session,
716
+ bridge: 'shop-link',
717
+ shopUrl,
718
+ };
719
+ }
720
+
721
+ /**
722
+ * Confirme le paiement d'une facture après vérification obligatoire de la signature HMAC du webhook.
723
+ * Accepte une signature calculée soit sur localInvoiceRef (envoyée à SlickPay lors de la création)
724
+ * soit sur invoiceId (ID distant).
725
+ */
726
+ markInvoicePaid(invoiceIdOrRef, providedSignature) {
727
+ const localRecord = this.resolveLocalRecord(invoiceIdOrRef);
728
+ if (!localRecord) {
729
+ const err = new Error(`Facture introuvable : ${invoiceIdOrRef}`);
730
+ err.statusCode = 404;
731
+ throw err;
732
+ }
733
+
734
+ const validByLocalRef =
735
+ localRecord.localInvoiceRef &&
736
+ this.verifyWebhookSignature(
737
+ localRecord.localInvoiceRef,
738
+ localRecord.totals.totalCharge,
739
+ providedSignature,
740
+ 'paid'
741
+ );
742
+ const validByRemoteId = this.verifyWebhookSignature(
743
+ localRecord.invoiceId,
744
+ localRecord.totals.totalCharge,
745
+ providedSignature,
746
+ 'paid'
747
+ );
748
+
749
+ if (!validByLocalRef && !validByRemoteId) {
750
+ const err = new Error('Signature HMAC du webhook invalide ou manquante.');
751
+ err.statusCode = 401;
752
+ throw err;
753
+ }
754
+
755
+ localRecord.status = 'paid';
756
+ localRecord.paidAt = new Date().toISOString();
757
+ localRecord.webhookSignature = providedSignature;
758
+ return {
759
+ invoiceId: localRecord.invoiceId,
760
+ localInvoiceRef: localRecord.localInvoiceRef,
761
+ status: localRecord.status,
762
+ paidAt: localRecord.paidAt,
763
+ totals: localRecord.totals,
764
+ };
765
+ }
766
+ }
767
+
768
+ /**
769
+ * Classes compatibles avec la signature `@slick-pay-algeria/slickpay-npm`
770
+ */
771
+ export class Invoice {
772
+ constructor(publicKey, sandbox = false, options = {}) {
773
+ const isFn = typeof options === 'function';
774
+ const fetchImpl = isFn ? options : options.fetchImpl;
775
+ const webhookSecret = isFn ? undefined : options.webhookSecret;
776
+ const requirePriceSignature = isFn ? false : Boolean(options.requirePriceSignature);
777
+ const defaultReturnUrl = isFn
778
+ ? 'https://localhost/payment-return'
779
+ : options.defaultReturnUrl || 'https://localhost/payment-return';
780
+ this.gateway = new SlickPayGateway({
781
+ publicKey,
782
+ mode: sandbox ? 'sandbox' : 'production',
783
+ accountType: 'users',
784
+ webhookSecret,
785
+ requirePriceSignature,
786
+ defaultReturnUrl,
787
+ fetchImpl,
788
+ });
789
+ }
790
+ commission(amount) {
791
+ return this.gateway.calculateInvoiceCommission(amount);
792
+ }
793
+ store(data) {
794
+ return this.gateway.createCheckoutSession({ ...data, accountType: 'users' });
795
+ }
796
+ show(id) {
797
+ return this.gateway.getInvoiceStatus(id, 'users');
798
+ }
799
+ }
800
+
801
+ export class MerchantInvoice {
802
+ constructor(publicKey, sandbox = false, options = {}) {
803
+ const isFn = typeof options === 'function';
804
+ const fetchImpl = isFn ? options : options.fetchImpl;
805
+ const webhookSecret = isFn ? undefined : options.webhookSecret;
806
+ const requirePriceSignature = isFn ? false : Boolean(options.requirePriceSignature);
807
+ const defaultReturnUrl = isFn
808
+ ? 'https://localhost/payment-return'
809
+ : options.defaultReturnUrl || 'https://localhost/payment-return';
810
+ this.gateway = new SlickPayGateway({
811
+ publicKey,
812
+ mode: sandbox ? 'sandbox' : 'production',
813
+ accountType: 'merchants',
814
+ webhookSecret,
815
+ requirePriceSignature,
816
+ defaultReturnUrl,
817
+ fetchImpl,
818
+ });
819
+ }
820
+ store(data) {
821
+ return this.gateway.createCheckoutSession({ ...data, accountType: 'merchants' });
822
+ }
823
+ show(id) {
824
+ return this.gateway.getInvoiceStatus(id, 'merchants');
825
+ }
826
+ }