@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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1724 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ CARDCOM_API_BASE: () => CARDCOM_API_BASE,
34
+ CARDCOM_CURRENCY_CODES: () => CARDCOM_CURRENCY_CODES,
35
+ CARDCOM_DEAL_RESPONSE_ACTIONS: () => CARDCOM_DEAL_RESPONSE_ACTIONS,
36
+ CARDCOM_ENDPOINTS: () => CARDCOM_ENDPOINTS,
37
+ CARDCOM_LANGUAGE_CODES: () => CARDCOM_LANGUAGE_CODES,
38
+ CARDCOM_RESPONSE_CODE_MAP: () => CARDCOM_RESPONSE_CODE_MAP,
39
+ CARDCOM_SUPPORTED_CURRENCIES: () => CARDCOM_SUPPORTED_CURRENCIES,
40
+ CARDCOM_WEBHOOK_EVENTS: () => CARDCOM_WEBHOOK_EVENTS,
41
+ CardcomOperation: () => CardcomOperation,
42
+ CardcomProvider: () => CardcomProvider,
43
+ CardcomTransactionType: () => CardcomTransactionType,
44
+ CardcomWebhookHandler: () => CardcomWebhookHandler,
45
+ DEFAULT_HYP_ENDPOINTS: () => DEFAULT_HYP_ENDPOINTS,
46
+ HYP_CREDIT_TYPES: () => HYP_CREDIT_TYPES,
47
+ HYP_ERROR_MAP: () => HYP_ERROR_MAP,
48
+ HYP_RESULT_CODE_MAP: () => HYP_RESULT_CODE_MAP,
49
+ HYP_SUPPORTED_CURRENCIES: () => HYP_SUPPORTED_CURRENCIES,
50
+ HYP_TRANSACTION_CODES: () => HYP_TRANSACTION_CODES,
51
+ HYP_TRANSACTION_TYPES: () => HYP_TRANSACTION_TYPES,
52
+ HYP_VALIDATION_MODES: () => HYP_VALIDATION_MODES,
53
+ HypProvider: () => HypProvider,
54
+ HypWebhookHandler: () => HypWebhookHandler,
55
+ ISRAELI_BIN_RANGES: () => ISRAELI_BIN_RANGES,
56
+ ISRAELI_ROUTING_RULES: () => ISRAELI_ROUTING_RULES,
57
+ addIsraeliProviders: () => addIsraeliProviders,
58
+ createHypWebhookHandler: () => createHypWebhookHandler,
59
+ formatCardExpiration: () => formatCardExpiration,
60
+ formatHypAmount: () => formatHypAmount,
61
+ getCardIssuer: () => getCardIssuer,
62
+ getCardcomCallbackError: () => getCardcomCallbackError,
63
+ getCurrencyCode: () => getCurrencyCode,
64
+ getFallbackProviders: () => getFallbackProviders,
65
+ getOptimalProvider: () => getOptimalProvider,
66
+ getProviderFeePercent: () => getProviderFeePercent,
67
+ isCardcomCallbackAuthorized: () => isCardcomCallbackAuthorized,
68
+ isCardcomCallbackSuccess: () => isCardcomCallbackSuccess,
69
+ isHypSuccess: () => isHypSuccess,
70
+ isHypSupportedCurrency: () => isHypSupportedCurrency,
71
+ isIsraeliCard: () => isIsraeliCard,
72
+ mapCardcomDealResponseToStatus: () => mapCardcomDealResponseToStatus,
73
+ mapCardcomError: () => mapCardcomError,
74
+ mapHypError: () => mapHypError,
75
+ mapHypStatus: () => mapHypStatus,
76
+ parseCardExpiration: () => parseCardExpiration,
77
+ parseCardcomCallbackUrl: () => parseCardcomCallbackUrl,
78
+ validateCardcomCallback: () => validateCardcomCallback
79
+ });
80
+ module.exports = __toCommonJS(src_exports);
81
+
82
+ // src/providers/hyp/hyp-provider.ts
83
+ var import_types = require("@nehorai/payments/types");
84
+
85
+ // src/providers/hyp/hyp-types.ts
86
+ var DEFAULT_HYP_ENDPOINTS = {
87
+ test: "https://cguat2.creditguard.co.il",
88
+ production: "https://cgpay3.creditguard.co.il"
89
+ };
90
+ var HYP_SUPPORTED_CURRENCIES = [
91
+ "ILS",
92
+ // Israeli Shekel (primary)
93
+ "USD",
94
+ // US Dollar
95
+ "EUR",
96
+ // Euro
97
+ "GBP"
98
+ // British Pound
99
+ ];
100
+ var HYP_RESULT_CODE_MAP = {
101
+ "000": "captured",
102
+ // Success
103
+ "001": "failed",
104
+ // Declined
105
+ "002": "failed",
106
+ // Invalid card
107
+ "003": "failed",
108
+ // Expired card
109
+ "004": "failed",
110
+ // Insufficient funds
111
+ "005": "failed",
112
+ // Invalid CVV
113
+ "006": "failed",
114
+ // Card not permitted
115
+ "033": "failed",
116
+ // Lost/Stolen card
117
+ "034": "failed",
118
+ // Suspected fraud
119
+ "051": "failed",
120
+ // Insufficient funds
121
+ "054": "failed",
122
+ // Expired card
123
+ "057": "failed",
124
+ // Transaction not permitted
125
+ "100": "failed",
126
+ // System error
127
+ "200": "pending_authorization"
128
+ // Pending
129
+ };
130
+ var HYP_TRANSACTION_TYPES = {
131
+ /** Regular charge (immediate capture) */
132
+ DEBIT: "Debit",
133
+ /** Refund */
134
+ CREDIT: "Credit",
135
+ /** Authorization only (J5) */
136
+ DEBIT_J5: "Debit"
137
+ };
138
+ var HYP_TRANSACTION_CODES = {
139
+ /** Regular transaction */
140
+ REGULAR: "Regular",
141
+ /** Verify only (authorization) */
142
+ VERIFY: "Verify",
143
+ /** Force transaction */
144
+ FORCE: "Force"
145
+ };
146
+ var HYP_VALIDATION_MODES = {
147
+ /** Auto commit (immediate capture) */
148
+ AUTO_COMM: "AutoComm",
149
+ /** Transaction only (authorization, requires manual capture) */
150
+ TX_ONLY: "TxOnly"
151
+ };
152
+ var HYP_CREDIT_TYPES = {
153
+ /** Regular credit card */
154
+ REGULAR: "1",
155
+ /** Token/Saved card */
156
+ TOKEN: "8"
157
+ };
158
+ var HYP_ERROR_MAP = {
159
+ "001": "card_declined",
160
+ "002": "invalid_card",
161
+ "003": "expired_card",
162
+ "004": "insufficient_funds",
163
+ "005": "invalid_cvc",
164
+ "006": "card_declined",
165
+ "033": "card_declined",
166
+ "034": "card_declined",
167
+ "051": "insufficient_funds",
168
+ "054": "expired_card",
169
+ "057": "card_declined",
170
+ "100": "processing_error",
171
+ "200": "authentication_required"
172
+ };
173
+ function mapHypStatus(resultCode) {
174
+ return HYP_RESULT_CODE_MAP[resultCode] ?? null;
175
+ }
176
+ function mapHypError(resultCode) {
177
+ return HYP_ERROR_MAP[resultCode] ?? "unknown";
178
+ }
179
+ function isHypSupportedCurrency(currency) {
180
+ return HYP_SUPPORTED_CURRENCIES.includes(
181
+ currency
182
+ );
183
+ }
184
+ function isHypSuccess(resultCode) {
185
+ return resultCode === "000";
186
+ }
187
+ function formatHypAmount(amountMinor) {
188
+ return amountMinor;
189
+ }
190
+ function formatCardExpiration(month, year) {
191
+ const mm = month.padStart(2, "0");
192
+ const yy = year.slice(-2);
193
+ return `${mm}${yy}`;
194
+ }
195
+ function parseCardExpiration(expiration) {
196
+ const mm = expiration.substring(0, 2);
197
+ const yy = expiration.substring(2, 4);
198
+ return {
199
+ month: mm,
200
+ year: `20${yy}`
201
+ };
202
+ }
203
+
204
+ // src/providers/hyp/hyp-provider.ts
205
+ var HypProvider = class {
206
+ name = "hyp";
207
+ supportedCurrencies = HYP_SUPPORTED_CURRENCIES;
208
+ supportsRecurring = true;
209
+ supportsSplitPayments = false;
210
+ config;
211
+ constructor(config) {
212
+ if (!config.terminalNumber || !config.user || !config.password) {
213
+ throw new Error(
214
+ "HypProvider requires terminalNumber, user, and password in config"
215
+ );
216
+ }
217
+ const baseUrl = config.baseUrl ?? (config.environment === "production" ? DEFAULT_HYP_ENDPOINTS.production : DEFAULT_HYP_ENDPOINTS.test);
218
+ this.config = { ...config, baseUrl };
219
+ }
220
+ // ==========================================================================
221
+ // Payment Intent Operations
222
+ // ==========================================================================
223
+ /**
224
+ * Create a payment intent
225
+ *
226
+ * For Hyp, this generates a hosted payment page or prepares for direct charge.
227
+ */
228
+ async createPaymentIntent(params) {
229
+ try {
230
+ if (!params.paymentMethodId) {
231
+ return await this.createHostedPage(params);
232
+ }
233
+ return await this.chargeWithToken(params);
234
+ } catch (error) {
235
+ return this.handleError(error);
236
+ }
237
+ }
238
+ /**
239
+ * Create hosted payment page
240
+ */
241
+ async createHostedPage(params) {
242
+ const uniqueid = params.idempotencyKey;
243
+ const request = {
244
+ terminalNumber: this.config.terminalNumber,
245
+ user: this.config.user,
246
+ password: this.config.password,
247
+ total: formatHypAmount(params.amount.amountMinor),
248
+ currency: params.amount.currency,
249
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
250
+ transactionCode: params.captureMethod === "manual" ? HYP_TRANSACTION_CODES.VERIFY : HYP_TRANSACTION_CODES.REGULAR,
251
+ validation: params.captureMethod === "manual" ? HYP_VALIDATION_MODES.TX_ONLY : HYP_VALIDATION_MODES.AUTO_COMM,
252
+ uniqueid,
253
+ successUrl: params.returnUrl,
254
+ errorUrl: params.returnUrl,
255
+ cancelUrl: params.returnUrl,
256
+ language: "en"
257
+ };
258
+ const response = await this.sendDoDealRequest(request);
259
+ if (!isHypSuccess(response.resultCode)) {
260
+ return {
261
+ success: false,
262
+ error: response.resultDescription ?? "Transaction failed",
263
+ errorCode: mapHypError(response.resultCode)
264
+ };
265
+ }
266
+ return {
267
+ success: true,
268
+ providerIntentId: response.transactionId ?? uniqueid,
269
+ redirectUrl: response.redirectUrl,
270
+ status: "created"
271
+ };
272
+ }
273
+ /**
274
+ * Charge with saved payment method token
275
+ */
276
+ async chargeWithToken(params) {
277
+ const uniqueid = params.idempotencyKey;
278
+ const request = {
279
+ terminalNumber: this.config.terminalNumber,
280
+ user: this.config.user,
281
+ password: this.config.password,
282
+ total: formatHypAmount(params.amount.amountMinor),
283
+ currency: params.amount.currency,
284
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
285
+ transactionCode: params.captureMethod === "manual" ? HYP_TRANSACTION_CODES.VERIFY : HYP_TRANSACTION_CODES.REGULAR,
286
+ validation: params.captureMethod === "manual" ? HYP_VALIDATION_MODES.TX_ONLY : HYP_VALIDATION_MODES.AUTO_COMM,
287
+ creditType: HYP_CREDIT_TYPES.TOKEN,
288
+ cardToken: params.paymentMethodId,
289
+ uniqueid
290
+ };
291
+ const response = await this.sendDoDealRequest(request);
292
+ if (!isHypSuccess(response.resultCode)) {
293
+ return {
294
+ success: false,
295
+ error: response.resultDescription ?? "Transaction failed",
296
+ errorCode: mapHypError(response.resultCode)
297
+ };
298
+ }
299
+ const status = mapHypStatus(response.resultCode) ?? "created";
300
+ return {
301
+ success: true,
302
+ providerIntentId: response.transactionId ?? uniqueid,
303
+ status
304
+ };
305
+ }
306
+ async authorize(params) {
307
+ try {
308
+ return {
309
+ success: true,
310
+ authorizationCode: params.providerIntentId,
311
+ status: "authorized",
312
+ captureDeadline: (0, import_types.calculateCaptureDeadline)(/* @__PURE__ */ new Date())
313
+ };
314
+ } catch (error) {
315
+ return this.handleError(error);
316
+ }
317
+ }
318
+ async capture(params) {
319
+ try {
320
+ const request = {
321
+ terminalNumber: this.config.terminalNumber,
322
+ user: this.config.user,
323
+ password: this.config.password,
324
+ total: params.amount ? formatHypAmount(params.amount.amountMinor) : void 0,
325
+ currency: params.amount?.currency ?? "ILS",
326
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
327
+ transactionCode: HYP_TRANSACTION_CODES.FORCE,
328
+ validation: HYP_VALIDATION_MODES.AUTO_COMM,
329
+ uniqueid: params.idempotencyKey,
330
+ authorizationCode: params.providerIntentId
331
+ };
332
+ const response = await this.sendDoDealRequest(request);
333
+ if (!isHypSuccess(response.resultCode)) {
334
+ return {
335
+ success: false,
336
+ error: response.resultDescription ?? "Capture failed",
337
+ errorCode: mapHypError(response.resultCode)
338
+ };
339
+ }
340
+ return {
341
+ success: true,
342
+ providerTransactionId: response.transactionId ?? params.providerIntentId,
343
+ status: "captured",
344
+ capturedAmount: params.amount ?? {
345
+ amountMinor: 0,
346
+ currency: "ILS"
347
+ }
348
+ };
349
+ } catch (error) {
350
+ return this.handleError(error);
351
+ }
352
+ }
353
+ async void(params) {
354
+ try {
355
+ const request = {
356
+ terminalNumber: this.config.terminalNumber,
357
+ user: this.config.user,
358
+ password: this.config.password,
359
+ transactionId: params.providerIntentId,
360
+ currency: "ILS",
361
+ uniqueid: params.providerIntentId
362
+ };
363
+ const response = await this.sendRefundRequest(request);
364
+ if (!isHypSuccess(response.resultCode)) {
365
+ return {
366
+ success: false,
367
+ error: response.resultDescription ?? "Void failed"
368
+ };
369
+ }
370
+ return { success: true, status: "voided" };
371
+ } catch (error) {
372
+ return this.handleError(error);
373
+ }
374
+ }
375
+ // ==========================================================================
376
+ // Refunds
377
+ // ==========================================================================
378
+ async refund(params) {
379
+ try {
380
+ const request = {
381
+ terminalNumber: this.config.terminalNumber,
382
+ user: this.config.user,
383
+ password: this.config.password,
384
+ transactionId: params.providerTransactionId,
385
+ total: params.amount ? formatHypAmount(params.amount.amountMinor) : void 0,
386
+ currency: params.amount?.currency ?? "ILS",
387
+ uniqueid: params.idempotencyKey
388
+ };
389
+ const response = await this.sendRefundRequest(request);
390
+ if (!isHypSuccess(response.resultCode)) {
391
+ return {
392
+ success: false,
393
+ error: response.resultDescription ?? "Refund failed"
394
+ };
395
+ }
396
+ return {
397
+ success: true,
398
+ providerRefundId: response.transactionId ?? params.idempotencyKey,
399
+ refundedAmount: params.amount ?? {
400
+ amountMinor: 0,
401
+ currency: "ILS"
402
+ },
403
+ status: "succeeded"
404
+ };
405
+ } catch (error) {
406
+ return this.handleError(error);
407
+ }
408
+ }
409
+ // ==========================================================================
410
+ // Payment Methods (Tokenization)
411
+ // ==========================================================================
412
+ async createSetupIntent(params) {
413
+ try {
414
+ const uniqueid = `setup_${params.userId}_${Date.now()}`;
415
+ const request = {
416
+ terminalNumber: this.config.terminalNumber,
417
+ user: this.config.user,
418
+ password: this.config.password,
419
+ total: 0,
420
+ currency: "ILS",
421
+ transactionType: HYP_TRANSACTION_TYPES.DEBIT,
422
+ transactionCode: HYP_TRANSACTION_CODES.VERIFY,
423
+ validation: HYP_VALIDATION_MODES.TX_ONLY,
424
+ creditType: HYP_CREDIT_TYPES.TOKEN,
425
+ customerData: params.customerId ?? params.userId,
426
+ uniqueid,
427
+ language: "en"
428
+ };
429
+ const response = await this.sendDoDealRequest(request);
430
+ if (!isHypSuccess(response.resultCode)) {
431
+ return {
432
+ success: false,
433
+ error: response.resultDescription ?? "Setup failed"
434
+ };
435
+ }
436
+ return {
437
+ success: true,
438
+ setupIntentId: response.transactionId ?? uniqueid,
439
+ clientSecret: response.redirectUrl
440
+ };
441
+ } catch (error) {
442
+ return this.handleError(error);
443
+ }
444
+ }
445
+ async savePaymentMethod(params) {
446
+ try {
447
+ const cardToken = params.setupData.cardToken;
448
+ const cardMask = params.setupData.cardMask;
449
+ const cardBrand = params.setupData.cardBrand;
450
+ const cardExpiration = params.setupData.cardExpiration;
451
+ if (!cardToken) {
452
+ return {
453
+ success: false,
454
+ error: "No card token received"
455
+ };
456
+ }
457
+ return {
458
+ success: true,
459
+ paymentMethodId: cardToken,
460
+ cardBrand: cardBrand ?? "unknown",
461
+ cardLast4: cardMask?.slice(-4) ?? "0000",
462
+ cardExpMonth: cardExpiration?.substring(0, 2) ?? "01",
463
+ cardExpYear: `20${cardExpiration?.substring(2, 4) ?? "99"}`
464
+ };
465
+ } catch (error) {
466
+ return this.handleError(error);
467
+ }
468
+ }
469
+ async deletePaymentMethod(_paymentMethodId) {
470
+ return {
471
+ success: true
472
+ };
473
+ }
474
+ // ==========================================================================
475
+ // Customer Management
476
+ // ==========================================================================
477
+ async createCustomer(params) {
478
+ return {
479
+ success: true,
480
+ customerId: params.userId
481
+ };
482
+ }
483
+ async getOrCreateCustomer(userId, _email) {
484
+ return {
485
+ success: true,
486
+ customerId: userId
487
+ };
488
+ }
489
+ // ==========================================================================
490
+ // Health & Security
491
+ // ==========================================================================
492
+ async getHealth() {
493
+ const start = Date.now();
494
+ try {
495
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
496
+ method: "POST",
497
+ headers: {
498
+ "Content-Type": "text/xml"
499
+ },
500
+ body: this.buildTestXML(),
501
+ signal: AbortSignal.timeout(5e3)
502
+ });
503
+ const healthy = response.ok;
504
+ return {
505
+ provider: "hyp",
506
+ healthy,
507
+ lastChecked: /* @__PURE__ */ new Date(),
508
+ avgLatencyMs: Date.now() - start,
509
+ circuitBreakerOpen: false
510
+ };
511
+ } catch {
512
+ return {
513
+ provider: "hyp",
514
+ healthy: false,
515
+ lastChecked: /* @__PURE__ */ new Date(),
516
+ circuitBreakerOpen: false
517
+ };
518
+ }
519
+ }
520
+ validateWebhookSignature(_payload, _signature) {
521
+ if (!this.config.webhookSecret) return false;
522
+ return !!this.config.webhookSecret;
523
+ }
524
+ async getPaymentIntentStatus(_providerIntentId) {
525
+ return {
526
+ status: "unknown",
527
+ error: "Status query not supported by Hyp basic integration"
528
+ };
529
+ }
530
+ // ==========================================================================
531
+ // XML Request Builders
532
+ // ==========================================================================
533
+ buildDoDealXML(request) {
534
+ const parts = [];
535
+ parts.push('<?xml version="1.0" encoding="utf-8"?>');
536
+ parts.push("<ashrait>");
537
+ parts.push("<request>");
538
+ parts.push(`<version>1000</version>`);
539
+ parts.push("<language>ENG</language>");
540
+ parts.push("<command>doDeal</command>");
541
+ parts.push(`<terminalNumber>${this.escapeXml(request.terminalNumber)}</terminalNumber>`);
542
+ parts.push(`<user>${this.escapeXml(request.user)}</user>`);
543
+ parts.push(`<password>${this.escapeXml(request.password)}</password>`);
544
+ if (request.cardNo) {
545
+ parts.push(`<cardNo>${this.escapeXml(request.cardNo)}</cardNo>`);
546
+ }
547
+ if (request.cardExpiration) {
548
+ parts.push(`<cardExpiration>${this.escapeXml(request.cardExpiration)}</cardExpiration>`);
549
+ }
550
+ if (request.cvv) {
551
+ parts.push(`<cvv>${this.escapeXml(request.cvv)}</cvv>`);
552
+ }
553
+ if (request.cardToken) {
554
+ parts.push(`<cardToken>${this.escapeXml(request.cardToken)}</cardToken>`);
555
+ }
556
+ if (request.authorizationCode) {
557
+ parts.push(`<authNumber>${this.escapeXml(request.authorizationCode)}</authNumber>`);
558
+ }
559
+ if (request.total !== void 0) {
560
+ parts.push(`<total>${request.total}</total>`);
561
+ }
562
+ parts.push(`<currency>${this.escapeXml(request.currency)}</currency>`);
563
+ parts.push(`<transactionType>${this.escapeXml(request.transactionType)}</transactionType>`);
564
+ if (request.transactionCode) {
565
+ parts.push(`<transactionCode>${this.escapeXml(request.transactionCode)}</transactionCode>`);
566
+ }
567
+ if (request.creditType) {
568
+ parts.push(`<creditType>${request.creditType}</creditType>`);
569
+ }
570
+ if (request.validation) {
571
+ parts.push(`<validation>${this.escapeXml(request.validation)}</validation>`);
572
+ }
573
+ if (request.uniqueid) {
574
+ parts.push(`<uniqueid>${this.escapeXml(request.uniqueid)}</uniqueid>`);
575
+ }
576
+ if (request.customerData) {
577
+ parts.push(`<customerData>${this.escapeXml(request.customerData)}</customerData>`);
578
+ }
579
+ if (request.successUrl) {
580
+ parts.push(`<successUrl>${this.escapeXml(request.successUrl)}</successUrl>`);
581
+ }
582
+ if (request.errorUrl) {
583
+ parts.push(`<errorUrl>${this.escapeXml(request.errorUrl)}</errorUrl>`);
584
+ }
585
+ if (request.cancelUrl) {
586
+ parts.push(`<cancelUrl>${this.escapeXml(request.cancelUrl)}</cancelUrl>`);
587
+ }
588
+ parts.push("</request>");
589
+ parts.push("</ashrait>");
590
+ return parts.join("");
591
+ }
592
+ buildRefundXML(request) {
593
+ const parts = [];
594
+ parts.push('<?xml version="1.0" encoding="utf-8"?>');
595
+ parts.push("<ashrait>");
596
+ parts.push("<request>");
597
+ parts.push(`<version>1000</version>`);
598
+ parts.push("<language>ENG</language>");
599
+ parts.push("<command>refundDeal</command>");
600
+ parts.push(`<terminalNumber>${this.escapeXml(request.terminalNumber)}</terminalNumber>`);
601
+ parts.push(`<user>${this.escapeXml(request.user)}</user>`);
602
+ parts.push(`<password>${this.escapeXml(request.password)}</password>`);
603
+ parts.push(`<transactionId>${this.escapeXml(request.transactionId)}</transactionId>`);
604
+ parts.push(`<currency>${this.escapeXml(request.currency)}</currency>`);
605
+ if (request.total !== void 0) {
606
+ parts.push(`<total>${request.total}</total>`);
607
+ }
608
+ if (request.uniqueid) {
609
+ parts.push(`<uniqueid>${this.escapeXml(request.uniqueid)}</uniqueid>`);
610
+ }
611
+ parts.push("</request>");
612
+ parts.push("</ashrait>");
613
+ return parts.join("");
614
+ }
615
+ buildTestXML() {
616
+ return `<?xml version="1.0" encoding="utf-8"?>
617
+ <ashrait>
618
+ <request>
619
+ <version>1000</version>
620
+ <language>ENG</language>
621
+ <command>echo</command>
622
+ </request>
623
+ </ashrait>`;
624
+ }
625
+ // ==========================================================================
626
+ // HTTP Helpers
627
+ // ==========================================================================
628
+ async sendDoDealRequest(request) {
629
+ const xmlBody = this.buildDoDealXML(request);
630
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
631
+ method: "POST",
632
+ headers: {
633
+ "Content-Type": "text/xml; charset=utf-8"
634
+ },
635
+ body: xmlBody
636
+ });
637
+ if (!response.ok) {
638
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
639
+ }
640
+ const xmlResponse = await response.text();
641
+ return this.parseDoDealResponse(xmlResponse);
642
+ }
643
+ async sendRefundRequest(request) {
644
+ const xmlBody = this.buildRefundXML(request);
645
+ const response = await fetch(`${this.config.baseUrl}/xpo/Relay`, {
646
+ method: "POST",
647
+ headers: {
648
+ "Content-Type": "text/xml; charset=utf-8"
649
+ },
650
+ body: xmlBody
651
+ });
652
+ if (!response.ok) {
653
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
654
+ }
655
+ const xmlResponse = await response.text();
656
+ return this.parseRefundResponse(xmlResponse);
657
+ }
658
+ // ==========================================================================
659
+ // XML Parsing
660
+ // ==========================================================================
661
+ parseDoDealResponse(xml) {
662
+ return {
663
+ resultCode: this.extractXmlValue(xml, "resultCode") ?? "100",
664
+ resultDescription: this.extractXmlValue(xml, "resultDescription"),
665
+ transactionId: this.extractXmlValue(xml, "transactionId"),
666
+ authorizationCode: this.extractXmlValue(xml, "authorizationCode"),
667
+ voucherNumber: this.extractXmlValue(xml, "voucherNumber"),
668
+ cardToken: this.extractXmlValue(xml, "cardToken"),
669
+ cardMask: this.extractXmlValue(xml, "cardMask"),
670
+ cardBrand: this.extractXmlValue(xml, "cardBrand"),
671
+ cardExpiration: this.extractXmlValue(xml, "cardExpiration"),
672
+ redirectUrl: this.extractXmlValue(xml, "redirectUrl"),
673
+ uniqueid: this.extractXmlValue(xml, "uniqueid"),
674
+ rawXml: xml
675
+ };
676
+ }
677
+ parseRefundResponse(xml) {
678
+ return {
679
+ resultCode: this.extractXmlValue(xml, "resultCode") ?? "100",
680
+ resultDescription: this.extractXmlValue(xml, "resultDescription"),
681
+ transactionId: this.extractXmlValue(xml, "transactionId"),
682
+ authorizationCode: this.extractXmlValue(xml, "authorizationCode"),
683
+ uniqueid: this.extractXmlValue(xml, "uniqueid")
684
+ };
685
+ }
686
+ extractXmlValue(xml, tagName) {
687
+ const regex = new RegExp(`<${tagName}>([^<]*)</${tagName}>`, "i");
688
+ const match = xml.match(regex);
689
+ return match ? match[1].trim() : void 0;
690
+ }
691
+ escapeXml(str) {
692
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
693
+ }
694
+ // ==========================================================================
695
+ // Error Handling
696
+ // ==========================================================================
697
+ handleError(error) {
698
+ if (error instanceof Error) {
699
+ return {
700
+ success: false,
701
+ error: error.message,
702
+ errorCode: "unknown"
703
+ };
704
+ }
705
+ return {
706
+ success: false,
707
+ error: "Unknown error occurred",
708
+ errorCode: "unknown"
709
+ };
710
+ }
711
+ };
712
+
713
+ // src/providers/hyp/hyp-webhook-handler.ts
714
+ var HYP_EVENT_TYPES = {
715
+ TRANSACTION_SUCCESS: "transaction.success",
716
+ TRANSACTION_FAILED: "transaction.failed",
717
+ TRANSACTION_PENDING: "transaction.pending",
718
+ REFUND_SUCCESS: "refund.success",
719
+ REFUND_FAILED: "refund.failed"
720
+ };
721
+ var HypWebhookHandler = class {
722
+ provider = "hyp";
723
+ supportedEventTypes = Object.values(HYP_EVENT_TYPES);
724
+ parseEvent(rawPayload) {
725
+ try {
726
+ const resultCode = String(rawPayload.resultCode ?? "100");
727
+ const resultDescription = String(rawPayload.resultDescription ?? "");
728
+ const transactionId = String(rawPayload.transactionId ?? "");
729
+ const uniqueid = String(rawPayload.uniqueid ?? "");
730
+ const total = Number(rawPayload.total ?? 0);
731
+ const currency = String(rawPayload.currency ?? "ILS");
732
+ const eventType = this.determineEventType(resultCode);
733
+ const newStatus = mapHypStatus(resultCode);
734
+ const event = {
735
+ provider: "hyp",
736
+ eventId: uniqueid || transactionId || `hyp_${Date.now()}`,
737
+ eventType,
738
+ providerTransactionId: transactionId,
739
+ amountMinor: total,
740
+ currency,
741
+ newStatus: newStatus ?? void 0,
742
+ error: isHypSuccess(resultCode) ? void 0 : {
743
+ code: resultCode,
744
+ message: resultDescription
745
+ },
746
+ timestamp: /* @__PURE__ */ new Date(),
747
+ rawPayload
748
+ };
749
+ return {
750
+ success: true,
751
+ event
752
+ };
753
+ } catch (error) {
754
+ return {
755
+ success: false,
756
+ error: error instanceof Error ? error.message : "Failed to parse webhook"
757
+ };
758
+ }
759
+ }
760
+ async processEvent(event) {
761
+ try {
762
+ if (!event.providerTransactionId) {
763
+ return {
764
+ success: false,
765
+ error: "Missing transaction ID in webhook",
766
+ action: "ignored_event_type"
767
+ };
768
+ }
769
+ const action = this.determineAction(event);
770
+ return {
771
+ success: true,
772
+ transactionId: event.providerTransactionId,
773
+ action
774
+ };
775
+ } catch (error) {
776
+ return {
777
+ success: false,
778
+ error: error instanceof Error ? error.message : "Processing failed",
779
+ action: "ignored_event_type"
780
+ };
781
+ }
782
+ }
783
+ canHandle(eventType) {
784
+ return this.supportedEventTypes.includes(
785
+ eventType
786
+ );
787
+ }
788
+ async reconcile(_transactionId, _providerTransactionId) {
789
+ return {
790
+ reconciled: false,
791
+ finalStatus: "pending_authorization",
792
+ source: "webhook",
793
+ statusChanged: false
794
+ };
795
+ }
796
+ mapEventType(providerEventType) {
797
+ return providerEventType;
798
+ }
799
+ mapStatus(providerStatus) {
800
+ return mapHypStatus(providerStatus);
801
+ }
802
+ // ==========================================================================
803
+ // Helper Methods
804
+ // ==========================================================================
805
+ determineEventType(resultCode) {
806
+ if (isHypSuccess(resultCode)) {
807
+ return HYP_EVENT_TYPES.TRANSACTION_SUCCESS;
808
+ }
809
+ if (resultCode === "200") {
810
+ return HYP_EVENT_TYPES.TRANSACTION_PENDING;
811
+ }
812
+ return HYP_EVENT_TYPES.TRANSACTION_FAILED;
813
+ }
814
+ determineAction(event) {
815
+ switch (event.eventType) {
816
+ case HYP_EVENT_TYPES.TRANSACTION_SUCCESS:
817
+ case HYP_EVENT_TYPES.TRANSACTION_FAILED:
818
+ case HYP_EVENT_TYPES.TRANSACTION_PENDING:
819
+ case HYP_EVENT_TYPES.REFUND_FAILED:
820
+ return "status_updated";
821
+ case HYP_EVENT_TYPES.REFUND_SUCCESS:
822
+ return "refund_processed";
823
+ default:
824
+ return "ignored_event_type";
825
+ }
826
+ }
827
+ // ==========================================================================
828
+ // Webhook Validation
829
+ // ==========================================================================
830
+ validateSignature(payload, signature, secret) {
831
+ const hasRequiredParams = payload.resultCode !== void 0 && (payload.transactionId !== void 0 || payload.uniqueid !== void 0);
832
+ if (!hasRequiredParams) {
833
+ return false;
834
+ }
835
+ if (secret && signature) {
836
+ return this.validateHMAC(payload, signature, secret);
837
+ }
838
+ return hasRequiredParams;
839
+ }
840
+ validateHMAC(_payload, signature, _secret) {
841
+ try {
842
+ return !!signature;
843
+ } catch {
844
+ return false;
845
+ }
846
+ }
847
+ // ==========================================================================
848
+ // Callback URL Builders
849
+ // ==========================================================================
850
+ buildSuccessUrl(baseUrl, transactionId) {
851
+ return `${baseUrl}/api/payments/hyp/callback?status=success&txId=${transactionId}`;
852
+ }
853
+ buildErrorUrl(baseUrl, transactionId) {
854
+ return `${baseUrl}/api/payments/hyp/callback?status=error&txId=${transactionId}`;
855
+ }
856
+ buildCancelUrl(baseUrl, transactionId) {
857
+ return `${baseUrl}/api/payments/hyp/callback?status=cancel&txId=${transactionId}`;
858
+ }
859
+ // ==========================================================================
860
+ // Response Parsing
861
+ // ==========================================================================
862
+ extractErrorDetails(payload) {
863
+ const resultCode = String(payload.resultCode ?? "unknown");
864
+ const resultDescription = String(payload.resultDescription ?? "Unknown error");
865
+ return {
866
+ code: resultCode,
867
+ message: resultDescription,
868
+ userMessage: this.getUserFriendlyMessage(resultCode)
869
+ };
870
+ }
871
+ getUserFriendlyMessage(resultCode) {
872
+ const errorCode = mapHypError(resultCode);
873
+ const messages = {
874
+ card_declined: "Your card was declined. Please try another payment method.",
875
+ invalid_card: "The card information is invalid. Please check and try again.",
876
+ expired_card: "Your card has expired. Please use a different card.",
877
+ insufficient_funds: "Insufficient funds. Please try another payment method.",
878
+ invalid_cvc: "The security code (CVV) is incorrect.",
879
+ processing_error: "A processing error occurred. Please try again.",
880
+ authentication_required: "Additional authentication is required. Please complete the verification.",
881
+ unknown: "An error occurred. Please try again or contact support."
882
+ };
883
+ return messages[errorCode] ?? messages.unknown;
884
+ }
885
+ extractCardDetails(payload) {
886
+ const cardToken = payload.cardToken;
887
+ const cardMask = payload.cardMask;
888
+ const cardBrand = payload.cardBrand;
889
+ const cardExpiration = payload.cardExpiration;
890
+ return {
891
+ cardToken,
892
+ cardMask,
893
+ cardBrand,
894
+ cardExpiration,
895
+ last4: cardMask?.slice(-4)
896
+ };
897
+ }
898
+ };
899
+ function createHypWebhookHandler() {
900
+ return new HypWebhookHandler();
901
+ }
902
+
903
+ // src/providers/cardcom/cardcom-provider.ts
904
+ var crypto = __toESM(require("crypto"), 1);
905
+ var import_types2 = require("@nehorai/payments/types");
906
+
907
+ // src/providers/cardcom/cardcom-types.ts
908
+ var CARDCOM_API_BASE = "https://secure.cardcom.solutions";
909
+ var CARDCOM_ENDPOINTS = {
910
+ LOW_PROFILE_CREATE: "/api/v11/LowProfile/Create",
911
+ LOW_PROFILE_STATUS: "/Interface/BillGoldGetLowProfileIndicator.aspx",
912
+ DIRECT_CHARGE: "/api/v11/Transactions/Transaction",
913
+ REFUND: "/api/v11/Transactions/RefundByTransactionId"
914
+ };
915
+ var CARDCOM_SUPPORTED_CURRENCIES = ["ILS", "USD", "EUR", "GBP"];
916
+ var CardcomOperation = /* @__PURE__ */ ((CardcomOperation2) => {
917
+ CardcomOperation2[CardcomOperation2["BILL_ONLY"] = 1] = "BILL_ONLY";
918
+ CardcomOperation2[CardcomOperation2["BILL_AND_CREATE_TOKEN"] = 2] = "BILL_AND_CREATE_TOKEN";
919
+ CardcomOperation2[CardcomOperation2["CREATE_TOKEN_ONLY"] = 3] = "CREATE_TOKEN_ONLY";
920
+ CardcomOperation2[CardcomOperation2["SUSPEND_DEAL_ONLY"] = 4] = "SUSPEND_DEAL_ONLY";
921
+ return CardcomOperation2;
922
+ })(CardcomOperation || {});
923
+ var CardcomTransactionType = /* @__PURE__ */ ((CardcomTransactionType2) => {
924
+ CardcomTransactionType2[CardcomTransactionType2["REGULAR"] = 1] = "REGULAR";
925
+ CardcomTransactionType2[CardcomTransactionType2["CREDIT"] = 2] = "CREDIT";
926
+ CardcomTransactionType2[CardcomTransactionType2["INSTALLMENTS"] = 3] = "INSTALLMENTS";
927
+ return CardcomTransactionType2;
928
+ })(CardcomTransactionType || {});
929
+ var CARDCOM_WEBHOOK_EVENTS = [
930
+ "payment.completed",
931
+ "payment.declined",
932
+ "payment.authorized"
933
+ ];
934
+ var CARDCOM_DEAL_RESPONSE_ACTIONS = {
935
+ 0: "pending",
936
+ 1: "approved",
937
+ 2: "declined",
938
+ 3: "error"
939
+ };
940
+ var CARDCOM_RESPONSE_CODE_MAP = {
941
+ 0: "created",
942
+ 1: "failed",
943
+ 2: "failed",
944
+ 3: "failed",
945
+ 4: "failed",
946
+ 5: "failed",
947
+ 6: "failed",
948
+ 7: "failed",
949
+ 8: "failed",
950
+ 9: "failed",
951
+ 10: "failed"
952
+ };
953
+ function mapCardcomDealResponseToStatus(dealResponse) {
954
+ switch (dealResponse) {
955
+ case 0:
956
+ return "pending_authorization";
957
+ case 1:
958
+ return "captured";
959
+ case 2:
960
+ return "failed";
961
+ case 3:
962
+ return "failed";
963
+ default:
964
+ return "failed";
965
+ }
966
+ }
967
+ function mapCardcomError(responseCode) {
968
+ const errorMessages = {
969
+ 0: "Success",
970
+ 1: "General error",
971
+ 2: "Invalid API credentials",
972
+ 3: "Invalid terminal number",
973
+ 4: "Invalid operation type",
974
+ 5: "Invalid card details",
975
+ 6: "Card declined by issuer",
976
+ 7: "Insufficient funds",
977
+ 8: "Invalid amount",
978
+ 9: "Transaction not found",
979
+ 10: "Duplicate transaction",
980
+ 11: "Terminal not active",
981
+ 12: "CVV validation failed",
982
+ 13: "Card expired",
983
+ 14: "Invalid currency",
984
+ 15: "Operation not supported"
985
+ };
986
+ return errorMessages[responseCode] ?? `Error code ${responseCode}`;
987
+ }
988
+ var CARDCOM_CURRENCY_CODES = {
989
+ ILS: 1,
990
+ USD: 2,
991
+ EUR: 3,
992
+ GBP: 4
993
+ };
994
+ function getCurrencyCode(currency) {
995
+ return CARDCOM_CURRENCY_CODES[currency.toUpperCase()] ?? 1;
996
+ }
997
+ var CARDCOM_LANGUAGE_CODES = {
998
+ en: "en",
999
+ he: "he"
1000
+ };
1001
+
1002
+ // src/providers/cardcom/cardcom-provider.ts
1003
+ var CardcomProvider = class {
1004
+ name = "cardcom";
1005
+ supportedCurrencies = CARDCOM_SUPPORTED_CURRENCIES;
1006
+ supportsRecurring = true;
1007
+ supportsSplitPayments = false;
1008
+ config;
1009
+ constructor(config) {
1010
+ if (!config.terminalNumber || !config.apiName || !config.apiPassword) {
1011
+ throw new Error(
1012
+ "CardcomProvider requires terminalNumber, apiName, and apiPassword in config"
1013
+ );
1014
+ }
1015
+ this.config = config;
1016
+ }
1017
+ // ==========================================================================
1018
+ // Payment Intent Operations
1019
+ // ==========================================================================
1020
+ async createPaymentIntent(params) {
1021
+ try {
1022
+ const amountMajor = params.amount.amountMinor / 100;
1023
+ const operation = params.captureMethod === "manual" ? 4 /* SUSPEND_DEAL_ONLY */ : params.metadata?.savePaymentMethod ? 2 /* BILL_AND_CREATE_TOKEN */ : 1 /* BILL_ONLY */;
1024
+ const request = {
1025
+ TerminalNumber: this.config.terminalNumber,
1026
+ ApiName: this.config.apiName,
1027
+ ApiPassword: this.config.apiPassword,
1028
+ Sum: amountMajor,
1029
+ CoinID: getCurrencyCode(params.amount.currency),
1030
+ Operation: operation,
1031
+ Language: "en",
1032
+ ReturnUrl: params.returnUrl,
1033
+ ErrorUrl: params.returnUrl,
1034
+ ProductName: params.description ?? "Payment",
1035
+ InternalDealNumber: params.idempotencyKey,
1036
+ SendEmail: false
1037
+ };
1038
+ if (params.metadata?.customerName) {
1039
+ request.CustomerName = String(params.metadata.customerName);
1040
+ }
1041
+ if (params.metadata?.customerEmail) {
1042
+ request.Email = String(params.metadata.customerEmail);
1043
+ }
1044
+ const response = await this.makeRequest(
1045
+ CARDCOM_ENDPOINTS.LOW_PROFILE_CREATE,
1046
+ request
1047
+ );
1048
+ if (response.ResponseCode !== 0 || !response.PaymentUrl) {
1049
+ return {
1050
+ success: false,
1051
+ error: mapCardcomError(response.ResponseCode),
1052
+ errorCode: String(response.ResponseCode)
1053
+ };
1054
+ }
1055
+ return {
1056
+ success: true,
1057
+ providerIntentId: response.LowProfileCode,
1058
+ redirectUrl: response.PaymentUrl,
1059
+ status: "created"
1060
+ };
1061
+ } catch (error) {
1062
+ return this.handleError(error);
1063
+ }
1064
+ }
1065
+ async authorize(params) {
1066
+ try {
1067
+ const statusResponse = await this.getLowProfileStatus(
1068
+ params.providerIntentId
1069
+ );
1070
+ if (!statusResponse.success || !statusResponse.data) {
1071
+ return {
1072
+ success: false,
1073
+ error: statusResponse.error ?? "Failed to check payment status"
1074
+ };
1075
+ }
1076
+ const status = statusResponse.data;
1077
+ if (status.DealResponse === 1) {
1078
+ return {
1079
+ success: true,
1080
+ authorizationCode: status.InternalDealNumber ?? params.providerIntentId,
1081
+ status: "authorized",
1082
+ captureDeadline: (0, import_types2.calculateCaptureDeadline)(/* @__PURE__ */ new Date())
1083
+ };
1084
+ }
1085
+ if (status.DealResponse === 2) {
1086
+ return {
1087
+ success: false,
1088
+ error: "Payment declined",
1089
+ status: "failed"
1090
+ };
1091
+ }
1092
+ return {
1093
+ success: false,
1094
+ error: "Payment not yet completed",
1095
+ status: "pending_authorization"
1096
+ };
1097
+ } catch (error) {
1098
+ return this.handleError(error);
1099
+ }
1100
+ }
1101
+ async capture(params) {
1102
+ try {
1103
+ const statusResponse = await this.getLowProfileStatus(
1104
+ params.providerIntentId
1105
+ );
1106
+ if (!statusResponse.success || !statusResponse.data) {
1107
+ return {
1108
+ success: false,
1109
+ error: statusResponse.error ?? "Failed to capture payment"
1110
+ };
1111
+ }
1112
+ const status = statusResponse.data;
1113
+ if (status.DealResponse === 1) {
1114
+ return {
1115
+ success: true,
1116
+ providerTransactionId: status.InternalDealNumber ?? params.providerIntentId,
1117
+ status: "captured",
1118
+ capturedAmount: {
1119
+ amountMinor: Math.round((status.Amount ?? 0) * 100),
1120
+ currency: status.Currency ?? params.amount?.currency ?? "ILS"
1121
+ }
1122
+ };
1123
+ }
1124
+ return {
1125
+ success: false,
1126
+ error: "Payment not authorized for capture",
1127
+ status: mapCardcomDealResponseToStatus(status.DealResponse ?? 3)
1128
+ };
1129
+ } catch (error) {
1130
+ return this.handleError(error);
1131
+ }
1132
+ }
1133
+ async void(_params) {
1134
+ return {
1135
+ success: false,
1136
+ error: "Void operation not supported via API. Please use Cardcom merchant dashboard."
1137
+ };
1138
+ }
1139
+ async refund(params) {
1140
+ try {
1141
+ const refundAmount = params.amount ? params.amount.amountMinor / 100 : void 0;
1142
+ if (!refundAmount) {
1143
+ return {
1144
+ success: false,
1145
+ error: "Refund amount is required"
1146
+ };
1147
+ }
1148
+ const request = {
1149
+ TerminalNumber: this.config.terminalNumber,
1150
+ ApiName: this.config.apiName,
1151
+ ApiPassword: this.config.apiPassword,
1152
+ InternalDealNumber: params.providerTransactionId,
1153
+ Amount: refundAmount,
1154
+ CoinID: params.amount ? getCurrencyCode(params.amount.currency) : 1
1155
+ };
1156
+ const response = await this.makeRequest(
1157
+ CARDCOM_ENDPOINTS.REFUND,
1158
+ request
1159
+ );
1160
+ if (response.ResponseCode !== 0) {
1161
+ return {
1162
+ success: false,
1163
+ error: mapCardcomError(response.ResponseCode)
1164
+ };
1165
+ }
1166
+ return {
1167
+ success: true,
1168
+ providerRefundId: response.InternalDealNumber ?? params.providerTransactionId,
1169
+ refundedAmount: {
1170
+ amountMinor: Math.round((response.Amount ?? 0) * 100),
1171
+ currency: params.amount?.currency ?? "ILS"
1172
+ },
1173
+ status: "succeeded"
1174
+ };
1175
+ } catch (error) {
1176
+ return this.handleError(error);
1177
+ }
1178
+ }
1179
+ // ==========================================================================
1180
+ // Payment Method Tokenization
1181
+ // ==========================================================================
1182
+ async createSetupIntent(params) {
1183
+ try {
1184
+ const request = {
1185
+ TerminalNumber: this.config.terminalNumber,
1186
+ ApiName: this.config.apiName,
1187
+ ApiPassword: this.config.apiPassword,
1188
+ Sum: 0,
1189
+ Operation: 3 /* CREATE_TOKEN_ONLY */,
1190
+ Language: "en",
1191
+ InternalDealNumber: `setup_${params.userId}_${Date.now()}`
1192
+ };
1193
+ const response = await this.makeRequest(
1194
+ CARDCOM_ENDPOINTS.LOW_PROFILE_CREATE,
1195
+ request
1196
+ );
1197
+ if (response.ResponseCode !== 0 || !response.PaymentUrl) {
1198
+ return {
1199
+ success: false,
1200
+ error: mapCardcomError(response.ResponseCode)
1201
+ };
1202
+ }
1203
+ return {
1204
+ success: true,
1205
+ setupIntentId: response.LowProfileCode,
1206
+ clientSecret: response.PaymentUrl
1207
+ };
1208
+ } catch (error) {
1209
+ return this.handleError(error);
1210
+ }
1211
+ }
1212
+ async savePaymentMethod(params) {
1213
+ try {
1214
+ const lowProfileCode = params.setupData.lowProfileCode;
1215
+ if (!lowProfileCode) {
1216
+ return {
1217
+ success: false,
1218
+ error: "Low profile code is required"
1219
+ };
1220
+ }
1221
+ const statusResponse = await this.getLowProfileStatus(lowProfileCode);
1222
+ if (!statusResponse.success || !statusResponse.data) {
1223
+ return {
1224
+ success: false,
1225
+ error: statusResponse.error ?? "Failed to retrieve payment method"
1226
+ };
1227
+ }
1228
+ const status = statusResponse.data;
1229
+ if (!status.Token) {
1230
+ return {
1231
+ success: false,
1232
+ error: "No token created"
1233
+ };
1234
+ }
1235
+ const [expMonth, expYear] = (status.CardExpiration ?? "/").split("/");
1236
+ return {
1237
+ success: true,
1238
+ paymentMethodId: status.Token,
1239
+ cardBrand: status.CardType ?? "unknown",
1240
+ cardLast4: status.CardMask?.slice(-4),
1241
+ cardExpMonth: expMonth?.padStart(2, "0"),
1242
+ cardExpYear: expYear ? `20${expYear}` : void 0,
1243
+ cardBin: status.CardBin
1244
+ };
1245
+ } catch (error) {
1246
+ return this.handleError(error);
1247
+ }
1248
+ }
1249
+ async deletePaymentMethod(_paymentMethodId) {
1250
+ return {
1251
+ success: true
1252
+ };
1253
+ }
1254
+ // ==========================================================================
1255
+ // Customer Management
1256
+ // ==========================================================================
1257
+ async createCustomer(params) {
1258
+ return {
1259
+ success: true,
1260
+ customerId: params.userId
1261
+ };
1262
+ }
1263
+ async getOrCreateCustomer(userId, email) {
1264
+ return this.createCustomer({ userId, email });
1265
+ }
1266
+ // ==========================================================================
1267
+ // Health & Status
1268
+ // ==========================================================================
1269
+ async getHealth() {
1270
+ const start = Date.now();
1271
+ try {
1272
+ const request = {
1273
+ TerminalNumber: this.config.terminalNumber,
1274
+ ApiName: this.config.apiName,
1275
+ ApiPassword: this.config.apiPassword,
1276
+ Sum: 1,
1277
+ Operation: 1 /* BILL_ONLY */,
1278
+ InternalDealNumber: `health_check_${Date.now()}`
1279
+ };
1280
+ const response = await this.makeRequest(
1281
+ CARDCOM_ENDPOINTS.LOW_PROFILE_CREATE,
1282
+ request
1283
+ );
1284
+ const healthy = response.ResponseCode === 0 || response.ResponseCode === 1;
1285
+ return {
1286
+ provider: "cardcom",
1287
+ healthy,
1288
+ lastChecked: /* @__PURE__ */ new Date(),
1289
+ avgLatencyMs: Date.now() - start,
1290
+ circuitBreakerOpen: false
1291
+ };
1292
+ } catch {
1293
+ return {
1294
+ provider: "cardcom",
1295
+ healthy: false,
1296
+ lastChecked: /* @__PURE__ */ new Date(),
1297
+ circuitBreakerOpen: false
1298
+ };
1299
+ }
1300
+ }
1301
+ validateWebhookSignature(payload, signature) {
1302
+ if (!this.config.webhookSecret) {
1303
+ return false;
1304
+ }
1305
+ try {
1306
+ const expectedSignature = crypto.createHmac("sha256", this.config.webhookSecret).update(payload).digest("hex");
1307
+ return crypto.timingSafeEqual(
1308
+ Buffer.from(signature),
1309
+ Buffer.from(expectedSignature)
1310
+ );
1311
+ } catch {
1312
+ return false;
1313
+ }
1314
+ }
1315
+ async getPaymentIntentStatus(providerIntentId) {
1316
+ try {
1317
+ const result = await this.getLowProfileStatus(providerIntentId);
1318
+ if (!result.success || !result.data) {
1319
+ return {
1320
+ status: "unknown",
1321
+ error: result.error
1322
+ };
1323
+ }
1324
+ const status = mapCardcomDealResponseToStatus(
1325
+ result.data.DealResponse ?? 0
1326
+ );
1327
+ return { status };
1328
+ } catch (error) {
1329
+ return {
1330
+ status: "unknown",
1331
+ error: error instanceof Error ? error.message : "Unknown error"
1332
+ };
1333
+ }
1334
+ }
1335
+ // ==========================================================================
1336
+ // Helper Methods
1337
+ // ==========================================================================
1338
+ async makeRequest(endpoint, data) {
1339
+ const url = `${CARDCOM_API_BASE}${endpoint}`;
1340
+ const response = await fetch(url, {
1341
+ method: "POST",
1342
+ headers: {
1343
+ "Content-Type": "application/json"
1344
+ },
1345
+ body: JSON.stringify(data)
1346
+ });
1347
+ if (!response.ok) {
1348
+ throw new Error(`Cardcom API error: ${response.status} ${response.statusText}`);
1349
+ }
1350
+ return response.json();
1351
+ }
1352
+ async getLowProfileStatus(lowProfileCode) {
1353
+ try {
1354
+ const params = new URLSearchParams({
1355
+ terminalnumber: this.config.terminalNumber,
1356
+ lowprofilecode: lowProfileCode,
1357
+ username: this.config.apiName
1358
+ });
1359
+ const url = `${CARDCOM_API_BASE}${CARDCOM_ENDPOINTS.LOW_PROFILE_STATUS}?${params}`;
1360
+ const response = await fetch(url, {
1361
+ method: "GET"
1362
+ });
1363
+ if (!response.ok) {
1364
+ return {
1365
+ success: false,
1366
+ error: `Status check failed: ${response.status}`
1367
+ };
1368
+ }
1369
+ const data = await response.json();
1370
+ if (data.ResponseCode !== 0) {
1371
+ return {
1372
+ success: false,
1373
+ error: mapCardcomError(data.ResponseCode)
1374
+ };
1375
+ }
1376
+ return { success: true, data };
1377
+ } catch (error) {
1378
+ return {
1379
+ success: false,
1380
+ error: error instanceof Error ? error.message : "Status check failed"
1381
+ };
1382
+ }
1383
+ }
1384
+ handleError(error) {
1385
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1386
+ return {
1387
+ success: false,
1388
+ error: errorMessage
1389
+ };
1390
+ }
1391
+ };
1392
+
1393
+ // src/providers/cardcom/cardcom-webhook-handler.ts
1394
+ var CardcomWebhookHandler = class {
1395
+ provider = "cardcom";
1396
+ supportedEventTypes = CARDCOM_WEBHOOK_EVENTS;
1397
+ parseEvent(rawPayload) {
1398
+ try {
1399
+ const params = rawPayload;
1400
+ const responseCode = parseInt(params.ResponseCode ?? "1", 10);
1401
+ const dealResponse = parseInt(params.DealResponse ?? "0", 10);
1402
+ const lowProfileCode = params.LowProfileCode ?? "";
1403
+ const internalDealNumber = params.InternalDealNumber ?? "";
1404
+ if (!lowProfileCode && !internalDealNumber) {
1405
+ return {
1406
+ success: false,
1407
+ error: "Missing LowProfileCode or InternalDealNumber in callback"
1408
+ };
1409
+ }
1410
+ let eventType;
1411
+ if (dealResponse === 1) {
1412
+ eventType = "payment.completed";
1413
+ } else if (dealResponse === 2) {
1414
+ eventType = "payment.declined";
1415
+ } else if (dealResponse === 0 && responseCode === 0) {
1416
+ eventType = "payment.authorized";
1417
+ } else {
1418
+ eventType = "payment.declined";
1419
+ }
1420
+ const status = mapCardcomDealResponseToStatus(dealResponse);
1421
+ const amountString = params.Amount ?? "0";
1422
+ const amountMajor = parseFloat(amountString);
1423
+ const amountMinor = Math.round(amountMajor * 100);
1424
+ const parsed = {
1425
+ provider: "cardcom",
1426
+ eventId: `${lowProfileCode}_${internalDealNumber}_${Date.now()}`,
1427
+ eventType,
1428
+ providerTransactionId: internalDealNumber || lowProfileCode,
1429
+ timestamp: /* @__PURE__ */ new Date(),
1430
+ rawPayload,
1431
+ newStatus: status,
1432
+ amountMinor,
1433
+ currency: params.Currency ?? "ILS"
1434
+ };
1435
+ if (dealResponse === 2 || responseCode !== 0) {
1436
+ parsed.error = {
1437
+ code: String(responseCode),
1438
+ message: CARDCOM_DEAL_RESPONSE_ACTIONS[dealResponse] ?? "Payment failed"
1439
+ };
1440
+ }
1441
+ return { success: true, event: parsed };
1442
+ } catch (error) {
1443
+ return {
1444
+ success: false,
1445
+ error: error instanceof Error ? error.message : "Parse error"
1446
+ };
1447
+ }
1448
+ }
1449
+ async processEvent(event) {
1450
+ const action = this.getActionForEvent(event.eventType);
1451
+ if (action === "ignored") {
1452
+ return {
1453
+ success: true,
1454
+ action: "ignored_event_type"
1455
+ };
1456
+ }
1457
+ return {
1458
+ success: true,
1459
+ transactionId: event.providerTransactionId,
1460
+ action: "status_updated"
1461
+ };
1462
+ }
1463
+ canHandle(eventType) {
1464
+ return this.supportedEventTypes.includes(
1465
+ eventType
1466
+ );
1467
+ }
1468
+ async reconcile(_transactionId, _providerTransactionId) {
1469
+ return {
1470
+ reconciled: false,
1471
+ finalStatus: "created",
1472
+ source: "provider_query",
1473
+ statusChanged: false
1474
+ };
1475
+ }
1476
+ mapEventType(providerEventType) {
1477
+ return providerEventType;
1478
+ }
1479
+ mapStatus(providerStatus) {
1480
+ const dealResponse = parseInt(providerStatus, 10);
1481
+ if (isNaN(dealResponse)) {
1482
+ return null;
1483
+ }
1484
+ return mapCardcomDealResponseToStatus(dealResponse);
1485
+ }
1486
+ getActionForEvent(eventType) {
1487
+ switch (eventType) {
1488
+ case "payment.completed":
1489
+ case "payment.declined":
1490
+ case "payment.authorized":
1491
+ return "status_update";
1492
+ default:
1493
+ return "ignored";
1494
+ }
1495
+ }
1496
+ };
1497
+ function validateCardcomCallback(params) {
1498
+ const requiredFields = ["ResponseCode", "LowProfileCode"];
1499
+ for (const field of requiredFields) {
1500
+ if (!params[field]) {
1501
+ return {
1502
+ valid: false,
1503
+ error: `Missing required field: ${field}`
1504
+ };
1505
+ }
1506
+ }
1507
+ const responseCode = parseInt(String(params.ResponseCode), 10);
1508
+ if (isNaN(responseCode)) {
1509
+ return {
1510
+ valid: false,
1511
+ error: "Invalid ResponseCode format"
1512
+ };
1513
+ }
1514
+ return { valid: true };
1515
+ }
1516
+ function parseCardcomCallbackUrl(url) {
1517
+ try {
1518
+ const urlObj = new URL(url);
1519
+ const params = {};
1520
+ params.ResponseCode = urlObj.searchParams.get("ResponseCode") ?? void 0;
1521
+ params.LowProfileCode = urlObj.searchParams.get("LowProfileCode") ?? void 0;
1522
+ params.DealResponse = urlObj.searchParams.get("DealResponse") ?? void 0;
1523
+ params.OperationResponse = urlObj.searchParams.get("OperationResponse") ?? void 0;
1524
+ params.InternalDealNumber = urlObj.searchParams.get("InternalDealNumber") ?? void 0;
1525
+ params.Amount = urlObj.searchParams.get("Amount") ?? void 0;
1526
+ params.Currency = urlObj.searchParams.get("Currency") ?? void 0;
1527
+ params.CardMask = urlObj.searchParams.get("CardMask") ?? void 0;
1528
+ params.Token = urlObj.searchParams.get("Token") ?? void 0;
1529
+ return params;
1530
+ } catch {
1531
+ return {};
1532
+ }
1533
+ }
1534
+ function isCardcomCallbackSuccess(params) {
1535
+ const responseCode = parseInt(params.ResponseCode ?? "1", 10);
1536
+ const dealResponse = parseInt(params.DealResponse ?? "0", 10);
1537
+ return responseCode === 0 && dealResponse === 1;
1538
+ }
1539
+ function isCardcomCallbackAuthorized(params) {
1540
+ const responseCode = parseInt(params.ResponseCode ?? "1", 10);
1541
+ const dealResponse = parseInt(params.DealResponse ?? "0", 10);
1542
+ return responseCode === 0 && (dealResponse === 0 || dealResponse === 1);
1543
+ }
1544
+ function getCardcomCallbackError(params) {
1545
+ const responseCode = parseInt(params.ResponseCode ?? "1", 10);
1546
+ const dealResponse = parseInt(params.DealResponse ?? "0", 10);
1547
+ if (responseCode === 0 && dealResponse === 1) {
1548
+ return null;
1549
+ }
1550
+ if (dealResponse === 2) {
1551
+ return "Payment declined by card issuer";
1552
+ }
1553
+ if (responseCode !== 0) {
1554
+ return `Payment failed with code ${responseCode}`;
1555
+ }
1556
+ return "Payment processing error";
1557
+ }
1558
+
1559
+ // src/routing/routing-rules.ts
1560
+ var ISRAELI_BIN_RANGES = [
1561
+ // Isracard
1562
+ { start: "458000", end: "458999", issuer: "Isracard", country: "IL" },
1563
+ { start: "480000", end: "480999", issuer: "Isracard", country: "IL" },
1564
+ // Cal (Visa Cal)
1565
+ { start: "532600", end: "532699", issuer: "Cal", country: "IL" },
1566
+ { start: "557050", end: "557059", issuer: "Cal", country: "IL" },
1567
+ // Leumi Card
1568
+ { start: "589200", end: "589299", issuer: "Leumi Card", country: "IL" },
1569
+ // Diners Israel
1570
+ { start: "363700", end: "363799", issuer: "Diners Israel", country: "IL" },
1571
+ // Max (Leumi)
1572
+ { start: "491861", end: "491861", issuer: "Max", country: "IL" },
1573
+ { start: "458600", end: "458699", issuer: "Max", country: "IL" }
1574
+ ];
1575
+ var ISRAELI_CARD_BIN_RULES = [
1576
+ {
1577
+ ranges: ISRAELI_BIN_RANGES.map((r) => ({
1578
+ start: r.start,
1579
+ end: r.end,
1580
+ issuer: r.issuer,
1581
+ country: r.country
1582
+ })),
1583
+ preferredProvider: "hyp",
1584
+ priority: 1
1585
+ }
1586
+ ];
1587
+ var ISRAELI_PROVIDER_PRIORITIES = [
1588
+ {
1589
+ provider: "hyp",
1590
+ priority: 1,
1591
+ maxFeePercent: 1.8,
1592
+ supportsCurrency: ["ILS", "USD", "EUR"],
1593
+ supportsRecurring: true,
1594
+ isLocalGateway: true
1595
+ },
1596
+ {
1597
+ provider: "cardcom",
1598
+ priority: 2,
1599
+ maxFeePercent: 2,
1600
+ supportsCurrency: ["ILS", "USD", "EUR"],
1601
+ supportsRecurring: true,
1602
+ isLocalGateway: true
1603
+ },
1604
+ {
1605
+ provider: "stripe",
1606
+ priority: 3,
1607
+ maxFeePercent: 2.9,
1608
+ supportsCurrency: ["USD", "EUR", "GBP", "ILS", "CAD", "AUD"],
1609
+ supportsRecurring: true,
1610
+ isLocalGateway: false
1611
+ }
1612
+ ];
1613
+ var ISRAELI_ROUTING_RULES = {
1614
+ cardBinRules: ISRAELI_CARD_BIN_RULES,
1615
+ providerPriorities: ISRAELI_PROVIDER_PRIORITIES
1616
+ };
1617
+ function isIsraeliCard(bin) {
1618
+ if (!bin || bin.length < 6) return false;
1619
+ const binPrefix = bin.substring(0, 6);
1620
+ return ISRAELI_BIN_RANGES.some(
1621
+ (range) => binPrefix >= range.start && binPrefix <= range.end
1622
+ );
1623
+ }
1624
+ function getCardIssuer(bin) {
1625
+ if (!bin || bin.length < 6) return null;
1626
+ const binPrefix = bin.substring(0, 6);
1627
+ const range = ISRAELI_BIN_RANGES.find(
1628
+ (r) => binPrefix >= r.start && binPrefix <= r.end
1629
+ );
1630
+ return range?.issuer ?? null;
1631
+ }
1632
+ function getOptimalProvider(isIsraeli, currency, requiresRecurring, availableProviders) {
1633
+ const candidates = ISRAELI_PROVIDER_PRIORITIES.filter(
1634
+ (p) => availableProviders.includes(p.provider)
1635
+ );
1636
+ if (candidates.length === 0) return null;
1637
+ const suitable = candidates.filter((p) => {
1638
+ if (!p.supportsCurrency.includes(currency)) return false;
1639
+ if (requiresRecurring && !p.supportsRecurring) return false;
1640
+ return true;
1641
+ });
1642
+ if (suitable.length === 0) {
1643
+ return candidates[0]?.provider ?? null;
1644
+ }
1645
+ if (isIsraeli) {
1646
+ const localProviders = suitable.filter((p) => p.isLocalGateway);
1647
+ if (localProviders.length > 0) {
1648
+ return localProviders.sort((a, b) => a.priority - b.priority)[0].provider;
1649
+ }
1650
+ }
1651
+ return suitable.sort((a, b) => a.priority - b.priority)[0].provider;
1652
+ }
1653
+ function getFallbackProviders(primaryProvider, availableProviders) {
1654
+ return ISRAELI_PROVIDER_PRIORITIES.filter(
1655
+ (p) => p.provider !== primaryProvider && availableProviders.includes(p.provider)
1656
+ ).sort((a, b) => a.priority - b.priority).map((p) => p.provider);
1657
+ }
1658
+ function getProviderFeePercent(provider) {
1659
+ const config = ISRAELI_PROVIDER_PRIORITIES.find((p) => p.provider === provider);
1660
+ return config?.maxFeePercent ?? 3;
1661
+ }
1662
+
1663
+ // src/factory.ts
1664
+ function addIsraeliProviders(services, config) {
1665
+ if (config.hyp) {
1666
+ services.providers.set("hyp", new HypProvider(config.hyp));
1667
+ services.webhookHandlers.set("hyp", new HypWebhookHandler());
1668
+ }
1669
+ if (config.cardcom) {
1670
+ services.providers.set("cardcom", new CardcomProvider(config.cardcom));
1671
+ services.webhookHandlers.set("cardcom", new CardcomWebhookHandler());
1672
+ }
1673
+ return services;
1674
+ }
1675
+ // Annotate the CommonJS export names for ESM import in node:
1676
+ 0 && (module.exports = {
1677
+ CARDCOM_API_BASE,
1678
+ CARDCOM_CURRENCY_CODES,
1679
+ CARDCOM_DEAL_RESPONSE_ACTIONS,
1680
+ CARDCOM_ENDPOINTS,
1681
+ CARDCOM_LANGUAGE_CODES,
1682
+ CARDCOM_RESPONSE_CODE_MAP,
1683
+ CARDCOM_SUPPORTED_CURRENCIES,
1684
+ CARDCOM_WEBHOOK_EVENTS,
1685
+ CardcomOperation,
1686
+ CardcomProvider,
1687
+ CardcomTransactionType,
1688
+ CardcomWebhookHandler,
1689
+ DEFAULT_HYP_ENDPOINTS,
1690
+ HYP_CREDIT_TYPES,
1691
+ HYP_ERROR_MAP,
1692
+ HYP_RESULT_CODE_MAP,
1693
+ HYP_SUPPORTED_CURRENCIES,
1694
+ HYP_TRANSACTION_CODES,
1695
+ HYP_TRANSACTION_TYPES,
1696
+ HYP_VALIDATION_MODES,
1697
+ HypProvider,
1698
+ HypWebhookHandler,
1699
+ ISRAELI_BIN_RANGES,
1700
+ ISRAELI_ROUTING_RULES,
1701
+ addIsraeliProviders,
1702
+ createHypWebhookHandler,
1703
+ formatCardExpiration,
1704
+ formatHypAmount,
1705
+ getCardIssuer,
1706
+ getCardcomCallbackError,
1707
+ getCurrencyCode,
1708
+ getFallbackProviders,
1709
+ getOptimalProvider,
1710
+ getProviderFeePercent,
1711
+ isCardcomCallbackAuthorized,
1712
+ isCardcomCallbackSuccess,
1713
+ isHypSuccess,
1714
+ isHypSupportedCurrency,
1715
+ isIsraeliCard,
1716
+ mapCardcomDealResponseToStatus,
1717
+ mapCardcomError,
1718
+ mapHypError,
1719
+ mapHypStatus,
1720
+ parseCardExpiration,
1721
+ parseCardcomCallbackUrl,
1722
+ validateCardcomCallback
1723
+ });
1724
+ //# sourceMappingURL=index.cjs.map