@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,1381 @@
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 isHypSuccess(resultCode) {
99
+ return resultCode === "000";
100
+ }
101
+ function formatHypAmount(amountMinor) {
102
+ return amountMinor;
103
+ }
104
+
105
+ // src/providers/hyp/hyp-provider.ts
106
+ var HypProvider = class {
107
+ name = "hyp";
108
+ supportedCurrencies = HYP_SUPPORTED_CURRENCIES;
109
+ supportsRecurring = true;
110
+ supportsSplitPayments = false;
111
+ config;
112
+ constructor(config) {
113
+ if (!config.terminalNumber || !config.user || !config.password) {
114
+ throw new Error(
115
+ "HypProvider requires terminalNumber, user, and password in config"
116
+ );
117
+ }
118
+ const baseUrl = config.baseUrl ?? (config.environment === "production" ? DEFAULT_HYP_ENDPOINTS.production : DEFAULT_HYP_ENDPOINTS.test);
119
+ this.config = { ...config, baseUrl };
120
+ }
121
+ // ==========================================================================
122
+ // Payment Intent Operations
123
+ // ==========================================================================
124
+ /**
125
+ * Create a payment intent
126
+ *
127
+ * For Hyp, this generates a hosted payment page or prepares for direct charge.
128
+ */
129
+ async createPaymentIntent(params) {
130
+ try {
131
+ if (!params.paymentMethodId) {
132
+ return await this.createHostedPage(params);
133
+ }
134
+ return await this.chargeWithToken(params);
135
+ } catch (error) {
136
+ return this.handleError(error);
137
+ }
138
+ }
139
+ /**
140
+ * Create hosted payment page
141
+ */
142
+ async createHostedPage(params) {
143
+ const uniqueid = params.idempotencyKey;
144
+ const request = {
145
+ terminalNumber: this.config.terminalNumber,
146
+ user: this.config.user,
147
+ password: this.config.password,
148
+ total: formatHypAmount(params.amount.amountMinor),
149
+ currency: params.amount.currency,
150
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
151
+ transactionCode: params.captureMethod === "manual" ? HYP_TRANSACTION_CODES.VERIFY : HYP_TRANSACTION_CODES.REGULAR,
152
+ validation: params.captureMethod === "manual" ? HYP_VALIDATION_MODES.TX_ONLY : HYP_VALIDATION_MODES.AUTO_COMM,
153
+ uniqueid,
154
+ successUrl: params.returnUrl,
155
+ errorUrl: params.returnUrl,
156
+ cancelUrl: params.returnUrl,
157
+ language: "en"
158
+ };
159
+ const response = await this.sendDoDealRequest(request);
160
+ if (!isHypSuccess(response.resultCode)) {
161
+ return {
162
+ success: false,
163
+ error: response.resultDescription ?? "Transaction failed",
164
+ errorCode: mapHypError(response.resultCode)
165
+ };
166
+ }
167
+ return {
168
+ success: true,
169
+ providerIntentId: response.transactionId ?? uniqueid,
170
+ redirectUrl: response.redirectUrl,
171
+ status: "created"
172
+ };
173
+ }
174
+ /**
175
+ * Charge with saved payment method token
176
+ */
177
+ async chargeWithToken(params) {
178
+ const uniqueid = params.idempotencyKey;
179
+ const request = {
180
+ terminalNumber: this.config.terminalNumber,
181
+ user: this.config.user,
182
+ password: this.config.password,
183
+ total: formatHypAmount(params.amount.amountMinor),
184
+ currency: params.amount.currency,
185
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
186
+ transactionCode: params.captureMethod === "manual" ? HYP_TRANSACTION_CODES.VERIFY : HYP_TRANSACTION_CODES.REGULAR,
187
+ validation: params.captureMethod === "manual" ? HYP_VALIDATION_MODES.TX_ONLY : HYP_VALIDATION_MODES.AUTO_COMM,
188
+ creditType: HYP_CREDIT_TYPES.TOKEN,
189
+ cardToken: params.paymentMethodId,
190
+ uniqueid
191
+ };
192
+ const response = await this.sendDoDealRequest(request);
193
+ if (!isHypSuccess(response.resultCode)) {
194
+ return {
195
+ success: false,
196
+ error: response.resultDescription ?? "Transaction failed",
197
+ errorCode: mapHypError(response.resultCode)
198
+ };
199
+ }
200
+ const status = mapHypStatus(response.resultCode) ?? "created";
201
+ return {
202
+ success: true,
203
+ providerIntentId: response.transactionId ?? uniqueid,
204
+ status
205
+ };
206
+ }
207
+ async authorize(params) {
208
+ try {
209
+ return {
210
+ success: true,
211
+ authorizationCode: params.providerIntentId,
212
+ status: "authorized",
213
+ captureDeadline: calculateCaptureDeadline(/* @__PURE__ */ new Date())
214
+ };
215
+ } catch (error) {
216
+ return this.handleError(error);
217
+ }
218
+ }
219
+ async capture(params) {
220
+ try {
221
+ const request = {
222
+ terminalNumber: this.config.terminalNumber,
223
+ user: this.config.user,
224
+ password: this.config.password,
225
+ total: params.amount ? formatHypAmount(params.amount.amountMinor) : void 0,
226
+ currency: params.amount?.currency ?? "ILS",
227
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
228
+ transactionCode: HYP_TRANSACTION_CODES.FORCE,
229
+ validation: HYP_VALIDATION_MODES.AUTO_COMM,
230
+ uniqueid: params.idempotencyKey,
231
+ authorizationCode: params.providerIntentId
232
+ };
233
+ const response = await this.sendDoDealRequest(request);
234
+ if (!isHypSuccess(response.resultCode)) {
235
+ return {
236
+ success: false,
237
+ error: response.resultDescription ?? "Capture failed",
238
+ errorCode: mapHypError(response.resultCode)
239
+ };
240
+ }
241
+ return {
242
+ success: true,
243
+ providerTransactionId: response.transactionId ?? params.providerIntentId,
244
+ status: "captured",
245
+ capturedAmount: params.amount ?? {
246
+ amountMinor: 0,
247
+ currency: "ILS"
248
+ }
249
+ };
250
+ } catch (error) {
251
+ return this.handleError(error);
252
+ }
253
+ }
254
+ async void(params) {
255
+ try {
256
+ const request = {
257
+ terminalNumber: this.config.terminalNumber,
258
+ user: this.config.user,
259
+ password: this.config.password,
260
+ transactionId: params.providerIntentId,
261
+ currency: "ILS",
262
+ uniqueid: params.providerIntentId
263
+ };
264
+ const response = await this.sendRefundRequest(request);
265
+ if (!isHypSuccess(response.resultCode)) {
266
+ return {
267
+ success: false,
268
+ error: response.resultDescription ?? "Void failed"
269
+ };
270
+ }
271
+ return { success: true, status: "voided" };
272
+ } catch (error) {
273
+ return this.handleError(error);
274
+ }
275
+ }
276
+ // ==========================================================================
277
+ // Refunds
278
+ // ==========================================================================
279
+ async refund(params) {
280
+ try {
281
+ const request = {
282
+ terminalNumber: this.config.terminalNumber,
283
+ user: this.config.user,
284
+ password: this.config.password,
285
+ transactionId: params.providerTransactionId,
286
+ total: params.amount ? formatHypAmount(params.amount.amountMinor) : void 0,
287
+ currency: params.amount?.currency ?? "ILS",
288
+ uniqueid: params.idempotencyKey
289
+ };
290
+ const response = await this.sendRefundRequest(request);
291
+ if (!isHypSuccess(response.resultCode)) {
292
+ return {
293
+ success: false,
294
+ error: response.resultDescription ?? "Refund failed"
295
+ };
296
+ }
297
+ return {
298
+ success: true,
299
+ providerRefundId: response.transactionId ?? params.idempotencyKey,
300
+ refundedAmount: params.amount ?? {
301
+ amountMinor: 0,
302
+ currency: "ILS"
303
+ },
304
+ status: "succeeded"
305
+ };
306
+ } catch (error) {
307
+ return this.handleError(error);
308
+ }
309
+ }
310
+ // ==========================================================================
311
+ // Payment Methods (Tokenization)
312
+ // ==========================================================================
313
+ async createSetupIntent(params) {
314
+ try {
315
+ const uniqueid = `setup_${params.userId}_${Date.now()}`;
316
+ const request = {
317
+ terminalNumber: this.config.terminalNumber,
318
+ user: this.config.user,
319
+ password: this.config.password,
320
+ total: 0,
321
+ currency: "ILS",
322
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
323
+ transactionCode: HYP_TRANSACTION_CODES.VERIFY,
324
+ validation: HYP_VALIDATION_MODES.TX_ONLY,
325
+ creditType: HYP_CREDIT_TYPES.TOKEN,
326
+ customerData: params.customerId ?? params.userId,
327
+ uniqueid,
328
+ language: "en"
329
+ };
330
+ const response = await this.sendDoDealRequest(request);
331
+ if (!isHypSuccess(response.resultCode)) {
332
+ return {
333
+ success: false,
334
+ error: response.resultDescription ?? "Setup failed"
335
+ };
336
+ }
337
+ return {
338
+ success: true,
339
+ setupIntentId: response.transactionId ?? uniqueid,
340
+ clientSecret: response.redirectUrl
341
+ };
342
+ } catch (error) {
343
+ return this.handleError(error);
344
+ }
345
+ }
346
+ async savePaymentMethod(params) {
347
+ try {
348
+ const cardToken = params.setupData.cardToken;
349
+ const cardMask = params.setupData.cardMask;
350
+ const cardBrand = params.setupData.cardBrand;
351
+ const cardExpiration = params.setupData.cardExpiration;
352
+ if (!cardToken) {
353
+ return {
354
+ success: false,
355
+ error: "No card token received"
356
+ };
357
+ }
358
+ return {
359
+ success: true,
360
+ paymentMethodId: cardToken,
361
+ cardBrand: cardBrand ?? "unknown",
362
+ cardLast4: cardMask?.slice(-4) ?? "0000",
363
+ cardExpMonth: cardExpiration?.substring(0, 2) ?? "01",
364
+ cardExpYear: `20${cardExpiration?.substring(2, 4) ?? "99"}`
365
+ };
366
+ } catch (error) {
367
+ return this.handleError(error);
368
+ }
369
+ }
370
+ async deletePaymentMethod(_paymentMethodId) {
371
+ return {
372
+ success: true
373
+ };
374
+ }
375
+ // ==========================================================================
376
+ // Customer Management
377
+ // ==========================================================================
378
+ async createCustomer(params) {
379
+ return {
380
+ success: true,
381
+ customerId: params.userId
382
+ };
383
+ }
384
+ async getOrCreateCustomer(userId, _email) {
385
+ return {
386
+ success: true,
387
+ customerId: userId
388
+ };
389
+ }
390
+ // ==========================================================================
391
+ // Health & Security
392
+ // ==========================================================================
393
+ async getHealth() {
394
+ const start = Date.now();
395
+ try {
396
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
397
+ method: "POST",
398
+ headers: {
399
+ "Content-Type": "text/xml"
400
+ },
401
+ body: this.buildTestXML(),
402
+ signal: AbortSignal.timeout(5e3)
403
+ });
404
+ const healthy = response.ok;
405
+ return {
406
+ provider: "hyp",
407
+ healthy,
408
+ lastChecked: /* @__PURE__ */ new Date(),
409
+ avgLatencyMs: Date.now() - start,
410
+ circuitBreakerOpen: false
411
+ };
412
+ } catch {
413
+ return {
414
+ provider: "hyp",
415
+ healthy: false,
416
+ lastChecked: /* @__PURE__ */ new Date(),
417
+ circuitBreakerOpen: false
418
+ };
419
+ }
420
+ }
421
+ validateWebhookSignature(_payload, _signature) {
422
+ if (!this.config.webhookSecret) return false;
423
+ return !!this.config.webhookSecret;
424
+ }
425
+ async getPaymentIntentStatus(_providerIntentId) {
426
+ return {
427
+ status: "unknown",
428
+ error: "Status query not supported by Hyp basic integration"
429
+ };
430
+ }
431
+ // ==========================================================================
432
+ // XML Request Builders
433
+ // ==========================================================================
434
+ buildDoDealXML(request) {
435
+ const parts = [];
436
+ parts.push('<?xml version="1.0" encoding="utf-8"?>');
437
+ parts.push("<ashrait>");
438
+ parts.push("<request>");
439
+ parts.push(`<version>1000</version>`);
440
+ parts.push("<language>ENG</language>");
441
+ parts.push("<command>doDeal</command>");
442
+ parts.push(`<terminalNumber>${this.escapeXml(request.terminalNumber)}</terminalNumber>`);
443
+ parts.push(`<user>${this.escapeXml(request.user)}</user>`);
444
+ parts.push(`<password>${this.escapeXml(request.password)}</password>`);
445
+ if (request.cardNo) {
446
+ parts.push(`<cardNo>${this.escapeXml(request.cardNo)}</cardNo>`);
447
+ }
448
+ if (request.cardExpiration) {
449
+ parts.push(`<cardExpiration>${this.escapeXml(request.cardExpiration)}</cardExpiration>`);
450
+ }
451
+ if (request.cvv) {
452
+ parts.push(`<cvv>${this.escapeXml(request.cvv)}</cvv>`);
453
+ }
454
+ if (request.cardToken) {
455
+ parts.push(`<cardToken>${this.escapeXml(request.cardToken)}</cardToken>`);
456
+ }
457
+ if (request.authorizationCode) {
458
+ parts.push(`<authNumber>${this.escapeXml(request.authorizationCode)}</authNumber>`);
459
+ }
460
+ if (request.total !== void 0) {
461
+ parts.push(`<total>${request.total}</total>`);
462
+ }
463
+ parts.push(`<currency>${this.escapeXml(request.currency)}</currency>`);
464
+ parts.push(`<transactionType>${this.escapeXml(request.transactionType)}</transactionType>`);
465
+ if (request.transactionCode) {
466
+ parts.push(`<transactionCode>${this.escapeXml(request.transactionCode)}</transactionCode>`);
467
+ }
468
+ if (request.creditType) {
469
+ parts.push(`<creditType>${request.creditType}</creditType>`);
470
+ }
471
+ if (request.validation) {
472
+ parts.push(`<validation>${this.escapeXml(request.validation)}</validation>`);
473
+ }
474
+ if (request.uniqueid) {
475
+ parts.push(`<uniqueid>${this.escapeXml(request.uniqueid)}</uniqueid>`);
476
+ }
477
+ if (request.customerData) {
478
+ parts.push(`<customerData>${this.escapeXml(request.customerData)}</customerData>`);
479
+ }
480
+ if (request.successUrl) {
481
+ parts.push(`<successUrl>${this.escapeXml(request.successUrl)}</successUrl>`);
482
+ }
483
+ if (request.errorUrl) {
484
+ parts.push(`<errorUrl>${this.escapeXml(request.errorUrl)}</errorUrl>`);
485
+ }
486
+ if (request.cancelUrl) {
487
+ parts.push(`<cancelUrl>${this.escapeXml(request.cancelUrl)}</cancelUrl>`);
488
+ }
489
+ parts.push("</request>");
490
+ parts.push("</ashrait>");
491
+ return parts.join("");
492
+ }
493
+ buildRefundXML(request) {
494
+ const parts = [];
495
+ parts.push('<?xml version="1.0" encoding="utf-8"?>');
496
+ parts.push("<ashrait>");
497
+ parts.push("<request>");
498
+ parts.push(`<version>1000</version>`);
499
+ parts.push("<language>ENG</language>");
500
+ parts.push("<command>refundDeal</command>");
501
+ parts.push(`<terminalNumber>${this.escapeXml(request.terminalNumber)}</terminalNumber>`);
502
+ parts.push(`<user>${this.escapeXml(request.user)}</user>`);
503
+ parts.push(`<password>${this.escapeXml(request.password)}</password>`);
504
+ parts.push(`<transactionId>${this.escapeXml(request.transactionId)}</transactionId>`);
505
+ parts.push(`<currency>${this.escapeXml(request.currency)}</currency>`);
506
+ if (request.total !== void 0) {
507
+ parts.push(`<total>${request.total}</total>`);
508
+ }
509
+ if (request.uniqueid) {
510
+ parts.push(`<uniqueid>${this.escapeXml(request.uniqueid)}</uniqueid>`);
511
+ }
512
+ parts.push("</request>");
513
+ parts.push("</ashrait>");
514
+ return parts.join("");
515
+ }
516
+ buildTestXML() {
517
+ return `<?xml version="1.0" encoding="utf-8"?>
518
+ <ashrait>
519
+ <request>
520
+ <version>1000</version>
521
+ <language>ENG</language>
522
+ <command>echo</command>
523
+ </request>
524
+ </ashrait>`;
525
+ }
526
+ // ==========================================================================
527
+ // HTTP Helpers
528
+ // ==========================================================================
529
+ async sendDoDealRequest(request) {
530
+ const xmlBody = this.buildDoDealXML(request);
531
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
532
+ method: "POST",
533
+ headers: {
534
+ "Content-Type": "text/xml; charset=utf-8"
535
+ },
536
+ body: xmlBody
537
+ });
538
+ if (!response.ok) {
539
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
540
+ }
541
+ const xmlResponse = await response.text();
542
+ return this.parseDoDealResponse(xmlResponse);
543
+ }
544
+ async sendRefundRequest(request) {
545
+ const xmlBody = this.buildRefundXML(request);
546
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
547
+ method: "POST",
548
+ headers: {
549
+ "Content-Type": "text/xml; charset=utf-8"
550
+ },
551
+ body: xmlBody
552
+ });
553
+ if (!response.ok) {
554
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
555
+ }
556
+ const xmlResponse = await response.text();
557
+ return this.parseRefundResponse(xmlResponse);
558
+ }
559
+ // ==========================================================================
560
+ // XML Parsing
561
+ // ==========================================================================
562
+ parseDoDealResponse(xml) {
563
+ return {
564
+ resultCode: this.extractXmlValue(xml, "resultCode") ?? "100",
565
+ resultDescription: this.extractXmlValue(xml, "resultDescription"),
566
+ transactionId: this.extractXmlValue(xml, "transactionId"),
567
+ authorizationCode: this.extractXmlValue(xml, "authorizationCode"),
568
+ voucherNumber: this.extractXmlValue(xml, "voucherNumber"),
569
+ cardToken: this.extractXmlValue(xml, "cardToken"),
570
+ cardMask: this.extractXmlValue(xml, "cardMask"),
571
+ cardBrand: this.extractXmlValue(xml, "cardBrand"),
572
+ cardExpiration: this.extractXmlValue(xml, "cardExpiration"),
573
+ redirectUrl: this.extractXmlValue(xml, "redirectUrl"),
574
+ uniqueid: this.extractXmlValue(xml, "uniqueid"),
575
+ rawXml: xml
576
+ };
577
+ }
578
+ parseRefundResponse(xml) {
579
+ return {
580
+ resultCode: this.extractXmlValue(xml, "resultCode") ?? "100",
581
+ resultDescription: this.extractXmlValue(xml, "resultDescription"),
582
+ transactionId: this.extractXmlValue(xml, "transactionId"),
583
+ authorizationCode: this.extractXmlValue(xml, "authorizationCode"),
584
+ uniqueid: this.extractXmlValue(xml, "uniqueid")
585
+ };
586
+ }
587
+ extractXmlValue(xml, tagName) {
588
+ const regex = new RegExp(`<${tagName}>([^<]*)</${tagName}>`, "i");
589
+ const match = xml.match(regex);
590
+ return match ? match[1].trim() : void 0;
591
+ }
592
+ escapeXml(str) {
593
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
594
+ }
595
+ // ==========================================================================
596
+ // Error Handling
597
+ // ==========================================================================
598
+ handleError(error) {
599
+ if (error instanceof Error) {
600
+ return {
601
+ success: false,
602
+ error: error.message,
603
+ errorCode: "unknown"
604
+ };
605
+ }
606
+ return {
607
+ success: false,
608
+ error: "Unknown error occurred",
609
+ errorCode: "unknown"
610
+ };
611
+ }
612
+ };
613
+
614
+ // src/providers/cardcom/cardcom-provider.ts
615
+ import * as crypto from "crypto";
616
+ import { calculateCaptureDeadline as calculateCaptureDeadline2 } from "@nehorai/payments/types";
617
+
618
+ // src/providers/cardcom/cardcom-types.ts
619
+ var CARDCOM_API_BASE = "https://secure.cardcom.solutions";
620
+ var CARDCOM_ENDPOINTS = {
621
+ LOW_PROFILE_CREATE: "/api/v11/LowProfile/Create",
622
+ LOW_PROFILE_STATUS: "/Interface/BillGoldGetLowProfileIndicator.aspx",
623
+ DIRECT_CHARGE: "/api/v11/Transactions/Transaction",
624
+ REFUND: "/api/v11/Transactions/RefundByTransactionId"
625
+ };
626
+ var CARDCOM_SUPPORTED_CURRENCIES = ["ILS", "USD", "EUR", "GBP"];
627
+ var CARDCOM_WEBHOOK_EVENTS = [
628
+ "payment.completed",
629
+ "payment.declined",
630
+ "payment.authorized"
631
+ ];
632
+ var CARDCOM_DEAL_RESPONSE_ACTIONS = {
633
+ 0: "pending",
634
+ 1: "approved",
635
+ 2: "declined",
636
+ 3: "error"
637
+ };
638
+ function mapCardcomDealResponseToStatus(dealResponse) {
639
+ switch (dealResponse) {
640
+ case 0:
641
+ return "pending_authorization";
642
+ case 1:
643
+ return "captured";
644
+ case 2:
645
+ return "failed";
646
+ case 3:
647
+ return "failed";
648
+ default:
649
+ return "failed";
650
+ }
651
+ }
652
+ function mapCardcomError(responseCode) {
653
+ const errorMessages = {
654
+ 0: "Success",
655
+ 1: "General error",
656
+ 2: "Invalid API credentials",
657
+ 3: "Invalid terminal number",
658
+ 4: "Invalid operation type",
659
+ 5: "Invalid card details",
660
+ 6: "Card declined by issuer",
661
+ 7: "Insufficient funds",
662
+ 8: "Invalid amount",
663
+ 9: "Transaction not found",
664
+ 10: "Duplicate transaction",
665
+ 11: "Terminal not active",
666
+ 12: "CVV validation failed",
667
+ 13: "Card expired",
668
+ 14: "Invalid currency",
669
+ 15: "Operation not supported"
670
+ };
671
+ return errorMessages[responseCode] ?? `Error code ${responseCode}`;
672
+ }
673
+ var CARDCOM_CURRENCY_CODES = {
674
+ ILS: 1,
675
+ USD: 2,
676
+ EUR: 3,
677
+ GBP: 4
678
+ };
679
+ function getCurrencyCode(currency) {
680
+ return CARDCOM_CURRENCY_CODES[currency.toUpperCase()] ?? 1;
681
+ }
682
+
683
+ // src/providers/cardcom/cardcom-provider.ts
684
+ var CardcomProvider = class {
685
+ name = "cardcom";
686
+ supportedCurrencies = CARDCOM_SUPPORTED_CURRENCIES;
687
+ supportsRecurring = true;
688
+ supportsSplitPayments = false;
689
+ config;
690
+ constructor(config) {
691
+ if (!config.terminalNumber || !config.apiName || !config.apiPassword) {
692
+ throw new Error(
693
+ "CardcomProvider requires terminalNumber, apiName, and apiPassword in config"
694
+ );
695
+ }
696
+ this.config = config;
697
+ }
698
+ // ==========================================================================
699
+ // Payment Intent Operations
700
+ // ==========================================================================
701
+ async createPaymentIntent(params) {
702
+ try {
703
+ const amountMajor = params.amount.amountMinor / 100;
704
+ const operation = params.captureMethod === "manual" ? 4 /* SUSPEND_DEAL_ONLY */ : params.metadata?.savePaymentMethod ? 2 /* BILL_AND_CREATE_TOKEN */ : 1 /* BILL_ONLY */;
705
+ const request = {
706
+ TerminalNumber: this.config.terminalNumber,
707
+ ApiName: this.config.apiName,
708
+ ApiPassword: this.config.apiPassword,
709
+ Sum: amountMajor,
710
+ CoinID: getCurrencyCode(params.amount.currency),
711
+ Operation: operation,
712
+ Language: "en",
713
+ ReturnUrl: params.returnUrl,
714
+ ErrorUrl: params.returnUrl,
715
+ ProductName: params.description ?? "Payment",
716
+ InternalDealNumber: params.idempotencyKey,
717
+ SendEmail: false
718
+ };
719
+ if (params.metadata?.customerName) {
720
+ request.CustomerName = String(params.metadata.customerName);
721
+ }
722
+ if (params.metadata?.customerEmail) {
723
+ request.Email = String(params.metadata.customerEmail);
724
+ }
725
+ const response = await this.makeRequest(
726
+ CARDCOM_ENDPOINTS.LOW_PROFILE_CREATE,
727
+ request
728
+ );
729
+ if (response.ResponseCode !== 0 || !response.PaymentUrl) {
730
+ return {
731
+ success: false,
732
+ error: mapCardcomError(response.ResponseCode),
733
+ errorCode: String(response.ResponseCode)
734
+ };
735
+ }
736
+ return {
737
+ success: true,
738
+ providerIntentId: response.LowProfileCode,
739
+ redirectUrl: response.PaymentUrl,
740
+ status: "created"
741
+ };
742
+ } catch (error) {
743
+ return this.handleError(error);
744
+ }
745
+ }
746
+ async authorize(params) {
747
+ try {
748
+ const statusResponse = await this.getLowProfileStatus(
749
+ params.providerIntentId
750
+ );
751
+ if (!statusResponse.success || !statusResponse.data) {
752
+ return {
753
+ success: false,
754
+ error: statusResponse.error ?? "Failed to check payment status"
755
+ };
756
+ }
757
+ const status = statusResponse.data;
758
+ if (status.DealResponse === 1) {
759
+ return {
760
+ success: true,
761
+ authorizationCode: status.InternalDealNumber ?? params.providerIntentId,
762
+ status: "authorized",
763
+ captureDeadline: calculateCaptureDeadline2(/* @__PURE__ */ new Date())
764
+ };
765
+ }
766
+ if (status.DealResponse === 2) {
767
+ return {
768
+ success: false,
769
+ error: "Payment declined",
770
+ status: "failed"
771
+ };
772
+ }
773
+ return {
774
+ success: false,
775
+ error: "Payment not yet completed",
776
+ status: "pending_authorization"
777
+ };
778
+ } catch (error) {
779
+ return this.handleError(error);
780
+ }
781
+ }
782
+ async capture(params) {
783
+ try {
784
+ const statusResponse = await this.getLowProfileStatus(
785
+ params.providerIntentId
786
+ );
787
+ if (!statusResponse.success || !statusResponse.data) {
788
+ return {
789
+ success: false,
790
+ error: statusResponse.error ?? "Failed to capture payment"
791
+ };
792
+ }
793
+ const status = statusResponse.data;
794
+ if (status.DealResponse === 1) {
795
+ return {
796
+ success: true,
797
+ providerTransactionId: status.InternalDealNumber ?? params.providerIntentId,
798
+ status: "captured",
799
+ capturedAmount: {
800
+ amountMinor: Math.round((status.Amount ?? 0) * 100),
801
+ currency: status.Currency ?? params.amount?.currency ?? "ILS"
802
+ }
803
+ };
804
+ }
805
+ return {
806
+ success: false,
807
+ error: "Payment not authorized for capture",
808
+ status: mapCardcomDealResponseToStatus(status.DealResponse ?? 3)
809
+ };
810
+ } catch (error) {
811
+ return this.handleError(error);
812
+ }
813
+ }
814
+ async void(_params) {
815
+ return {
816
+ success: false,
817
+ error: "Void operation not supported via API. Please use Cardcom merchant dashboard."
818
+ };
819
+ }
820
+ async refund(params) {
821
+ try {
822
+ const refundAmount = params.amount ? params.amount.amountMinor / 100 : void 0;
823
+ if (!refundAmount) {
824
+ return {
825
+ success: false,
826
+ error: "Refund amount is required"
827
+ };
828
+ }
829
+ const request = {
830
+ TerminalNumber: this.config.terminalNumber,
831
+ ApiName: this.config.apiName,
832
+ ApiPassword: this.config.apiPassword,
833
+ InternalDealNumber: params.providerTransactionId,
834
+ Amount: refundAmount,
835
+ CoinID: params.amount ? getCurrencyCode(params.amount.currency) : 1
836
+ };
837
+ const response = await this.makeRequest(
838
+ CARDCOM_ENDPOINTS.REFUND,
839
+ request
840
+ );
841
+ if (response.ResponseCode !== 0) {
842
+ return {
843
+ success: false,
844
+ error: mapCardcomError(response.ResponseCode)
845
+ };
846
+ }
847
+ return {
848
+ success: true,
849
+ providerRefundId: response.InternalDealNumber ?? params.providerTransactionId,
850
+ refundedAmount: {
851
+ amountMinor: Math.round((response.Amount ?? 0) * 100),
852
+ currency: params.amount?.currency ?? "ILS"
853
+ },
854
+ status: "succeeded"
855
+ };
856
+ } catch (error) {
857
+ return this.handleError(error);
858
+ }
859
+ }
860
+ // ==========================================================================
861
+ // Payment Method Tokenization
862
+ // ==========================================================================
863
+ async createSetupIntent(params) {
864
+ try {
865
+ const request = {
866
+ TerminalNumber: this.config.terminalNumber,
867
+ ApiName: this.config.apiName,
868
+ ApiPassword: this.config.apiPassword,
869
+ Sum: 0,
870
+ Operation: 3 /* CREATE_TOKEN_ONLY */,
871
+ Language: "en",
872
+ InternalDealNumber: `setup_${params.userId}_${Date.now()}`
873
+ };
874
+ const response = await this.makeRequest(
875
+ CARDCOM_ENDPOINTS.LOW_PROFILE_CREATE,
876
+ request
877
+ );
878
+ if (response.ResponseCode !== 0 || !response.PaymentUrl) {
879
+ return {
880
+ success: false,
881
+ error: mapCardcomError(response.ResponseCode)
882
+ };
883
+ }
884
+ return {
885
+ success: true,
886
+ setupIntentId: response.LowProfileCode,
887
+ clientSecret: response.PaymentUrl
888
+ };
889
+ } catch (error) {
890
+ return this.handleError(error);
891
+ }
892
+ }
893
+ async savePaymentMethod(params) {
894
+ try {
895
+ const lowProfileCode = params.setupData.lowProfileCode;
896
+ if (!lowProfileCode) {
897
+ return {
898
+ success: false,
899
+ error: "Low profile code is required"
900
+ };
901
+ }
902
+ const statusResponse = await this.getLowProfileStatus(lowProfileCode);
903
+ if (!statusResponse.success || !statusResponse.data) {
904
+ return {
905
+ success: false,
906
+ error: statusResponse.error ?? "Failed to retrieve payment method"
907
+ };
908
+ }
909
+ const status = statusResponse.data;
910
+ if (!status.Token) {
911
+ return {
912
+ success: false,
913
+ error: "No token created"
914
+ };
915
+ }
916
+ const [expMonth, expYear] = (status.CardExpiration ?? "/").split("/");
917
+ return {
918
+ success: true,
919
+ paymentMethodId: status.Token,
920
+ cardBrand: status.CardType ?? "unknown",
921
+ cardLast4: status.CardMask?.slice(-4),
922
+ cardExpMonth: expMonth?.padStart(2, "0"),
923
+ cardExpYear: expYear ? `20${expYear}` : void 0,
924
+ cardBin: status.CardBin
925
+ };
926
+ } catch (error) {
927
+ return this.handleError(error);
928
+ }
929
+ }
930
+ async deletePaymentMethod(_paymentMethodId) {
931
+ return {
932
+ success: true
933
+ };
934
+ }
935
+ // ==========================================================================
936
+ // Customer Management
937
+ // ==========================================================================
938
+ async createCustomer(params) {
939
+ return {
940
+ success: true,
941
+ customerId: params.userId
942
+ };
943
+ }
944
+ async getOrCreateCustomer(userId, email) {
945
+ return this.createCustomer({ userId, email });
946
+ }
947
+ // ==========================================================================
948
+ // Health & Status
949
+ // ==========================================================================
950
+ async getHealth() {
951
+ const start = Date.now();
952
+ try {
953
+ const request = {
954
+ TerminalNumber: this.config.terminalNumber,
955
+ ApiName: this.config.apiName,
956
+ ApiPassword: this.config.apiPassword,
957
+ Sum: 1,
958
+ Operation: 1 /* BILL_ONLY */,
959
+ InternalDealNumber: `health_check_${Date.now()}`
960
+ };
961
+ const response = await this.makeRequest(
962
+ CARDCOM_ENDPOINTS.LOW_PROFILE_CREATE,
963
+ request
964
+ );
965
+ const healthy = response.ResponseCode === 0 || response.ResponseCode === 1;
966
+ return {
967
+ provider: "cardcom",
968
+ healthy,
969
+ lastChecked: /* @__PURE__ */ new Date(),
970
+ avgLatencyMs: Date.now() - start,
971
+ circuitBreakerOpen: false
972
+ };
973
+ } catch {
974
+ return {
975
+ provider: "cardcom",
976
+ healthy: false,
977
+ lastChecked: /* @__PURE__ */ new Date(),
978
+ circuitBreakerOpen: false
979
+ };
980
+ }
981
+ }
982
+ validateWebhookSignature(payload, signature) {
983
+ if (!this.config.webhookSecret) {
984
+ return false;
985
+ }
986
+ try {
987
+ const expectedSignature = crypto.createHmac("sha256", this.config.webhookSecret).update(payload).digest("hex");
988
+ return crypto.timingSafeEqual(
989
+ Buffer.from(signature),
990
+ Buffer.from(expectedSignature)
991
+ );
992
+ } catch {
993
+ return false;
994
+ }
995
+ }
996
+ async getPaymentIntentStatus(providerIntentId) {
997
+ try {
998
+ const result = await this.getLowProfileStatus(providerIntentId);
999
+ if (!result.success || !result.data) {
1000
+ return {
1001
+ status: "unknown",
1002
+ error: result.error
1003
+ };
1004
+ }
1005
+ const status = mapCardcomDealResponseToStatus(
1006
+ result.data.DealResponse ?? 0
1007
+ );
1008
+ return { status };
1009
+ } catch (error) {
1010
+ return {
1011
+ status: "unknown",
1012
+ error: error instanceof Error ? error.message : "Unknown error"
1013
+ };
1014
+ }
1015
+ }
1016
+ // ==========================================================================
1017
+ // Helper Methods
1018
+ // ==========================================================================
1019
+ async makeRequest(endpoint, data) {
1020
+ const url = `${CARDCOM_API_BASE}${endpoint}`;
1021
+ const response = await fetch(url, {
1022
+ method: "POST",
1023
+ headers: {
1024
+ "Content-Type": "application/json"
1025
+ },
1026
+ body: JSON.stringify(data)
1027
+ });
1028
+ if (!response.ok) {
1029
+ throw new Error(`Cardcom API error: ${response.status} ${response.statusText}`);
1030
+ }
1031
+ return response.json();
1032
+ }
1033
+ async getLowProfileStatus(lowProfileCode) {
1034
+ try {
1035
+ const params = new URLSearchParams({
1036
+ terminalnumber: this.config.terminalNumber,
1037
+ lowprofilecode: lowProfileCode,
1038
+ username: this.config.apiName
1039
+ });
1040
+ const url = `${CARDCOM_API_BASE}${CARDCOM_ENDPOINTS.LOW_PROFILE_STATUS}?${params}`;
1041
+ const response = await fetch(url, {
1042
+ method: "GET"
1043
+ });
1044
+ if (!response.ok) {
1045
+ return {
1046
+ success: false,
1047
+ error: `Status check failed: ${response.status}`
1048
+ };
1049
+ }
1050
+ const data = await response.json();
1051
+ if (data.ResponseCode !== 0) {
1052
+ return {
1053
+ success: false,
1054
+ error: mapCardcomError(data.ResponseCode)
1055
+ };
1056
+ }
1057
+ return { success: true, data };
1058
+ } catch (error) {
1059
+ return {
1060
+ success: false,
1061
+ error: error instanceof Error ? error.message : "Status check failed"
1062
+ };
1063
+ }
1064
+ }
1065
+ handleError(error) {
1066
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1067
+ return {
1068
+ success: false,
1069
+ error: errorMessage
1070
+ };
1071
+ }
1072
+ };
1073
+
1074
+ // src/providers/hyp/hyp-webhook-handler.ts
1075
+ var HYP_EVENT_TYPES = {
1076
+ TRANSACTION_SUCCESS: "transaction.success",
1077
+ TRANSACTION_FAILED: "transaction.failed",
1078
+ TRANSACTION_PENDING: "transaction.pending",
1079
+ REFUND_SUCCESS: "refund.success",
1080
+ REFUND_FAILED: "refund.failed"
1081
+ };
1082
+ var HypWebhookHandler = class {
1083
+ provider = "hyp";
1084
+ supportedEventTypes = Object.values(HYP_EVENT_TYPES);
1085
+ parseEvent(rawPayload) {
1086
+ try {
1087
+ const resultCode = String(rawPayload.resultCode ?? "100");
1088
+ const resultDescription = String(rawPayload.resultDescription ?? "");
1089
+ const transactionId = String(rawPayload.transactionId ?? "");
1090
+ const uniqueid = String(rawPayload.uniqueid ?? "");
1091
+ const total = Number(rawPayload.total ?? 0);
1092
+ const currency = String(rawPayload.currency ?? "ILS");
1093
+ const eventType = this.determineEventType(resultCode);
1094
+ const newStatus = mapHypStatus(resultCode);
1095
+ const event = {
1096
+ provider: "hyp",
1097
+ eventId: uniqueid || transactionId || `hyp_${Date.now()}`,
1098
+ eventType,
1099
+ providerTransactionId: transactionId,
1100
+ amountMinor: total,
1101
+ currency,
1102
+ newStatus: newStatus ?? void 0,
1103
+ error: isHypSuccess(resultCode) ? void 0 : {
1104
+ code: resultCode,
1105
+ message: resultDescription
1106
+ },
1107
+ timestamp: /* @__PURE__ */ new Date(),
1108
+ rawPayload
1109
+ };
1110
+ return {
1111
+ success: true,
1112
+ event
1113
+ };
1114
+ } catch (error) {
1115
+ return {
1116
+ success: false,
1117
+ error: error instanceof Error ? error.message : "Failed to parse webhook"
1118
+ };
1119
+ }
1120
+ }
1121
+ async processEvent(event) {
1122
+ try {
1123
+ if (!event.providerTransactionId) {
1124
+ return {
1125
+ success: false,
1126
+ error: "Missing transaction ID in webhook",
1127
+ action: "ignored_event_type"
1128
+ };
1129
+ }
1130
+ const action = this.determineAction(event);
1131
+ return {
1132
+ success: true,
1133
+ transactionId: event.providerTransactionId,
1134
+ action
1135
+ };
1136
+ } catch (error) {
1137
+ return {
1138
+ success: false,
1139
+ error: error instanceof Error ? error.message : "Processing failed",
1140
+ action: "ignored_event_type"
1141
+ };
1142
+ }
1143
+ }
1144
+ canHandle(eventType) {
1145
+ return this.supportedEventTypes.includes(
1146
+ eventType
1147
+ );
1148
+ }
1149
+ async reconcile(_transactionId, _providerTransactionId) {
1150
+ return {
1151
+ reconciled: false,
1152
+ finalStatus: "pending_authorization",
1153
+ source: "webhook",
1154
+ statusChanged: false
1155
+ };
1156
+ }
1157
+ mapEventType(providerEventType) {
1158
+ return providerEventType;
1159
+ }
1160
+ mapStatus(providerStatus) {
1161
+ return mapHypStatus(providerStatus);
1162
+ }
1163
+ // ==========================================================================
1164
+ // Helper Methods
1165
+ // ==========================================================================
1166
+ determineEventType(resultCode) {
1167
+ if (isHypSuccess(resultCode)) {
1168
+ return HYP_EVENT_TYPES.TRANSACTION_SUCCESS;
1169
+ }
1170
+ if (resultCode === "200") {
1171
+ return HYP_EVENT_TYPES.TRANSACTION_PENDING;
1172
+ }
1173
+ return HYP_EVENT_TYPES.TRANSACTION_FAILED;
1174
+ }
1175
+ determineAction(event) {
1176
+ switch (event.eventType) {
1177
+ case HYP_EVENT_TYPES.TRANSACTION_SUCCESS:
1178
+ case HYP_EVENT_TYPES.TRANSACTION_FAILED:
1179
+ case HYP_EVENT_TYPES.TRANSACTION_PENDING:
1180
+ case HYP_EVENT_TYPES.REFUND_FAILED:
1181
+ return "status_updated";
1182
+ case HYP_EVENT_TYPES.REFUND_SUCCESS:
1183
+ return "refund_processed";
1184
+ default:
1185
+ return "ignored_event_type";
1186
+ }
1187
+ }
1188
+ // ==========================================================================
1189
+ // Webhook Validation
1190
+ // ==========================================================================
1191
+ validateSignature(payload, signature, secret) {
1192
+ const hasRequiredParams = payload.resultCode !== void 0 && (payload.transactionId !== void 0 || payload.uniqueid !== void 0);
1193
+ if (!hasRequiredParams) {
1194
+ return false;
1195
+ }
1196
+ if (secret && signature) {
1197
+ return this.validateHMAC(payload, signature, secret);
1198
+ }
1199
+ return hasRequiredParams;
1200
+ }
1201
+ validateHMAC(_payload, signature, _secret) {
1202
+ try {
1203
+ return !!signature;
1204
+ } catch {
1205
+ return false;
1206
+ }
1207
+ }
1208
+ // ==========================================================================
1209
+ // Callback URL Builders
1210
+ // ==========================================================================
1211
+ buildSuccessUrl(baseUrl, transactionId) {
1212
+ return `${baseUrl}/api/payments/hyp/callback?status=success&txId=${transactionId}`;
1213
+ }
1214
+ buildErrorUrl(baseUrl, transactionId) {
1215
+ return `${baseUrl}/api/payments/hyp/callback?status=error&txId=${transactionId}`;
1216
+ }
1217
+ buildCancelUrl(baseUrl, transactionId) {
1218
+ return `${baseUrl}/api/payments/hyp/callback?status=cancel&txId=${transactionId}`;
1219
+ }
1220
+ // ==========================================================================
1221
+ // Response Parsing
1222
+ // ==========================================================================
1223
+ extractErrorDetails(payload) {
1224
+ const resultCode = String(payload.resultCode ?? "unknown");
1225
+ const resultDescription = String(payload.resultDescription ?? "Unknown error");
1226
+ return {
1227
+ code: resultCode,
1228
+ message: resultDescription,
1229
+ userMessage: this.getUserFriendlyMessage(resultCode)
1230
+ };
1231
+ }
1232
+ getUserFriendlyMessage(resultCode) {
1233
+ const errorCode = mapHypError(resultCode);
1234
+ const messages = {
1235
+ card_declined: "Your card was declined. Please try another payment method.",
1236
+ invalid_card: "The card information is invalid. Please check and try again.",
1237
+ expired_card: "Your card has expired. Please use a different card.",
1238
+ insufficient_funds: "Insufficient funds. Please try another payment method.",
1239
+ invalid_cvc: "The security code (CVV) is incorrect.",
1240
+ processing_error: "A processing error occurred. Please try again.",
1241
+ authentication_required: "Additional authentication is required. Please complete the verification.",
1242
+ unknown: "An error occurred. Please try again or contact support."
1243
+ };
1244
+ return messages[errorCode] ?? messages.unknown;
1245
+ }
1246
+ extractCardDetails(payload) {
1247
+ const cardToken = payload.cardToken;
1248
+ const cardMask = payload.cardMask;
1249
+ const cardBrand = payload.cardBrand;
1250
+ const cardExpiration = payload.cardExpiration;
1251
+ return {
1252
+ cardToken,
1253
+ cardMask,
1254
+ cardBrand,
1255
+ cardExpiration,
1256
+ last4: cardMask?.slice(-4)
1257
+ };
1258
+ }
1259
+ };
1260
+
1261
+ // src/providers/cardcom/cardcom-webhook-handler.ts
1262
+ var CardcomWebhookHandler = class {
1263
+ provider = "cardcom";
1264
+ supportedEventTypes = CARDCOM_WEBHOOK_EVENTS;
1265
+ parseEvent(rawPayload) {
1266
+ try {
1267
+ const params = rawPayload;
1268
+ const responseCode = parseInt(params.ResponseCode ?? "1", 10);
1269
+ const dealResponse = parseInt(params.DealResponse ?? "0", 10);
1270
+ const lowProfileCode = params.LowProfileCode ?? "";
1271
+ const internalDealNumber = params.InternalDealNumber ?? "";
1272
+ if (!lowProfileCode && !internalDealNumber) {
1273
+ return {
1274
+ success: false,
1275
+ error: "Missing LowProfileCode or InternalDealNumber in callback"
1276
+ };
1277
+ }
1278
+ let eventType;
1279
+ if (dealResponse === 1) {
1280
+ eventType = "payment.completed";
1281
+ } else if (dealResponse === 2) {
1282
+ eventType = "payment.declined";
1283
+ } else if (dealResponse === 0 && responseCode === 0) {
1284
+ eventType = "payment.authorized";
1285
+ } else {
1286
+ eventType = "payment.declined";
1287
+ }
1288
+ const status = mapCardcomDealResponseToStatus(dealResponse);
1289
+ const amountString = params.Amount ?? "0";
1290
+ const amountMajor = parseFloat(amountString);
1291
+ const amountMinor = Math.round(amountMajor * 100);
1292
+ const parsed = {
1293
+ provider: "cardcom",
1294
+ eventId: `${lowProfileCode}_${internalDealNumber}_${Date.now()}`,
1295
+ eventType,
1296
+ providerTransactionId: internalDealNumber || lowProfileCode,
1297
+ timestamp: /* @__PURE__ */ new Date(),
1298
+ rawPayload,
1299
+ newStatus: status,
1300
+ amountMinor,
1301
+ currency: params.Currency ?? "ILS"
1302
+ };
1303
+ if (dealResponse === 2 || responseCode !== 0) {
1304
+ parsed.error = {
1305
+ code: String(responseCode),
1306
+ message: CARDCOM_DEAL_RESPONSE_ACTIONS[dealResponse] ?? "Payment failed"
1307
+ };
1308
+ }
1309
+ return { success: true, event: parsed };
1310
+ } catch (error) {
1311
+ return {
1312
+ success: false,
1313
+ error: error instanceof Error ? error.message : "Parse error"
1314
+ };
1315
+ }
1316
+ }
1317
+ async processEvent(event) {
1318
+ const action = this.getActionForEvent(event.eventType);
1319
+ if (action === "ignored") {
1320
+ return {
1321
+ success: true,
1322
+ action: "ignored_event_type"
1323
+ };
1324
+ }
1325
+ return {
1326
+ success: true,
1327
+ transactionId: event.providerTransactionId,
1328
+ action: "status_updated"
1329
+ };
1330
+ }
1331
+ canHandle(eventType) {
1332
+ return this.supportedEventTypes.includes(
1333
+ eventType
1334
+ );
1335
+ }
1336
+ async reconcile(_transactionId, _providerTransactionId) {
1337
+ return {
1338
+ reconciled: false,
1339
+ finalStatus: "created",
1340
+ source: "provider_query",
1341
+ statusChanged: false
1342
+ };
1343
+ }
1344
+ mapEventType(providerEventType) {
1345
+ return providerEventType;
1346
+ }
1347
+ mapStatus(providerStatus) {
1348
+ const dealResponse = parseInt(providerStatus, 10);
1349
+ if (isNaN(dealResponse)) {
1350
+ return null;
1351
+ }
1352
+ return mapCardcomDealResponseToStatus(dealResponse);
1353
+ }
1354
+ getActionForEvent(eventType) {
1355
+ switch (eventType) {
1356
+ case "payment.completed":
1357
+ case "payment.declined":
1358
+ case "payment.authorized":
1359
+ return "status_update";
1360
+ default:
1361
+ return "ignored";
1362
+ }
1363
+ }
1364
+ };
1365
+
1366
+ // src/factory.ts
1367
+ function addIsraeliProviders(services, config) {
1368
+ if (config.hyp) {
1369
+ services.providers.set("hyp", new HypProvider(config.hyp));
1370
+ services.webhookHandlers.set("hyp", new HypWebhookHandler());
1371
+ }
1372
+ if (config.cardcom) {
1373
+ services.providers.set("cardcom", new CardcomProvider(config.cardcom));
1374
+ services.webhookHandlers.set("cardcom", new CardcomWebhookHandler());
1375
+ }
1376
+ return services;
1377
+ }
1378
+ export {
1379
+ addIsraeliProviders
1380
+ };
1381
+ //# sourceMappingURL=factory.js.map