@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,910 @@
1
+ /**
2
+ * SlickPay Universal Web Component & JS SDK (slickpay-widget.js)
3
+ * Design inspiré de Stripe Checkout (épuré, multi-étapes progressives, 100% compatible CSP).
4
+ *
5
+ * Durcissement Sécurité & Accessibilité (Audit) :
6
+ * - Échappement HTML systématique (escapeHtml) sur toutes les valeurs dynamiques (prévention XSS DOM/Shadow DOM)
7
+ * - Validation stricte des URLs paymentUrl / shopUrl (sanitizeUrl : seuls https:// et http:// sont acceptés, javascript: rejeté)
8
+ * - Conservation des saisies (formValues) lors du clic sur +/- quantité
9
+ * - Montant par défaut cohérent (45000 DZD) et support de productId / priceSignature pour la vérification de prix côté serveur
10
+ * - Accessibilité : fermeture par touche Escape, piégeage du focus (Tab/Shift+Tab), aria-labelledby et role="alert"
11
+ * - Suivi de statut post-création via SlickPay.checkStatus(invoiceId) et bouton de vérification dans l'Étape 3
12
+ */
13
+
14
+ (function (global) {
15
+ 'use strict';
16
+
17
+ const currentScript =
18
+ document.currentScript ||
19
+ document.querySelector('script[src*="slickpay-widget.js"]');
20
+ const scriptBaseUrl =
21
+ currentScript && currentScript.src
22
+ ? currentScript.src.replace(/\/slickpay-widget\.js(\?.*)?$/, '')
23
+ : './sdk';
24
+ const defaultApiUrl =
25
+ currentScript && currentScript.src
26
+ ? currentScript.src.replace(/\/sdk\/slickpay-widget\.js(\?.*)?$/, '/api/checkout.php')
27
+ : './api/checkout.php';
28
+ const widgetCssUrl = `${scriptBaseUrl}/slickpay-widget.css?v=6`;
29
+
30
+ function escapeHtml(str) {
31
+ return String(str ?? '')
32
+ .replace(/&/g, '&')
33
+ .replace(/</g, '&lt;')
34
+ .replace(/>/g, '&gt;')
35
+ .replace(/"/g, '&quot;')
36
+ .replace(/'/g, '&#39;');
37
+ }
38
+
39
+ function sanitizeUrl(candidateUrl, requireHttps = true) {
40
+ if (!candidateUrl) return '';
41
+ try {
42
+ const parsed = new URL(String(candidateUrl), global.location ? global.location.href : 'https://localhost');
43
+ if (requireHttps && parsed.protocol !== 'https:') {
44
+ return '';
45
+ }
46
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
47
+ return '';
48
+ }
49
+ return parsed.toString();
50
+ } catch (_) {
51
+ return '';
52
+ }
53
+ }
54
+
55
+ const globalConfig = {
56
+ endpoint: defaultApiUrl,
57
+ mode: 'mock',
58
+ publicKey: '',
59
+ accountType: 'users',
60
+ merchantName: 'Boutique Demo DZ',
61
+ locale: 'fr',
62
+ brandColor: '#635bff',
63
+ deliveryFee: 0,
64
+ shopUrl: '',
65
+ returnUrl: '',
66
+ customFields: [],
67
+ };
68
+
69
+ function readScriptDatasetConfig() {
70
+ if (!currentScript || !currentScript.dataset) return;
71
+ const ds = currentScript.dataset;
72
+ if (ds.endpoint) globalConfig.endpoint = ds.endpoint;
73
+ if (ds.mode) globalConfig.mode = ds.mode;
74
+ if (ds.publicKey) globalConfig.publicKey = ds.publicKey;
75
+ if (ds.accountType) globalConfig.accountType = ds.accountType;
76
+ if (ds.merchantName) globalConfig.merchantName = ds.merchantName;
77
+ if (ds.locale) globalConfig.locale = ds.locale;
78
+ if (ds.brandColor) globalConfig.brandColor = ds.brandColor;
79
+ if (ds.deliveryFee) globalConfig.deliveryFee = Number(ds.deliveryFee) || 0;
80
+ if (ds.shopUrl) globalConfig.shopUrl = ds.shopUrl;
81
+ if (ds.returnUrl) globalConfig.returnUrl = ds.returnUrl;
82
+ if (ds.customFields) {
83
+ try {
84
+ globalConfig.customFields = JSON.parse(ds.customFields);
85
+ } catch (_) {}
86
+ }
87
+ }
88
+ readScriptDatasetConfig();
89
+
90
+ if (
91
+ typeof document !== 'undefined' &&
92
+ !document.getElementById('slickpay-widget-global-css')
93
+ ) {
94
+ const linkEl = document.createElement('link');
95
+ linkEl.id = 'slickpay-widget-global-css';
96
+ linkEl.rel = 'stylesheet';
97
+ linkEl.href = widgetCssUrl;
98
+ document.head.appendChild(linkEl);
99
+ }
100
+
101
+ // Liste complète des 58 Wilayas d'Algérie
102
+ const WILAYAS_58 = [
103
+ ['01', 'Adrar'], ['02', 'Chlef'], ['03', 'Laghouat'], ['04', 'Oum El Bouaghi'],
104
+ ['05', 'Batna'], ['06', 'Béjaïa'], ['07', 'Biskra'], ['08', 'Béchar'],
105
+ ['09', 'Blida'], ['10', 'Bouira'], ['11', 'Tamanrasset'], ['12', 'Tébessa'],
106
+ ['13', 'Tlemcen'], ['14', 'Tiaret'], ['15', 'Tizi Ouzou'], ['16', 'Alger'],
107
+ ['17', 'Djelfa'], ['18', 'Jijel'], ['19', 'Sétif'], ['20', 'Saïda'],
108
+ ['21', 'Skikda'], ['22', 'Sidi Bel Abbès'], ['23', 'Annaba'], ['24', 'Guelma'],
109
+ ['25', 'Constantine'], ['26', 'Médéa'], ['27', 'Mostaganem'], ['28', "M'Sila"],
110
+ ['29', 'Mascara'], ['30', 'Ouargla'], ['31', 'Oran'], ['32', 'El Bayadh'],
111
+ ['33', 'Illizi'], ['34', 'Bordj Bou Arréridj'], ['35', 'Boumerdès'], ['36', 'El Tarf'],
112
+ ['37', 'Tindouf'], ['38', 'Tissemsilt'], ['39', 'El Oued'], ['40', 'Khenchela'],
113
+ ['41', 'Souk Ahras'], ['42', 'Tipaza'], ['43', 'Mila'], ['44', 'Aïn Defla'],
114
+ ['45', 'Naâma'], ['46', 'Aïn Témouchent'], ['47', 'Ghardaïa'], ['48', 'Relizane'],
115
+ ['49', 'Timimoun'], ['50', 'Bordj Badji Mokhtar'], ['51', 'Ouled Djellal'], ['52', 'Béni Abbès'],
116
+ ['53', 'In Salah'], ['54', 'In Guezzam'], ['55', 'Touggourt'], ['56', 'Djanet'],
117
+ ['57', "El M'Ghair"], ['58', 'El Meniaa'],
118
+ ];
119
+
120
+ const I18N = {
121
+ fr: {
122
+ ctaDefault: 'Payer par carte CIB / Edahabia',
123
+ step1Label: 'Coordonnées',
124
+ step2Label: 'Facturation',
125
+ step3Label: 'Paiement',
126
+ step1Title: 'Vos coordonnées de contact',
127
+ step2Title: 'Adresse & informations fiscales',
128
+ step3Title: 'Récapitulatif avant redirection SATIM',
129
+ securedBy: 'Passerelle de paiement SlickPay · SATIM',
130
+ quantity: 'Quantité',
131
+ delivery: 'Frais de livraison',
132
+ freeDelivery: 'Inclus',
133
+ wilaya: 'Wilaya',
134
+ chooseWilaya: 'Sélectionner une wilaya...',
135
+ address: 'Adresse de facturation',
136
+ fullName: 'Nom complet ou Raison sociale',
137
+ email: 'Adresse e-mail',
138
+ phone: 'Téléphone mobile',
139
+ product: 'Article',
140
+ total: 'Total',
141
+ nextBtn: 'Continuer →',
142
+ backBtn: '← Retour',
143
+ generateBtn: 'Valider & préparer le paiement',
144
+ verifyHeading: 'Commande prête pour le règlement',
145
+ paidHeading: 'Paiement confirmé',
146
+ reservedNotice: 'Lien de paiement SATIM valable pendant 25 minutes.',
147
+ payNow: 'Procéder au paiement',
148
+ checkStatusBtn: 'Vérifier le statut du paiement',
149
+ editOrder: '← Modifier',
150
+ openShopLink: 'Lien marchand',
151
+ processing: 'Connexion à la passerelle...',
152
+ },
153
+ en: {
154
+ ctaDefault: 'Pay with CIB / Edahabia',
155
+ step1Label: 'Contact',
156
+ step2Label: 'Billing',
157
+ step3Label: 'Pay',
158
+ step1Title: 'Contact information',
159
+ step2Title: 'Billing address & tax details',
160
+ step3Title: 'Order review before SATIM payment',
161
+ securedBy: 'Payment gateway by SlickPay · SATIM',
162
+ quantity: 'Quantity',
163
+ delivery: 'Delivery',
164
+ freeDelivery: 'Free',
165
+ wilaya: 'Wilaya (Province)',
166
+ chooseWilaya: 'Select a wilaya...',
167
+ address: 'Billing address',
168
+ fullName: 'Full name or Company',
169
+ email: 'Email address',
170
+ phone: 'Phone number',
171
+ product: 'Item',
172
+ total: 'Total',
173
+ nextBtn: 'Continue →',
174
+ backBtn: '← Back',
175
+ generateBtn: 'Confirm & prepare payment',
176
+ verifyHeading: 'Ready for payment',
177
+ paidHeading: 'Payment confirmed',
178
+ reservedNotice: 'SATIM payment session reserved for 25 minutes.',
179
+ payNow: 'Pay',
180
+ checkStatusBtn: 'Check payment status',
181
+ editOrder: '← Edit',
182
+ openShopLink: 'Merchant link',
183
+ processing: 'Connecting to gateway...',
184
+ },
185
+ ar: {
186
+ ctaDefault: 'الدفع بالبطاقة البنكية (CIB / الذهبية)',
187
+ step1Label: 'المعلومات',
188
+ step2Label: 'الفوترة',
189
+ step3Label: 'الدفع',
190
+ step1Title: 'معلومات الاتصال الخاصة بك',
191
+ step2Title: 'عنوان الفوترة والمعلومات الجبائية',
192
+ step3Title: 'مراجعة الطلب قبل الدفع عبر SATIM',
193
+ securedBy: 'بوابة الدفع عبر SlickPay · شبكة SATIM',
194
+ quantity: 'الكمية',
195
+ delivery: 'التوصيل',
196
+ freeDelivery: 'مجاني',
197
+ wilaya: 'الولاية',
198
+ chooseWilaya: 'اختر الولاية...',
199
+ address: 'عنوان الفوترة',
200
+ fullName: 'الاسم الكامل أو اسم المؤسسة',
201
+ email: 'البريد الإلكتروني',
202
+ phone: 'رقم الهاتف',
203
+ product: 'المنتج',
204
+ total: 'المجموع',
205
+ nextBtn: 'متابعة ←',
206
+ backBtn: 'رجوع →',
207
+ generateBtn: 'تأكيد وتحضير رابط الدفع',
208
+ verifyHeading: 'الطلب جاهز للدفع',
209
+ paidHeading: 'تم تأكيد الدفع',
210
+ reservedNotice: 'رابط الدفع محجوز لمدة 25 دقيقة.',
211
+ payNow: 'ادفع الآن',
212
+ checkStatusBtn: 'تحقق من حالة الدفع',
213
+ editOrder: 'تعديل',
214
+ openShopLink: 'رابط المتجر',
215
+ processing: 'جاري الاتصال بالبوابة...',
216
+ },
217
+ };
218
+
219
+ function formatDzd(amount) {
220
+ return new Intl.NumberFormat('fr-DZ').format(Number(amount) || 0) + ' DZD';
221
+ }
222
+
223
+ class SlickPayModalController {
224
+ constructor() {
225
+ this.host = null;
226
+ this.shadow = null;
227
+ this.boundKeyDown = this.handleKeyDown.bind(this);
228
+ this.state = {
229
+ step: 1,
230
+ quantity: 1,
231
+ loading: false,
232
+ error: null,
233
+ session: null,
234
+ formValues: {
235
+ wilaya: '16',
236
+ address: '',
237
+ fullName: '',
238
+ email: '',
239
+ phone: '',
240
+ customFields: {},
241
+ },
242
+ };
243
+ }
244
+
245
+ open(config = {}) {
246
+ const parsedAmount = Number(config.amount);
247
+ const hasValidAmount = Number.isFinite(parsedAmount) && parsedAmount >= 100;
248
+ const hasProductId = Boolean(config.productId && String(config.productId).trim());
249
+
250
+ this.config = {
251
+ endpoint: config.endpoint || globalConfig.endpoint,
252
+ mode: config.mode || globalConfig.mode,
253
+ publicKey: config.publicKey !== undefined ? config.publicKey : globalConfig.publicKey,
254
+ accountType: config.accountType || globalConfig.accountType,
255
+ productId: config.productId || '',
256
+ priceSignature: config.priceSignature || '',
257
+ productName: config.productName || 'Commande',
258
+ productDescription:
259
+ config.productDescription || 'Paiement sécurisé CIB / Edahabia',
260
+ amount: hasValidAmount ? parsedAmount : 0,
261
+ deliveryFee:
262
+ config.deliveryFee !== undefined
263
+ ? Number(config.deliveryFee)
264
+ : Number(globalConfig.deliveryFee || 0),
265
+ merchantName: config.merchantName || globalConfig.merchantName,
266
+ locale: config.locale || globalConfig.locale || 'fr',
267
+ shopUrl: config.shopUrl !== undefined ? config.shopUrl : globalConfig.shopUrl,
268
+ returnUrl: config.returnUrl || globalConfig.returnUrl || '',
269
+ customFields:
270
+ Array.isArray(config.customFields) && config.customFields.length > 0
271
+ ? config.customFields
272
+ : globalConfig.customFields,
273
+ prefill: config.prefill || {},
274
+ onSuccess: config.onSuccess || null,
275
+ onSessionCreated: config.onSessionCreated || config.onSuccess || null,
276
+ onPaymentVerified: config.onPaymentVerified || null,
277
+ onError: config.onError || null,
278
+ };
279
+
280
+ this.state.step = 1;
281
+ this.state.quantity = Math.max(1, Math.min(1000, parseInt(config.quantity || 1, 10) || 1));
282
+ this.state.loading = false;
283
+ this.state.error =
284
+ !hasValidAmount && !hasProductId
285
+ ? 'Configuration du bouton incomplète : attribut amount (>= 100 DZD) ou product-id requis.'
286
+ : null;
287
+ this.state.session = null;
288
+ this.state.formValues = {
289
+ wilaya: this.config.prefill.wilaya || '16',
290
+ address: this.config.prefill.address || '',
291
+ fullName: this.config.prefill.fullName || '',
292
+ email: this.config.prefill.email || '',
293
+ phone: this.config.prefill.phone || '',
294
+ customFields: { ...(this.config.prefill.customFields || {}) },
295
+ };
296
+
297
+ if (!this.host) {
298
+ this.host = document.createElement('div');
299
+ this.host.id = 'slickpay-universal-modal-host';
300
+ this.shadow = this.host.attachShadow({ mode: 'open' });
301
+ document.body.appendChild(this.host);
302
+ document.addEventListener('keydown', this.boundKeyDown);
303
+ }
304
+
305
+ this.render();
306
+ }
307
+
308
+ close() {
309
+ document.removeEventListener('keydown', this.boundKeyDown);
310
+ if (this.host && this.host.parentNode) {
311
+ this.host.parentNode.removeChild(this.host);
312
+ this.host = null;
313
+ this.shadow = null;
314
+ }
315
+ }
316
+
317
+ handleKeyDown(e) {
318
+ if (!this.shadow) return;
319
+ if (e.key === 'Escape') {
320
+ e.preventDefault();
321
+ this.close();
322
+ return;
323
+ }
324
+ if (e.key === 'Tab') {
325
+ const focusables = Array.from(
326
+ this.shadow.querySelectorAll(
327
+ 'button:not([disabled]), input:not([disabled]), select:not([disabled]), a[href]'
328
+ )
329
+ );
330
+ if (focusables.length === 0) return;
331
+ const first = focusables[0];
332
+ const last = focusables[focusables.length - 1];
333
+ const active = this.shadow.activeElement;
334
+ if (e.shiftKey && (active === first || !active)) {
335
+ e.preventDefault();
336
+ last.focus();
337
+ } else if (!e.shiftKey && active === last) {
338
+ e.preventDefault();
339
+ first.focus();
340
+ }
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Sauvegarde les champs en cours de saisie avant un re-rendu (ex: clic sur +/- quantité)
346
+ */
347
+ captureCurrentInputs() {
348
+ if (!this.shadow) return;
349
+ const fnEl = this.shadow.getElementById('sp-fullName');
350
+ const emEl = this.shadow.getElementById('sp-email');
351
+ const phEl = this.shadow.getElementById('sp-phone');
352
+ const wiEl = this.shadow.getElementById('sp-wilaya');
353
+ const adEl = this.shadow.getElementById('sp-address');
354
+
355
+ if (fnEl) this.state.formValues.fullName = fnEl.value;
356
+ if (emEl) this.state.formValues.email = emEl.value;
357
+ if (phEl) this.state.formValues.phone = phEl.value;
358
+ if (wiEl) this.state.formValues.wilaya = wiEl.value;
359
+ if (adEl) this.state.formValues.address = adEl.value;
360
+
361
+ if (this.config && Array.isArray(this.config.customFields)) {
362
+ for (const f of this.config.customFields) {
363
+ const cfEl = this.shadow.getElementById(`sp-custom-${f.key}`);
364
+ if (cfEl) {
365
+ this.state.formValues.customFields[f.key] = cfEl.value;
366
+ }
367
+ }
368
+ }
369
+ }
370
+
371
+ get dict() {
372
+ return I18N[this.config?.locale] || I18N.fr;
373
+ }
374
+
375
+ get totalAmount() {
376
+ return Math.round((this.config.amount * this.state.quantity + this.config.deliveryFee) * 100) / 100;
377
+ }
378
+
379
+ handleStep1Next(event) {
380
+ event.preventDefault();
381
+ this.captureCurrentInputs();
382
+ this.state.formValues.fullName = String(this.state.formValues.fullName || '').trim();
383
+ this.state.formValues.email = String(this.state.formValues.email || '').trim();
384
+ this.state.formValues.phone = String(this.state.formValues.phone || '').trim();
385
+ this.state.error = null;
386
+ this.state.step = 2;
387
+ this.render();
388
+ }
389
+
390
+ async handleStep2Submit(event) {
391
+ event.preventDefault();
392
+ this.captureCurrentInputs();
393
+ this.state.formValues.wilaya = this.state.formValues.wilaya || '16';
394
+ this.state.formValues.address = String(this.state.formValues.address || '').trim();
395
+
396
+ this.state.loading = true;
397
+ this.state.error = null;
398
+ this.render();
399
+
400
+ try {
401
+ const res = await fetch(this.config.endpoint, {
402
+ method: 'POST',
403
+ headers: { 'Content-Type': 'application/json' },
404
+ body: JSON.stringify({
405
+ mode: this.config.mode,
406
+ publicKey: this.config.publicKey || undefined,
407
+ accountType: this.config.accountType,
408
+ returnUrl: this.config.returnUrl || undefined,
409
+ productId: this.config.productId || undefined,
410
+ priceSignature: this.config.priceSignature || undefined,
411
+ productName: this.config.productName,
412
+ amount: this.config.amount,
413
+ quantity: this.state.quantity,
414
+ deliveryFee: this.config.deliveryFee,
415
+ wilaya: this.state.formValues.wilaya,
416
+ address: this.state.formValues.address,
417
+ fullName: this.state.formValues.fullName,
418
+ email: this.state.formValues.email,
419
+ phone: this.state.formValues.phone,
420
+ customFields: this.state.formValues.customFields,
421
+ }),
422
+ });
423
+
424
+ const data = await res.json();
425
+ if (!res.ok || !data.ok) {
426
+ throw new Error(
427
+ data.error || 'Erreur lors de la création de la session SlickPay'
428
+ );
429
+ }
430
+
431
+ this.state.session = data;
432
+ this.state.step = 3;
433
+ this.state.loading = false;
434
+ this.render();
435
+
436
+ window.dispatchEvent(
437
+ new CustomEvent('slickpay:session-created', { detail: data })
438
+ );
439
+ if (typeof this.config.onSessionCreated === 'function') {
440
+ this.config.onSessionCreated(data);
441
+ }
442
+ } catch (err) {
443
+ this.state.loading = false;
444
+ this.state.error = err.message;
445
+ this.render();
446
+ window.dispatchEvent(
447
+ new CustomEvent('slickpay:session-error', {
448
+ detail: { error: err.message },
449
+ })
450
+ );
451
+ if (typeof this.config.onError === 'function') {
452
+ this.config.onError(err);
453
+ }
454
+ }
455
+ }
456
+
457
+ async verifyCurrentSessionStatus() {
458
+ if (!this.state.session || !this.state.session.invoiceId) return;
459
+ this.state.loading = true;
460
+ this.state.error = null;
461
+ this.render();
462
+ try {
463
+ const statusData = await checkStatusRequest(
464
+ this.state.session.invoiceId,
465
+ this.config
466
+ );
467
+ this.state.session.status = statusData.status || 'pending';
468
+ this.state.loading = false;
469
+ this.render();
470
+ window.dispatchEvent(
471
+ new CustomEvent('slickpay:status-checked', { detail: statusData })
472
+ );
473
+ if (
474
+ statusData.status === 'paid' &&
475
+ typeof this.config.onPaymentVerified === 'function'
476
+ ) {
477
+ this.config.onPaymentVerified(statusData);
478
+ }
479
+ } catch (err) {
480
+ this.state.loading = false;
481
+ this.state.error = err.message;
482
+ this.render();
483
+ }
484
+ }
485
+
486
+ render() {
487
+ if (!this.shadow) return;
488
+ const t = this.dict;
489
+ const isRtl = this.config.locale === 'ar';
490
+ const s = this.state.step;
491
+
492
+ const wilayaOptions = WILAYAS_58.map(
493
+ ([code, name]) =>
494
+ `<option value="${escapeHtml(code)}" ${
495
+ this.state.formValues.wilaya === code ? 'selected' : ''
496
+ }>${escapeHtml(code)} - ${escapeHtml(name)}</option>`
497
+ ).join('');
498
+
499
+ const customFieldsHtml = this.config.customFields
500
+ .map((f) => {
501
+ const safeKey = escapeHtml(f.key);
502
+ const safeLabel = escapeHtml(f.label);
503
+ const safePlaceholder = escapeHtml(f.placeholder || f.label);
504
+ const val = escapeHtml(this.state.formValues.customFields[f.key] || '');
505
+ return `
506
+ <div class="sp-field">
507
+ <label for="sp-custom-${safeKey}">${safeLabel}${f.required ? ' *' : ''}</label>
508
+ <input
509
+ id="sp-custom-${safeKey}"
510
+ name="custom_${safeKey}"
511
+ type="text"
512
+ value="${val}"
513
+ placeholder="${safePlaceholder}"
514
+ ${f.required ? 'required' : ''}
515
+ />
516
+ </div>
517
+ `;
518
+ })
519
+ .join('');
520
+
521
+ const step1Html = `
522
+ <form id="sp-step1-form">
523
+ <p class="sp-step-title">${escapeHtml(t.step1Title)}</p>
524
+
525
+ <div class="sp-qty-bar">
526
+ <span>${escapeHtml(t.quantity)} (${escapeHtml(formatDzd(this.config.amount))} / u)</span>
527
+ <div class="sp-stepper">
528
+ <button type="button" id="sp-qty-minus" ${this.state.quantity <= 1 ? 'disabled' : ''}>−</button>
529
+ <output id="sp-qty-val">${escapeHtml(this.state.quantity)}</output>
530
+ <button type="button" id="sp-qty-plus">+</button>
531
+ </div>
532
+ </div>
533
+
534
+ <div class="sp-field">
535
+ <label for="sp-fullName">${escapeHtml(t.fullName)} *</label>
536
+ <input id="sp-fullName" name="fullName" type="text" required value="${escapeHtml(this.state.formValues.fullName)}" placeholder="Ex: Amine Benali" />
537
+ </div>
538
+
539
+ <div class="sp-field">
540
+ <label for="sp-email">${escapeHtml(t.email)} *</label>
541
+ <input id="sp-email" name="email" type="email" required value="${escapeHtml(this.state.formValues.email)}" placeholder="nom@entreprise.dz" />
542
+ </div>
543
+
544
+ <div class="sp-field">
545
+ <label for="sp-phone">${escapeHtml(t.phone)} *</label>
546
+ <input id="sp-phone" name="phone" type="tel" required value="${escapeHtml(this.state.formValues.phone)}" placeholder="0550 00 00 00" />
547
+ </div>
548
+
549
+ ${
550
+ this.state.error
551
+ ? `<div class="sp-error" role="alert">${escapeHtml(this.state.error)}</div>`
552
+ : ''
553
+ }
554
+
555
+ <div class="sp-actions-row">
556
+ <button type="submit" class="sp-btn-primary" id="sp-step1-next" ${this.state.error ? 'disabled' : ''}>
557
+ ${escapeHtml(t.nextBtn)}
558
+ </button>
559
+ </div>
560
+ </form>
561
+ `;
562
+
563
+ const step2Html = `
564
+ <form id="sp-step2-form">
565
+ <p class="sp-step-title">${escapeHtml(t.step2Title)}</p>
566
+
567
+ <div class="sp-field">
568
+ <label for="sp-wilaya">${escapeHtml(t.wilaya)} *</label>
569
+ <select id="sp-wilaya" name="wilaya" required>
570
+ <option value="">${escapeHtml(t.chooseWilaya)}</option>
571
+ ${wilayaOptions}
572
+ </select>
573
+ </div>
574
+
575
+ <div class="sp-field">
576
+ <label for="sp-address">${escapeHtml(t.address)} *</label>
577
+ <input id="sp-address" name="address" type="text" required value="${escapeHtml(this.state.formValues.address)}" placeholder="Rue, Commune, Ville..." />
578
+ </div>
579
+
580
+ ${
581
+ customFieldsHtml
582
+ ? `<div class="sp-grid-2">${customFieldsHtml}</div>`
583
+ : ''
584
+ }
585
+
586
+ ${
587
+ this.state.error
588
+ ? `<div class="sp-error" role="alert">${escapeHtml(this.state.error)}</div>`
589
+ : ''
590
+ }
591
+
592
+ <div class="sp-actions-row">
593
+ <button type="button" class="sp-btn-secondary" id="sp-step2-back">
594
+ ${escapeHtml(t.backBtn)}
595
+ </button>
596
+ <button type="submit" class="sp-btn-primary" id="sp-step2-submit" ${this.state.loading ? 'disabled' : ''}>
597
+ ${escapeHtml(this.state.loading ? t.processing : t.generateBtn)}
598
+ </button>
599
+ </div>
600
+ </form>
601
+ `;
602
+
603
+ const session = this.state.session;
604
+ const safePaymentUrl = session ? sanitizeUrl(session.paymentUrl, true) : '';
605
+ const safeShopUrl = sanitizeUrl(this.config.shopUrl, false);
606
+ const isPaid = session && session.status === 'paid';
607
+
608
+ const step3Html = session
609
+ ? `
610
+ <div>
611
+ <div class="sp-status-pill">✓ ${escapeHtml(isPaid ? t.paidHeading : t.verifyHeading)}</div>
612
+ <p class="sp-reserve-note">${escapeHtml(t.reservedNotice)}</p>
613
+
614
+ <div class="sp-summary-card">
615
+ <div class="sp-summary-row">
616
+ <span>${escapeHtml(t.product)}</span>
617
+ <strong>${escapeHtml(this.config.productName)} × ${escapeHtml(this.state.quantity)}</strong>
618
+ </div>
619
+ <div class="sp-summary-row">
620
+ <span>Client</span>
621
+ <span>${escapeHtml(session.customer?.fullName || this.state.formValues.fullName)}</span>
622
+ </div>
623
+ <div class="sp-summary-row">
624
+ <span>Wilaya</span>
625
+ <span>${escapeHtml(session.customer?.wilaya || this.state.formValues.wilaya)}</span>
626
+ </div>
627
+ <div class="sp-summary-row">
628
+ <span>Réf. transaction</span>
629
+ <code>${escapeHtml(session.invoiceId)}</code>
630
+ </div>
631
+ <div class="sp-summary-row sp-total">
632
+ <span>${escapeHtml(t.total)}</span>
633
+ <strong>${escapeHtml(formatDzd(session.totals?.totalChargeDzd || this.totalAmount))}</strong>
634
+ </div>
635
+ </div>
636
+
637
+ ${
638
+ this.state.error
639
+ ? `<div class="sp-error" role="alert">${escapeHtml(this.state.error)}</div>`
640
+ : ''
641
+ }
642
+
643
+ <div class="sp-actions-row">
644
+ <button type="button" class="sp-btn-secondary" id="sp-edit-order-btn">
645
+ ${escapeHtml(t.editOrder)}
646
+ </button>
647
+ ${
648
+ safePaymentUrl
649
+ ? `<a href="${escapeHtml(safePaymentUrl)}" target="_blank" rel="noopener noreferrer" class="sp-btn-primary" id="sp-pay-satim-btn">
650
+ ${escapeHtml(t.payNow)} (${escapeHtml(formatDzd(session.totals?.totalChargeDzd || this.totalAmount))}) →
651
+ </a>`
652
+ : ''
653
+ }
654
+ </div>
655
+ <div class="sp-actions-row">
656
+ <button type="button" class="sp-btn-secondary" id="sp-check-status-btn" ${this.state.loading ? 'disabled' : ''}>
657
+ ${escapeHtml(this.state.loading ? t.processing : t.checkStatusBtn)}
658
+ </button>
659
+ </div>
660
+ </div>
661
+ `
662
+ : '';
663
+
664
+ this.shadow.innerHTML = `
665
+ <link rel="stylesheet" href="${escapeHtml(widgetCssUrl)}" />
666
+ <div class="sp-overlay" dir="${isRtl ? 'rtl' : 'ltr'}">
667
+ <div class="sp-modal" role="dialog" aria-modal="true" aria-labelledby="sp-modal-title">
668
+ <div class="sp-header">
669
+ <div class="sp-merchant-info">
670
+ <span class="sp-merchant-tag">
671
+ <span class="sp-dot"></span>
672
+ ${escapeHtml(this.config.merchantName)}
673
+ </span>
674
+ <h3 class="sp-amount-hero" id="sp-modal-title">${escapeHtml(formatDzd(this.totalAmount))}</h3>
675
+ <p class="sp-product-sub">${escapeHtml(this.config.productName)} — ${escapeHtml(this.config.productDescription)}</p>
676
+ </div>
677
+ <button type="button" class="sp-close" id="sp-close-btn" aria-label="Fermer">✕</button>
678
+ </div>
679
+
680
+ <div class="sp-steps-bar">
681
+ <div class="sp-step-item ${s === 1 ? 'active' : s > 1 ? 'done' : ''}">
682
+ <span class="sp-step-num">${s > 1 ? '✓' : '1'}</span>
683
+ <span>${escapeHtml(t.step1Label)}</span>
684
+ </div>
685
+ <div class="sp-step-sep"></div>
686
+ <div class="sp-step-item ${s === 2 ? 'active' : s > 2 ? 'done' : ''}">
687
+ <span class="sp-step-num">${s > 2 ? '✓' : '2'}</span>
688
+ <span>${escapeHtml(t.step2Label)}</span>
689
+ </div>
690
+ <div class="sp-step-sep"></div>
691
+ <div class="sp-step-item ${s === 3 ? 'active' : ''}">
692
+ <span class="sp-step-num">3</span>
693
+ <span>${escapeHtml(t.step3Label)}</span>
694
+ </div>
695
+ </div>
696
+
697
+ <div class="sp-body">
698
+ ${s === 1 ? step1Html : s === 2 ? step2Html : step3Html}
699
+ </div>
700
+
701
+ <div class="sp-footer">
702
+ <span>${escapeHtml(t.securedBy)}</span>
703
+ ${
704
+ safeShopUrl
705
+ ? `<a href="${escapeHtml(safeShopUrl)}" target="_blank" rel="noopener noreferrer">${escapeHtml(t.openShopLink)} ↗</a>`
706
+ : ''
707
+ }
708
+ </div>
709
+ </div>
710
+ </div>
711
+ `;
712
+
713
+ const closeBtn = this.shadow.getElementById('sp-close-btn');
714
+ if (closeBtn) closeBtn.addEventListener('click', () => this.close());
715
+
716
+ const minusBtn = this.shadow.getElementById('sp-qty-minus');
717
+ if (minusBtn) {
718
+ minusBtn.addEventListener('click', () => {
719
+ if (this.state.quantity > 1) {
720
+ this.captureCurrentInputs();
721
+ this.state.quantity -= 1;
722
+ this.render();
723
+ }
724
+ });
725
+ }
726
+
727
+ const plusBtn = this.shadow.getElementById('sp-qty-plus');
728
+ if (plusBtn) {
729
+ plusBtn.addEventListener('click', () => {
730
+ if (this.state.quantity < 1000) {
731
+ this.captureCurrentInputs();
732
+ this.state.quantity += 1;
733
+ this.render();
734
+ }
735
+ });
736
+ }
737
+
738
+ const step1Form = this.shadow.getElementById('sp-step1-form');
739
+ if (step1Form) {
740
+ step1Form.addEventListener('submit', (e) => this.handleStep1Next(e));
741
+ }
742
+
743
+ const step2Back = this.shadow.getElementById('sp-step2-back');
744
+ if (step2Back) {
745
+ step2Back.addEventListener('click', () => {
746
+ this.captureCurrentInputs();
747
+ this.state.step = 1;
748
+ this.state.error = null;
749
+ this.render();
750
+ });
751
+ }
752
+
753
+ const step2Form = this.shadow.getElementById('sp-step2-form');
754
+ if (step2Form) {
755
+ step2Form.addEventListener('submit', (e) => this.handleStep2Submit(e));
756
+ }
757
+
758
+ const editBtn = this.shadow.getElementById('sp-edit-order-btn');
759
+ if (editBtn) {
760
+ editBtn.addEventListener('click', () => {
761
+ this.state.step = 2;
762
+ this.render();
763
+ });
764
+ }
765
+
766
+ const checkStatusBtn = this.shadow.getElementById('sp-check-status-btn');
767
+ if (checkStatusBtn) {
768
+ checkStatusBtn.addEventListener('click', () =>
769
+ this.verifyCurrentSessionStatus()
770
+ );
771
+ }
772
+ }
773
+ }
774
+
775
+ async function checkStatusRequest(invoiceId, opts = {}) {
776
+ const endpoint = opts.endpoint || globalConfig.endpoint;
777
+ const mode = opts.mode || globalConfig.mode;
778
+ const publicKey =
779
+ opts.publicKey !== undefined ? opts.publicKey : globalConfig.publicKey;
780
+ const accountType = opts.accountType || globalConfig.accountType;
781
+
782
+ const res = await fetch(endpoint, {
783
+ method: 'POST',
784
+ headers: { 'Content-Type': 'application/json' },
785
+ body: JSON.stringify({
786
+ action: 'status',
787
+ invoiceId,
788
+ mode,
789
+ publicKey: publicKey || undefined,
790
+ accountType,
791
+ }),
792
+ });
793
+ const data = await res.json();
794
+ if (!res.ok || !data.ok) {
795
+ throw new Error(data.error || 'Impossible de vérifier le statut de la facture.');
796
+ }
797
+ return data;
798
+ }
799
+
800
+ const modalSingleton = new SlickPayModalController();
801
+
802
+ if (typeof document !== 'undefined') {
803
+ document.addEventListener('click', function (e) {
804
+ const trigger = e.target.closest && e.target.closest('[data-slickpay]');
805
+ if (!trigger) return;
806
+ e.preventDefault();
807
+ const ds = trigger.dataset;
808
+ modalSingleton.open({
809
+ productId: ds.productId || '',
810
+ priceSignature: ds.priceSignature || '',
811
+ productName: ds.productName || ds.name || 'Article',
812
+ productDescription: ds.productDescription || ds.description || '',
813
+ amount: ds.amount !== undefined || ds.price !== undefined ? Number(ds.amount ?? ds.price) : NaN,
814
+ quantity: Number(ds.quantity || 1),
815
+ deliveryFee:
816
+ ds.deliveryFee !== undefined ? Number(ds.deliveryFee) : undefined,
817
+ });
818
+ });
819
+ }
820
+
821
+ class SlickPayButtonElement extends HTMLElement {
822
+ connectedCallback() {
823
+ this.renderButton();
824
+ }
825
+
826
+ static get observedAttributes() {
827
+ return ['label', 'amount', 'product-name', 'locale'];
828
+ }
829
+
830
+ attributeChangedCallback() {
831
+ if (this.isConnected) this.renderButton();
832
+ }
833
+
834
+ renderButton() {
835
+ const locale = this.getAttribute('locale') || globalConfig.locale || 'fr';
836
+ const dict = I18N[locale] || I18N.fr;
837
+ const amount = this.getAttribute('amount') || '45000';
838
+ const label =
839
+ this.getAttribute('label') ||
840
+ `${dict.ctaDefault} · ${formatDzd(amount)}`;
841
+
842
+ this.innerHTML = `
843
+ <button type="button" class="slickpay-trigger-btn">
844
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
845
+ <rect x="2" y="5" width="20" height="14" rx="2"></rect>
846
+ <line x1="2" y1="10" x2="22" y2="10"></line>
847
+ </svg>
848
+ <span>${escapeHtml(label)}</span>
849
+ </button>
850
+ `;
851
+
852
+ const btn = this.querySelector('button');
853
+ btn.addEventListener('click', () => this.openCheckout());
854
+ }
855
+
856
+ openCheckout() {
857
+ let customFields = undefined;
858
+ const rawCustom = this.getAttribute('custom-fields');
859
+ if (rawCustom) {
860
+ try {
861
+ customFields = JSON.parse(rawCustom);
862
+ } catch (_) {}
863
+ }
864
+
865
+ modalSingleton.open({
866
+ endpoint: this.getAttribute('endpoint') || undefined,
867
+ mode: this.getAttribute('mode') || undefined,
868
+ publicKey: this.getAttribute('public-key') || undefined,
869
+ accountType: this.getAttribute('account-type') || undefined,
870
+ productId: this.getAttribute('product-id') || undefined,
871
+ priceSignature: this.getAttribute('price-signature') || undefined,
872
+ productName: this.getAttribute('product-name') || 'Produit',
873
+ productDescription:
874
+ this.getAttribute('product-description') || undefined,
875
+ amount: this.hasAttribute('amount') ? Number(this.getAttribute('amount')) : NaN,
876
+ quantity: Number(this.getAttribute('quantity') || 1),
877
+ deliveryFee: this.hasAttribute('delivery-fee')
878
+ ? Number(this.getAttribute('delivery-fee'))
879
+ : undefined,
880
+ merchantName: this.getAttribute('merchant-name') || undefined,
881
+ locale: this.getAttribute('locale') || undefined,
882
+ shopUrl: this.getAttribute('shop-url') || undefined,
883
+ customFields,
884
+ });
885
+ }
886
+ }
887
+
888
+ if (!customElements.get('slickpay-button')) {
889
+ customElements.define('slickpay-button', SlickPayButtonElement);
890
+ }
891
+
892
+ global.SlickPay = {
893
+ init: function (options = {}) {
894
+ Object.assign(globalConfig, options);
895
+ document.querySelectorAll('slickpay-button').forEach((el) => {
896
+ if (typeof el.renderButton === 'function') el.renderButton();
897
+ });
898
+ return globalConfig;
899
+ },
900
+ getConfig: function () {
901
+ return { ...globalConfig };
902
+ },
903
+ openCheckout: (options) => modalSingleton.open(options),
904
+ closeCheckout: () => modalSingleton.close(),
905
+ checkStatus: (invoiceId, options) => checkStatusRequest(invoiceId, options),
906
+ escapeHtml,
907
+ sanitizeUrl,
908
+ WILAYAS_58,
909
+ };
910
+ })(typeof window !== 'undefined' ? window : globalThis);