@nehorai/payments-il 0.1.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,841 @@
1
+ // src/providers/hyp/hyp-provider.ts
2
+ import { calculateCaptureDeadline } from "@nehorai/payments/types";
3
+
4
+ // src/providers/hyp/hyp-types.ts
5
+ var DEFAULT_HYP_ENDPOINTS = {
6
+ test: "https://cguat2.creditguard.co.il",
7
+ production: "https://cgpay3.creditguard.co.il"
8
+ };
9
+ var HYP_SUPPORTED_CURRENCIES = [
10
+ "ILS",
11
+ // Israeli Shekel (primary)
12
+ "USD",
13
+ // US Dollar
14
+ "EUR",
15
+ // Euro
16
+ "GBP"
17
+ // British Pound
18
+ ];
19
+ var HYP_RESULT_CODE_MAP = {
20
+ "000": "captured",
21
+ // Success
22
+ "001": "failed",
23
+ // Declined
24
+ "002": "failed",
25
+ // Invalid card
26
+ "003": "failed",
27
+ // Expired card
28
+ "004": "failed",
29
+ // Insufficient funds
30
+ "005": "failed",
31
+ // Invalid CVV
32
+ "006": "failed",
33
+ // Card not permitted
34
+ "033": "failed",
35
+ // Lost/Stolen card
36
+ "034": "failed",
37
+ // Suspected fraud
38
+ "051": "failed",
39
+ // Insufficient funds
40
+ "054": "failed",
41
+ // Expired card
42
+ "057": "failed",
43
+ // Transaction not permitted
44
+ "100": "failed",
45
+ // System error
46
+ "200": "pending_authorization"
47
+ // Pending
48
+ };
49
+ var HYP_TRANSACTION_TYPES = {
50
+ /** Regular charge (immediate capture) */
51
+ DEBIT: "Debit",
52
+ /** Refund */
53
+ CREDIT: "Credit",
54
+ /** Authorization only (J5) */
55
+ DEBIT_J5: "Debit"
56
+ };
57
+ var HYP_TRANSACTION_CODES = {
58
+ /** Regular transaction */
59
+ REGULAR: "Regular",
60
+ /** Verify only (authorization) */
61
+ VERIFY: "Verify",
62
+ /** Force transaction */
63
+ FORCE: "Force"
64
+ };
65
+ var HYP_VALIDATION_MODES = {
66
+ /** Auto commit (immediate capture) */
67
+ AUTO_COMM: "AutoComm",
68
+ /** Transaction only (authorization, requires manual capture) */
69
+ TX_ONLY: "TxOnly"
70
+ };
71
+ var HYP_CREDIT_TYPES = {
72
+ /** Regular credit card */
73
+ REGULAR: "1",
74
+ /** Token/Saved card */
75
+ TOKEN: "8"
76
+ };
77
+ var HYP_ERROR_MAP = {
78
+ "001": "card_declined",
79
+ "002": "invalid_card",
80
+ "003": "expired_card",
81
+ "004": "insufficient_funds",
82
+ "005": "invalid_cvc",
83
+ "006": "card_declined",
84
+ "033": "card_declined",
85
+ "034": "card_declined",
86
+ "051": "insufficient_funds",
87
+ "054": "expired_card",
88
+ "057": "card_declined",
89
+ "100": "processing_error",
90
+ "200": "authentication_required"
91
+ };
92
+ function mapHypStatus(resultCode) {
93
+ return HYP_RESULT_CODE_MAP[resultCode] ?? null;
94
+ }
95
+ function mapHypError(resultCode) {
96
+ return HYP_ERROR_MAP[resultCode] ?? "unknown";
97
+ }
98
+ function isHypSupportedCurrency(currency) {
99
+ return HYP_SUPPORTED_CURRENCIES.includes(
100
+ currency
101
+ );
102
+ }
103
+ function isHypSuccess(resultCode) {
104
+ return resultCode === "000";
105
+ }
106
+ function formatHypAmount(amountMinor) {
107
+ return amountMinor;
108
+ }
109
+ function formatCardExpiration(month, year) {
110
+ const mm = month.padStart(2, "0");
111
+ const yy = year.slice(-2);
112
+ return `${mm}${yy}`;
113
+ }
114
+ function parseCardExpiration(expiration) {
115
+ const mm = expiration.substring(0, 2);
116
+ const yy = expiration.substring(2, 4);
117
+ return {
118
+ month: mm,
119
+ year: `20${yy}`
120
+ };
121
+ }
122
+
123
+ // src/providers/hyp/hyp-provider.ts
124
+ var HypProvider = class {
125
+ name = "hyp";
126
+ supportedCurrencies = HYP_SUPPORTED_CURRENCIES;
127
+ supportsRecurring = true;
128
+ supportsSplitPayments = false;
129
+ config;
130
+ constructor(config) {
131
+ if (!config.terminalNumber || !config.user || !config.password) {
132
+ throw new Error(
133
+ "HypProvider requires terminalNumber, user, and password in config"
134
+ );
135
+ }
136
+ const baseUrl = config.baseUrl ?? (config.environment === "production" ? DEFAULT_HYP_ENDPOINTS.production : DEFAULT_HYP_ENDPOINTS.test);
137
+ this.config = { ...config, baseUrl };
138
+ }
139
+ // ==========================================================================
140
+ // Payment Intent Operations
141
+ // ==========================================================================
142
+ /**
143
+ * Create a payment intent
144
+ *
145
+ * For Hyp, this generates a hosted payment page or prepares for direct charge.
146
+ */
147
+ async createPaymentIntent(params) {
148
+ try {
149
+ if (!params.paymentMethodId) {
150
+ return await this.createHostedPage(params);
151
+ }
152
+ return await this.chargeWithToken(params);
153
+ } catch (error) {
154
+ return this.handleError(error);
155
+ }
156
+ }
157
+ /**
158
+ * Create hosted payment page
159
+ */
160
+ async createHostedPage(params) {
161
+ const uniqueid = params.idempotencyKey;
162
+ const request = {
163
+ terminalNumber: this.config.terminalNumber,
164
+ user: this.config.user,
165
+ password: this.config.password,
166
+ total: formatHypAmount(params.amount.amountMinor),
167
+ currency: params.amount.currency,
168
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
169
+ transactionCode: params.captureMethod === "manual" ? HYP_TRANSACTION_CODES.VERIFY : HYP_TRANSACTION_CODES.REGULAR,
170
+ validation: params.captureMethod === "manual" ? HYP_VALIDATION_MODES.TX_ONLY : HYP_VALIDATION_MODES.AUTO_COMM,
171
+ uniqueid,
172
+ successUrl: params.returnUrl,
173
+ errorUrl: params.returnUrl,
174
+ cancelUrl: params.returnUrl,
175
+ language: "en"
176
+ };
177
+ const response = await this.sendDoDealRequest(request);
178
+ if (!isHypSuccess(response.resultCode)) {
179
+ return {
180
+ success: false,
181
+ error: response.resultDescription ?? "Transaction failed",
182
+ errorCode: mapHypError(response.resultCode)
183
+ };
184
+ }
185
+ return {
186
+ success: true,
187
+ providerIntentId: response.transactionId ?? uniqueid,
188
+ redirectUrl: response.redirectUrl,
189
+ status: "created"
190
+ };
191
+ }
192
+ /**
193
+ * Charge with saved payment method token
194
+ */
195
+ async chargeWithToken(params) {
196
+ const uniqueid = params.idempotencyKey;
197
+ const request = {
198
+ terminalNumber: this.config.terminalNumber,
199
+ user: this.config.user,
200
+ password: this.config.password,
201
+ total: formatHypAmount(params.amount.amountMinor),
202
+ currency: params.amount.currency,
203
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
204
+ transactionCode: params.captureMethod === "manual" ? HYP_TRANSACTION_CODES.VERIFY : HYP_TRANSACTION_CODES.REGULAR,
205
+ validation: params.captureMethod === "manual" ? HYP_VALIDATION_MODES.TX_ONLY : HYP_VALIDATION_MODES.AUTO_COMM,
206
+ creditType: HYP_CREDIT_TYPES.TOKEN,
207
+ cardToken: params.paymentMethodId,
208
+ uniqueid
209
+ };
210
+ const response = await this.sendDoDealRequest(request);
211
+ if (!isHypSuccess(response.resultCode)) {
212
+ return {
213
+ success: false,
214
+ error: response.resultDescription ?? "Transaction failed",
215
+ errorCode: mapHypError(response.resultCode)
216
+ };
217
+ }
218
+ const status = mapHypStatus(response.resultCode) ?? "created";
219
+ return {
220
+ success: true,
221
+ providerIntentId: response.transactionId ?? uniqueid,
222
+ status
223
+ };
224
+ }
225
+ async authorize(params) {
226
+ try {
227
+ return {
228
+ success: true,
229
+ authorizationCode: params.providerIntentId,
230
+ status: "authorized",
231
+ captureDeadline: calculateCaptureDeadline(/* @__PURE__ */ new Date())
232
+ };
233
+ } catch (error) {
234
+ return this.handleError(error);
235
+ }
236
+ }
237
+ async capture(params) {
238
+ try {
239
+ const request = {
240
+ terminalNumber: this.config.terminalNumber,
241
+ user: this.config.user,
242
+ password: this.config.password,
243
+ total: params.amount ? formatHypAmount(params.amount.amountMinor) : void 0,
244
+ currency: params.amount?.currency ?? "ILS",
245
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
246
+ transactionCode: HYP_TRANSACTION_CODES.FORCE,
247
+ validation: HYP_VALIDATION_MODES.AUTO_COMM,
248
+ uniqueid: params.idempotencyKey,
249
+ authorizationCode: params.providerIntentId
250
+ };
251
+ const response = await this.sendDoDealRequest(request);
252
+ if (!isHypSuccess(response.resultCode)) {
253
+ return {
254
+ success: false,
255
+ error: response.resultDescription ?? "Capture failed",
256
+ errorCode: mapHypError(response.resultCode)
257
+ };
258
+ }
259
+ return {
260
+ success: true,
261
+ providerTransactionId: response.transactionId ?? params.providerIntentId,
262
+ status: "captured",
263
+ capturedAmount: params.amount ?? {
264
+ amountMinor: 0,
265
+ currency: "ILS"
266
+ }
267
+ };
268
+ } catch (error) {
269
+ return this.handleError(error);
270
+ }
271
+ }
272
+ async void(params) {
273
+ try {
274
+ const request = {
275
+ terminalNumber: this.config.terminalNumber,
276
+ user: this.config.user,
277
+ password: this.config.password,
278
+ transactionId: params.providerIntentId,
279
+ currency: "ILS",
280
+ uniqueid: params.providerIntentId
281
+ };
282
+ const response = await this.sendRefundRequest(request);
283
+ if (!isHypSuccess(response.resultCode)) {
284
+ return {
285
+ success: false,
286
+ error: response.resultDescription ?? "Void failed"
287
+ };
288
+ }
289
+ return { success: true, status: "voided" };
290
+ } catch (error) {
291
+ return this.handleError(error);
292
+ }
293
+ }
294
+ // ==========================================================================
295
+ // Refunds
296
+ // ==========================================================================
297
+ async refund(params) {
298
+ try {
299
+ const request = {
300
+ terminalNumber: this.config.terminalNumber,
301
+ user: this.config.user,
302
+ password: this.config.password,
303
+ transactionId: params.providerTransactionId,
304
+ total: params.amount ? formatHypAmount(params.amount.amountMinor) : void 0,
305
+ currency: params.amount?.currency ?? "ILS",
306
+ uniqueid: params.idempotencyKey
307
+ };
308
+ const response = await this.sendRefundRequest(request);
309
+ if (!isHypSuccess(response.resultCode)) {
310
+ return {
311
+ success: false,
312
+ error: response.resultDescription ?? "Refund failed"
313
+ };
314
+ }
315
+ return {
316
+ success: true,
317
+ providerRefundId: response.transactionId ?? params.idempotencyKey,
318
+ refundedAmount: params.amount ?? {
319
+ amountMinor: 0,
320
+ currency: "ILS"
321
+ },
322
+ status: "succeeded"
323
+ };
324
+ } catch (error) {
325
+ return this.handleError(error);
326
+ }
327
+ }
328
+ // ==========================================================================
329
+ // Payment Methods (Tokenization)
330
+ // ==========================================================================
331
+ async createSetupIntent(params) {
332
+ try {
333
+ const uniqueid = `setup_${params.userId}_${Date.now()}`;
334
+ const request = {
335
+ terminalNumber: this.config.terminalNumber,
336
+ user: this.config.user,
337
+ password: this.config.password,
338
+ total: 0,
339
+ currency: "ILS",
340
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
341
+ transactionCode: HYP_TRANSACTION_CODES.VERIFY,
342
+ validation: HYP_VALIDATION_MODES.TX_ONLY,
343
+ creditType: HYP_CREDIT_TYPES.TOKEN,
344
+ customerData: params.customerId ?? params.userId,
345
+ uniqueid,
346
+ language: "en"
347
+ };
348
+ const response = await this.sendDoDealRequest(request);
349
+ if (!isHypSuccess(response.resultCode)) {
350
+ return {
351
+ success: false,
352
+ error: response.resultDescription ?? "Setup failed"
353
+ };
354
+ }
355
+ return {
356
+ success: true,
357
+ setupIntentId: response.transactionId ?? uniqueid,
358
+ clientSecret: response.redirectUrl
359
+ };
360
+ } catch (error) {
361
+ return this.handleError(error);
362
+ }
363
+ }
364
+ async savePaymentMethod(params) {
365
+ try {
366
+ const cardToken = params.setupData.cardToken;
367
+ const cardMask = params.setupData.cardMask;
368
+ const cardBrand = params.setupData.cardBrand;
369
+ const cardExpiration = params.setupData.cardExpiration;
370
+ if (!cardToken) {
371
+ return {
372
+ success: false,
373
+ error: "No card token received"
374
+ };
375
+ }
376
+ return {
377
+ success: true,
378
+ paymentMethodId: cardToken,
379
+ cardBrand: cardBrand ?? "unknown",
380
+ cardLast4: cardMask?.slice(-4) ?? "0000",
381
+ cardExpMonth: cardExpiration?.substring(0, 2) ?? "01",
382
+ cardExpYear: `20${cardExpiration?.substring(2, 4) ?? "99"}`
383
+ };
384
+ } catch (error) {
385
+ return this.handleError(error);
386
+ }
387
+ }
388
+ async deletePaymentMethod(_paymentMethodId) {
389
+ return {
390
+ success: true
391
+ };
392
+ }
393
+ // ==========================================================================
394
+ // Customer Management
395
+ // ==========================================================================
396
+ async createCustomer(params) {
397
+ return {
398
+ success: true,
399
+ customerId: params.userId
400
+ };
401
+ }
402
+ async getOrCreateCustomer(userId, _email) {
403
+ return {
404
+ success: true,
405
+ customerId: userId
406
+ };
407
+ }
408
+ // ==========================================================================
409
+ // Health & Security
410
+ // ==========================================================================
411
+ async getHealth() {
412
+ const start = Date.now();
413
+ try {
414
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
415
+ method: "POST",
416
+ headers: {
417
+ "Content-Type": "text/xml"
418
+ },
419
+ body: this.buildTestXML(),
420
+ signal: AbortSignal.timeout(5e3)
421
+ });
422
+ const healthy = response.ok;
423
+ return {
424
+ provider: "hyp",
425
+ healthy,
426
+ lastChecked: /* @__PURE__ */ new Date(),
427
+ avgLatencyMs: Date.now() - start,
428
+ circuitBreakerOpen: false
429
+ };
430
+ } catch {
431
+ return {
432
+ provider: "hyp",
433
+ healthy: false,
434
+ lastChecked: /* @__PURE__ */ new Date(),
435
+ circuitBreakerOpen: false
436
+ };
437
+ }
438
+ }
439
+ validateWebhookSignature(_payload, _signature) {
440
+ if (!this.config.webhookSecret) return false;
441
+ return !!this.config.webhookSecret;
442
+ }
443
+ async getPaymentIntentStatus(_providerIntentId) {
444
+ return {
445
+ status: "unknown",
446
+ error: "Status query not supported by Hyp basic integration"
447
+ };
448
+ }
449
+ // ==========================================================================
450
+ // XML Request Builders
451
+ // ==========================================================================
452
+ buildDoDealXML(request) {
453
+ const parts = [];
454
+ parts.push('<?xml version="1.0" encoding="utf-8"?>');
455
+ parts.push("<ashrait>");
456
+ parts.push("<request>");
457
+ parts.push(`<version>1000</version>`);
458
+ parts.push("<language>ENG</language>");
459
+ parts.push("<command>doDeal</command>");
460
+ parts.push(`<terminalNumber>${this.escapeXml(request.terminalNumber)}</terminalNumber>`);
461
+ parts.push(`<user>${this.escapeXml(request.user)}</user>`);
462
+ parts.push(`<password>${this.escapeXml(request.password)}</password>`);
463
+ if (request.cardNo) {
464
+ parts.push(`<cardNo>${this.escapeXml(request.cardNo)}</cardNo>`);
465
+ }
466
+ if (request.cardExpiration) {
467
+ parts.push(`<cardExpiration>${this.escapeXml(request.cardExpiration)}</cardExpiration>`);
468
+ }
469
+ if (request.cvv) {
470
+ parts.push(`<cvv>${this.escapeXml(request.cvv)}</cvv>`);
471
+ }
472
+ if (request.cardToken) {
473
+ parts.push(`<cardToken>${this.escapeXml(request.cardToken)}</cardToken>`);
474
+ }
475
+ if (request.authorizationCode) {
476
+ parts.push(`<authNumber>${this.escapeXml(request.authorizationCode)}</authNumber>`);
477
+ }
478
+ if (request.total !== void 0) {
479
+ parts.push(`<total>${request.total}</total>`);
480
+ }
481
+ parts.push(`<currency>${this.escapeXml(request.currency)}</currency>`);
482
+ parts.push(`<transactionType>${this.escapeXml(request.transactionType)}</transactionType>`);
483
+ if (request.transactionCode) {
484
+ parts.push(`<transactionCode>${this.escapeXml(request.transactionCode)}</transactionCode>`);
485
+ }
486
+ if (request.creditType) {
487
+ parts.push(`<creditType>${request.creditType}</creditType>`);
488
+ }
489
+ if (request.validation) {
490
+ parts.push(`<validation>${this.escapeXml(request.validation)}</validation>`);
491
+ }
492
+ if (request.uniqueid) {
493
+ parts.push(`<uniqueid>${this.escapeXml(request.uniqueid)}</uniqueid>`);
494
+ }
495
+ if (request.customerData) {
496
+ parts.push(`<customerData>${this.escapeXml(request.customerData)}</customerData>`);
497
+ }
498
+ if (request.successUrl) {
499
+ parts.push(`<successUrl>${this.escapeXml(request.successUrl)}</successUrl>`);
500
+ }
501
+ if (request.errorUrl) {
502
+ parts.push(`<errorUrl>${this.escapeXml(request.errorUrl)}</errorUrl>`);
503
+ }
504
+ if (request.cancelUrl) {
505
+ parts.push(`<cancelUrl>${this.escapeXml(request.cancelUrl)}</cancelUrl>`);
506
+ }
507
+ parts.push("</request>");
508
+ parts.push("</ashrait>");
509
+ return parts.join("");
510
+ }
511
+ buildRefundXML(request) {
512
+ const parts = [];
513
+ parts.push('<?xml version="1.0" encoding="utf-8"?>');
514
+ parts.push("<ashrait>");
515
+ parts.push("<request>");
516
+ parts.push(`<version>1000</version>`);
517
+ parts.push("<language>ENG</language>");
518
+ parts.push("<command>refundDeal</command>");
519
+ parts.push(`<terminalNumber>${this.escapeXml(request.terminalNumber)}</terminalNumber>`);
520
+ parts.push(`<user>${this.escapeXml(request.user)}</user>`);
521
+ parts.push(`<password>${this.escapeXml(request.password)}</password>`);
522
+ parts.push(`<transactionId>${this.escapeXml(request.transactionId)}</transactionId>`);
523
+ parts.push(`<currency>${this.escapeXml(request.currency)}</currency>`);
524
+ if (request.total !== void 0) {
525
+ parts.push(`<total>${request.total}</total>`);
526
+ }
527
+ if (request.uniqueid) {
528
+ parts.push(`<uniqueid>${this.escapeXml(request.uniqueid)}</uniqueid>`);
529
+ }
530
+ parts.push("</request>");
531
+ parts.push("</ashrait>");
532
+ return parts.join("");
533
+ }
534
+ buildTestXML() {
535
+ return `<?xml version="1.0" encoding="utf-8"?>
536
+ <ashrait>
537
+ <request>
538
+ <version>1000</version>
539
+ <language>ENG</language>
540
+ <command>echo</command>
541
+ </request>
542
+ </ashrait>`;
543
+ }
544
+ // ==========================================================================
545
+ // HTTP Helpers
546
+ // ==========================================================================
547
+ async sendDoDealRequest(request) {
548
+ const xmlBody = this.buildDoDealXML(request);
549
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
550
+ method: "POST",
551
+ headers: {
552
+ "Content-Type": "text/xml; charset=utf-8"
553
+ },
554
+ body: xmlBody
555
+ });
556
+ if (!response.ok) {
557
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
558
+ }
559
+ const xmlResponse = await response.text();
560
+ return this.parseDoDealResponse(xmlResponse);
561
+ }
562
+ async sendRefundRequest(request) {
563
+ const xmlBody = this.buildRefundXML(request);
564
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
565
+ method: "POST",
566
+ headers: {
567
+ "Content-Type": "text/xml; charset=utf-8"
568
+ },
569
+ body: xmlBody
570
+ });
571
+ if (!response.ok) {
572
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
573
+ }
574
+ const xmlResponse = await response.text();
575
+ return this.parseRefundResponse(xmlResponse);
576
+ }
577
+ // ==========================================================================
578
+ // XML Parsing
579
+ // ==========================================================================
580
+ parseDoDealResponse(xml) {
581
+ return {
582
+ resultCode: this.extractXmlValue(xml, "resultCode") ?? "100",
583
+ resultDescription: this.extractXmlValue(xml, "resultDescription"),
584
+ transactionId: this.extractXmlValue(xml, "transactionId"),
585
+ authorizationCode: this.extractXmlValue(xml, "authorizationCode"),
586
+ voucherNumber: this.extractXmlValue(xml, "voucherNumber"),
587
+ cardToken: this.extractXmlValue(xml, "cardToken"),
588
+ cardMask: this.extractXmlValue(xml, "cardMask"),
589
+ cardBrand: this.extractXmlValue(xml, "cardBrand"),
590
+ cardExpiration: this.extractXmlValue(xml, "cardExpiration"),
591
+ redirectUrl: this.extractXmlValue(xml, "redirectUrl"),
592
+ uniqueid: this.extractXmlValue(xml, "uniqueid"),
593
+ rawXml: xml
594
+ };
595
+ }
596
+ parseRefundResponse(xml) {
597
+ return {
598
+ resultCode: this.extractXmlValue(xml, "resultCode") ?? "100",
599
+ resultDescription: this.extractXmlValue(xml, "resultDescription"),
600
+ transactionId: this.extractXmlValue(xml, "transactionId"),
601
+ authorizationCode: this.extractXmlValue(xml, "authorizationCode"),
602
+ uniqueid: this.extractXmlValue(xml, "uniqueid")
603
+ };
604
+ }
605
+ extractXmlValue(xml, tagName) {
606
+ const regex = new RegExp(`<${tagName}>([^<]*)</${tagName}>`, "i");
607
+ const match = xml.match(regex);
608
+ return match ? match[1].trim() : void 0;
609
+ }
610
+ escapeXml(str) {
611
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
612
+ }
613
+ // ==========================================================================
614
+ // Error Handling
615
+ // ==========================================================================
616
+ handleError(error) {
617
+ if (error instanceof Error) {
618
+ return {
619
+ success: false,
620
+ error: error.message,
621
+ errorCode: "unknown"
622
+ };
623
+ }
624
+ return {
625
+ success: false,
626
+ error: "Unknown error occurred",
627
+ errorCode: "unknown"
628
+ };
629
+ }
630
+ };
631
+
632
+ // src/providers/hyp/hyp-webhook-handler.ts
633
+ var HYP_EVENT_TYPES = {
634
+ TRANSACTION_SUCCESS: "transaction.success",
635
+ TRANSACTION_FAILED: "transaction.failed",
636
+ TRANSACTION_PENDING: "transaction.pending",
637
+ REFUND_SUCCESS: "refund.success",
638
+ REFUND_FAILED: "refund.failed"
639
+ };
640
+ var HypWebhookHandler = class {
641
+ provider = "hyp";
642
+ supportedEventTypes = Object.values(HYP_EVENT_TYPES);
643
+ parseEvent(rawPayload) {
644
+ try {
645
+ const resultCode = String(rawPayload.resultCode ?? "100");
646
+ const resultDescription = String(rawPayload.resultDescription ?? "");
647
+ const transactionId = String(rawPayload.transactionId ?? "");
648
+ const uniqueid = String(rawPayload.uniqueid ?? "");
649
+ const total = Number(rawPayload.total ?? 0);
650
+ const currency = String(rawPayload.currency ?? "ILS");
651
+ const eventType = this.determineEventType(resultCode);
652
+ const newStatus = mapHypStatus(resultCode);
653
+ const event = {
654
+ provider: "hyp",
655
+ eventId: uniqueid || transactionId || `hyp_${Date.now()}`,
656
+ eventType,
657
+ providerTransactionId: transactionId,
658
+ amountMinor: total,
659
+ currency,
660
+ newStatus: newStatus ?? void 0,
661
+ error: isHypSuccess(resultCode) ? void 0 : {
662
+ code: resultCode,
663
+ message: resultDescription
664
+ },
665
+ timestamp: /* @__PURE__ */ new Date(),
666
+ rawPayload
667
+ };
668
+ return {
669
+ success: true,
670
+ event
671
+ };
672
+ } catch (error) {
673
+ return {
674
+ success: false,
675
+ error: error instanceof Error ? error.message : "Failed to parse webhook"
676
+ };
677
+ }
678
+ }
679
+ async processEvent(event) {
680
+ try {
681
+ if (!event.providerTransactionId) {
682
+ return {
683
+ success: false,
684
+ error: "Missing transaction ID in webhook",
685
+ action: "ignored_event_type"
686
+ };
687
+ }
688
+ const action = this.determineAction(event);
689
+ return {
690
+ success: true,
691
+ transactionId: event.providerTransactionId,
692
+ action
693
+ };
694
+ } catch (error) {
695
+ return {
696
+ success: false,
697
+ error: error instanceof Error ? error.message : "Processing failed",
698
+ action: "ignored_event_type"
699
+ };
700
+ }
701
+ }
702
+ canHandle(eventType) {
703
+ return this.supportedEventTypes.includes(
704
+ eventType
705
+ );
706
+ }
707
+ async reconcile(_transactionId, _providerTransactionId) {
708
+ return {
709
+ reconciled: false,
710
+ finalStatus: "pending_authorization",
711
+ source: "webhook",
712
+ statusChanged: false
713
+ };
714
+ }
715
+ mapEventType(providerEventType) {
716
+ return providerEventType;
717
+ }
718
+ mapStatus(providerStatus) {
719
+ return mapHypStatus(providerStatus);
720
+ }
721
+ // ==========================================================================
722
+ // Helper Methods
723
+ // ==========================================================================
724
+ determineEventType(resultCode) {
725
+ if (isHypSuccess(resultCode)) {
726
+ return HYP_EVENT_TYPES.TRANSACTION_SUCCESS;
727
+ }
728
+ if (resultCode === "200") {
729
+ return HYP_EVENT_TYPES.TRANSACTION_PENDING;
730
+ }
731
+ return HYP_EVENT_TYPES.TRANSACTION_FAILED;
732
+ }
733
+ determineAction(event) {
734
+ switch (event.eventType) {
735
+ case HYP_EVENT_TYPES.TRANSACTION_SUCCESS:
736
+ case HYP_EVENT_TYPES.TRANSACTION_FAILED:
737
+ case HYP_EVENT_TYPES.TRANSACTION_PENDING:
738
+ case HYP_EVENT_TYPES.REFUND_FAILED:
739
+ return "status_updated";
740
+ case HYP_EVENT_TYPES.REFUND_SUCCESS:
741
+ return "refund_processed";
742
+ default:
743
+ return "ignored_event_type";
744
+ }
745
+ }
746
+ // ==========================================================================
747
+ // Webhook Validation
748
+ // ==========================================================================
749
+ validateSignature(payload, signature, secret) {
750
+ const hasRequiredParams = payload.resultCode !== void 0 && (payload.transactionId !== void 0 || payload.uniqueid !== void 0);
751
+ if (!hasRequiredParams) {
752
+ return false;
753
+ }
754
+ if (secret && signature) {
755
+ return this.validateHMAC(payload, signature, secret);
756
+ }
757
+ return hasRequiredParams;
758
+ }
759
+ validateHMAC(_payload, signature, _secret) {
760
+ try {
761
+ return !!signature;
762
+ } catch {
763
+ return false;
764
+ }
765
+ }
766
+ // ==========================================================================
767
+ // Callback URL Builders
768
+ // ==========================================================================
769
+ buildSuccessUrl(baseUrl, transactionId) {
770
+ return `${baseUrl}/api/payments/hyp/callback?status=success&txId=${transactionId}`;
771
+ }
772
+ buildErrorUrl(baseUrl, transactionId) {
773
+ return `${baseUrl}/api/payments/hyp/callback?status=error&txId=${transactionId}`;
774
+ }
775
+ buildCancelUrl(baseUrl, transactionId) {
776
+ return `${baseUrl}/api/payments/hyp/callback?status=cancel&txId=${transactionId}`;
777
+ }
778
+ // ==========================================================================
779
+ // Response Parsing
780
+ // ==========================================================================
781
+ extractErrorDetails(payload) {
782
+ const resultCode = String(payload.resultCode ?? "unknown");
783
+ const resultDescription = String(payload.resultDescription ?? "Unknown error");
784
+ return {
785
+ code: resultCode,
786
+ message: resultDescription,
787
+ userMessage: this.getUserFriendlyMessage(resultCode)
788
+ };
789
+ }
790
+ getUserFriendlyMessage(resultCode) {
791
+ const errorCode = mapHypError(resultCode);
792
+ const messages = {
793
+ card_declined: "Your card was declined. Please try another payment method.",
794
+ invalid_card: "The card information is invalid. Please check and try again.",
795
+ expired_card: "Your card has expired. Please use a different card.",
796
+ insufficient_funds: "Insufficient funds. Please try another payment method.",
797
+ invalid_cvc: "The security code (CVV) is incorrect.",
798
+ processing_error: "A processing error occurred. Please try again.",
799
+ authentication_required: "Additional authentication is required. Please complete the verification.",
800
+ unknown: "An error occurred. Please try again or contact support."
801
+ };
802
+ return messages[errorCode] ?? messages.unknown;
803
+ }
804
+ extractCardDetails(payload) {
805
+ const cardToken = payload.cardToken;
806
+ const cardMask = payload.cardMask;
807
+ const cardBrand = payload.cardBrand;
808
+ const cardExpiration = payload.cardExpiration;
809
+ return {
810
+ cardToken,
811
+ cardMask,
812
+ cardBrand,
813
+ cardExpiration,
814
+ last4: cardMask?.slice(-4)
815
+ };
816
+ }
817
+ };
818
+ function createHypWebhookHandler() {
819
+ return new HypWebhookHandler();
820
+ }
821
+ export {
822
+ DEFAULT_HYP_ENDPOINTS,
823
+ HYP_CREDIT_TYPES,
824
+ HYP_ERROR_MAP,
825
+ HYP_RESULT_CODE_MAP,
826
+ HYP_SUPPORTED_CURRENCIES,
827
+ HYP_TRANSACTION_CODES,
828
+ HYP_TRANSACTION_TYPES,
829
+ HYP_VALIDATION_MODES,
830
+ HypProvider,
831
+ HypWebhookHandler,
832
+ createHypWebhookHandler,
833
+ formatCardExpiration,
834
+ formatHypAmount,
835
+ isHypSuccess,
836
+ isHypSupportedCurrency,
837
+ mapHypError,
838
+ mapHypStatus,
839
+ parseCardExpiration
840
+ };
841
+ //# sourceMappingURL=index.js.map