@sikka/aps 0.0.1

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.mjs ADDED
@@ -0,0 +1,2741 @@
1
+ // src/types.ts
2
+ var APSException = class extends Error {
3
+ constructor(error) {
4
+ super(error.message);
5
+ this.name = "APSException";
6
+ this.code = error.code;
7
+ this.statusCode = error.statusCode;
8
+ this.rawResponse = error.rawResponse;
9
+ }
10
+ };
11
+
12
+ // src/utils.ts
13
+ import crypto from "crypto";
14
+ var noopLogger = {
15
+ debug: () => {
16
+ },
17
+ info: () => {
18
+ },
19
+ warn: () => {
20
+ },
21
+ error: () => {
22
+ }
23
+ };
24
+ function generateHMAC(data, secret) {
25
+ return crypto.createHmac("sha256", secret).update(data).digest("base64");
26
+ }
27
+ function verifyHMAC(data, signature, secret) {
28
+ const expectedSignature = generateHMAC(data, secret);
29
+ return expectedSignature === signature;
30
+ }
31
+ function buildQueryString(params) {
32
+ return Object.entries(params).filter(([_, value]) => value !== void 0 && value !== null && value !== "").sort((a, b) => a[0].localeCompare(b[0])).map(([key, value]) => `${key}=${value}`).join("&");
33
+ }
34
+ function getBaseUrl(environment) {
35
+ if (environment === "production") {
36
+ return "https://checkout.payfort.com";
37
+ }
38
+ return "https://sbcheckout.payfort.com";
39
+ }
40
+ function getHostedCheckoutUrl(environment) {
41
+ if (environment === "production") {
42
+ return "https://checkout.payfort.com/FortAPI/paymentPage";
43
+ }
44
+ return "https://sbcheckout.payfort.com/FortAPI/paymentPage";
45
+ }
46
+ function getApiUrl(environment) {
47
+ if (environment === "production") {
48
+ return "https://paymentservices.payfort.com";
49
+ }
50
+ return "https://sbpaymentservices.payfort.com";
51
+ }
52
+ function generateOrderId() {
53
+ return `order_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
54
+ }
55
+ function sleep(ms) {
56
+ return new Promise((resolve) => setTimeout(resolve, ms));
57
+ }
58
+ var DEFAULT_TIMEOUT = 3e4;
59
+ var DEFAULT_MAX_RETRIES = 3;
60
+ var RateLimiter = class {
61
+ constructor(maxRequests = 100, windowMs = 6e4) {
62
+ this.requests = [];
63
+ this.maxRequests = maxRequests;
64
+ this.windowMs = windowMs;
65
+ }
66
+ /**
67
+ * Check if a request can be made
68
+ */
69
+ canMakeRequest() {
70
+ const now = Date.now();
71
+ this.requests = this.requests.filter((time) => now - time < this.windowMs);
72
+ return this.requests.length < this.maxRequests;
73
+ }
74
+ /**
75
+ * Record a request
76
+ */
77
+ recordRequest() {
78
+ this.requests.push(Date.now());
79
+ }
80
+ /**
81
+ * Get time until next request is allowed (in ms)
82
+ */
83
+ getTimeUntilNextRequest() {
84
+ if (this.canMakeRequest()) {
85
+ return 0;
86
+ }
87
+ const oldestRequest = Math.min(...this.requests);
88
+ return this.windowMs - (Date.now() - oldestRequest);
89
+ }
90
+ /**
91
+ * Wait until a request can be made
92
+ */
93
+ async waitForSlot() {
94
+ const waitTime = this.getTimeUntilNextRequest();
95
+ if (waitTime > 0) {
96
+ await sleep(waitTime);
97
+ }
98
+ }
99
+ };
100
+ var globalRateLimiter = null;
101
+ function getRateLimiter(maxRequests, windowMs) {
102
+ if (!globalRateLimiter) {
103
+ globalRateLimiter = new RateLimiter(maxRequests, windowMs);
104
+ }
105
+ return globalRateLimiter;
106
+ }
107
+ async function makeRequest(url, body, options = {}) {
108
+ const {
109
+ timeout = DEFAULT_TIMEOUT,
110
+ maxRetries = DEFAULT_MAX_RETRIES,
111
+ retryDelayMs = 1e3,
112
+ logger = noopLogger,
113
+ idempotencyKey
114
+ } = options;
115
+ const rateLimiter = getRateLimiter();
116
+ if (!rateLimiter.canMakeRequest()) {
117
+ logger.warn?.("Rate limit reached, waiting for slot...");
118
+ await rateLimiter.waitForSlot();
119
+ }
120
+ let lastError = null;
121
+ const startTime = Date.now();
122
+ const headers = {
123
+ "Content-Type": "application/json"
124
+ };
125
+ if (idempotencyKey) {
126
+ headers["Idempotency-Key"] = idempotencyKey;
127
+ }
128
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
129
+ const controller = new AbortController();
130
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
131
+ try {
132
+ logger.debug?.(`APS Request (attempt ${attempt + 1}/${maxRetries + 1}):`, { url, body });
133
+ rateLimiter.recordRequest();
134
+ const response = await fetch(url, {
135
+ method: "POST",
136
+ headers,
137
+ body: JSON.stringify(body),
138
+ signal: controller.signal
139
+ });
140
+ clearTimeout(timeoutId);
141
+ if (!response.ok) {
142
+ if (response.status === 429) {
143
+ const retryAfter = response.headers.get("Retry-After");
144
+ const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : retryDelayMs * Math.pow(2, attempt);
145
+ logger.warn?.(`Rate limited (429), waiting ${waitTime}ms before retry...`);
146
+ await sleep(waitTime);
147
+ continue;
148
+ }
149
+ if (response.status >= 500 && attempt < maxRetries) {
150
+ const delay = retryDelayMs * Math.pow(2, attempt);
151
+ logger.warn?.(`Server error (${response.status}), retrying in ${delay}ms...`);
152
+ await sleep(delay);
153
+ continue;
154
+ }
155
+ throw new Error(`HTTP error! status: ${response.status}`);
156
+ }
157
+ const data = await response.json();
158
+ const duration = Date.now() - startTime;
159
+ logger.info?.(`APS Response (${duration}ms):`, {
160
+ responseCode: data.response_code,
161
+ status: data.status
162
+ });
163
+ return data;
164
+ } catch (error) {
165
+ clearTimeout(timeoutId);
166
+ lastError = error instanceof Error ? error : new Error(String(error));
167
+ if (error instanceof Error && error.name === "AbortError") {
168
+ logger.error?.(`Request timed out after ${timeout}ms`);
169
+ throw new Error(`Request timed out after ${timeout}ms`);
170
+ }
171
+ logger.error?.(`Request failed (attempt ${attempt + 1}):`, lastError.message);
172
+ if (attempt < maxRetries) {
173
+ const delay = retryDelayMs * Math.pow(2, attempt);
174
+ await sleep(delay);
175
+ continue;
176
+ }
177
+ }
178
+ }
179
+ logger.error?.("Request failed after all retries:", lastError?.message);
180
+ throw lastError || new Error("Request failed after retries");
181
+ }
182
+ function validateRequiredFields(fields, required) {
183
+ const missing = required.filter((field) => {
184
+ const value = fields[field];
185
+ return value === void 0 || value === null || value === "";
186
+ });
187
+ if (missing.length > 0) {
188
+ throw new Error(`Missing required fields: ${missing.join(", ")}`);
189
+ }
190
+ }
191
+ function validateEmail(email) {
192
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
193
+ return emailRegex.test(email);
194
+ }
195
+ function validateCardNumber(cardNumber) {
196
+ const cleaned = cardNumber.replace(/\D/g, "");
197
+ if (cleaned.length < 13 || cleaned.length > 19) {
198
+ return false;
199
+ }
200
+ let sum = 0;
201
+ let shouldDouble = false;
202
+ for (let i = cleaned.length - 1; i >= 0; i--) {
203
+ let digit = parseInt(cleaned.charAt(i), 10);
204
+ if (shouldDouble) {
205
+ digit *= 2;
206
+ if (digit > 9) {
207
+ digit -= 9;
208
+ }
209
+ }
210
+ sum += digit;
211
+ shouldDouble = !shouldDouble;
212
+ }
213
+ return sum % 10 === 0;
214
+ }
215
+ function validateExpiryDate(month, year) {
216
+ const expiryMonth = parseInt(month, 10);
217
+ const expiryYear = parseInt(year.length === 2 ? `20${year}` : year, 10);
218
+ if (expiryMonth < 1 || expiryMonth > 12) {
219
+ return false;
220
+ }
221
+ const now = /* @__PURE__ */ new Date();
222
+ const currentYear = now.getFullYear();
223
+ const currentMonth = now.getMonth() + 1;
224
+ if (expiryYear < currentYear) {
225
+ return false;
226
+ }
227
+ if (expiryYear === currentYear && expiryMonth < currentMonth) {
228
+ return false;
229
+ }
230
+ return true;
231
+ }
232
+ function validateCVV(cvv) {
233
+ return /^\d{3,4}$/.test(cvv);
234
+ }
235
+
236
+ // src/modules/payment-links.ts
237
+ import crypto2 from "crypto";
238
+ var PaymentLinksModule = class {
239
+ constructor(config, options) {
240
+ this.config = config;
241
+ this.options = options;
242
+ }
243
+ /**
244
+ * Create a new payment link using APS Payment Links API
245
+ */
246
+ async create(options) {
247
+ try {
248
+ validateRequiredFields(options, ["order"]);
249
+ validateRequiredFields(options.order, ["amount", "currency"]);
250
+ if (options.order.customer?.email) {
251
+ if (!validateEmail(options.order.customer.email)) {
252
+ throw new Error("Invalid customer email format");
253
+ }
254
+ }
255
+ const orderId = options.order.id || `order_${Date.now()}`;
256
+ const amount = options.order.amount;
257
+ const currency = options.order.currency || this.config.currency;
258
+ const requestBody = {
259
+ service_command: "PAYMENT_LINK",
260
+ access_code: this.config.accessCode,
261
+ merchant_identifier: this.config.merchantId,
262
+ merchant_reference: orderId,
263
+ amount: amount.toString(),
264
+ currency,
265
+ language: this.config.language || "en",
266
+ customer_email: options.order.customer?.email || "customer@example.com",
267
+ notification_type: "NONE"
268
+ };
269
+ if (options.order.description) {
270
+ requestBody.order_description = options.order.description;
271
+ }
272
+ if (options.order.customer?.name) {
273
+ requestBody.customer_name = options.order.customer.name;
274
+ }
275
+ if (options.order.customer?.phone) {
276
+ requestBody.customer_phone = options.order.customer.phone;
277
+ }
278
+ if (options.recurring) {
279
+ requestBody.link_command = "AUTHORIZATION";
280
+ } else {
281
+ requestBody.link_command = "PURCHASE";
282
+ }
283
+ if (options.allowedPaymentMethods && options.allowedPaymentMethods.length > 0) {
284
+ requestBody.payment_option = options.allowedPaymentMethods[0];
285
+ }
286
+ if (options.tokenValidityHours && options.tokenValidityHours > 0) {
287
+ const expiryDate = /* @__PURE__ */ new Date();
288
+ expiryDate.setHours(expiryDate.getHours() + options.tokenValidityHours);
289
+ const year = expiryDate.getFullYear();
290
+ const month = String(expiryDate.getMonth() + 1).padStart(2, "0");
291
+ const day = String(expiryDate.getDate()).padStart(2, "0");
292
+ const hours = String(expiryDate.getHours()).padStart(2, "0");
293
+ const minutes = String(expiryDate.getMinutes()).padStart(2, "0");
294
+ const seconds = String(expiryDate.getSeconds()).padStart(2, "0");
295
+ requestBody.request_expiry_date = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}+00:00`;
296
+ }
297
+ requestBody.signature = this.generateSignature(requestBody);
298
+ const apiUrl = getApiUrl(this.config.environment);
299
+ const response = await this.makeApiRequest(`${apiUrl}/FortAPI/paymentApi`, requestBody);
300
+ const isSuccess = response.status?.toString() === "20" || response.response_code?.toString() === "00000" || response.response_code?.toString() === "48000" || response.response_message?.toLowerCase() === "success";
301
+ if (!isSuccess) {
302
+ throw new APSException({
303
+ code: response.response_code?.toString() || "PAYMENT_LINK_ERROR",
304
+ message: response.response_message || "Failed to create payment link",
305
+ rawResponse: response
306
+ });
307
+ }
308
+ return {
309
+ url: response.payment_link,
310
+ linkId: response.payment_link_id,
311
+ orderId,
312
+ expiresAt: requestBody.request_expiry_date ? new Date(requestBody.request_expiry_date) : void 0,
313
+ rawResponse: response
314
+ };
315
+ } catch (error) {
316
+ if (error instanceof APSException) {
317
+ throw error;
318
+ }
319
+ const apsError = {
320
+ code: "PAYMENT_LINK_ERROR",
321
+ message: error instanceof Error ? error.message : "Failed to create payment link",
322
+ rawResponse: error
323
+ };
324
+ throw new APSException(apsError);
325
+ }
326
+ }
327
+ /**
328
+ * Generate signature for APS API requests
329
+ * Following official APS documentation:
330
+ * 1. Sort all parameters alphabetically
331
+ * 2. Concatenate as param_name=param_value
332
+ * 3. Wrap with SHA phrase at beginning and end
333
+ * 4. Hash with SHA-256
334
+ */
335
+ generateSignature(params) {
336
+ const sortedKeys = Object.keys(params).sort();
337
+ const concatenated = sortedKeys.map((key) => `${key}=${params[key]}`).join("");
338
+ const signatureString = `${this.config.requestSecret}${concatenated}${this.config.requestSecret}`;
339
+ return crypto2.createHash("sha256").update(signatureString).digest("hex").toUpperCase();
340
+ }
341
+ /**
342
+ * Make API request to APS with timeout and retry support
343
+ */
344
+ async makeApiRequest(url, body, idempotencyKey) {
345
+ return makeRequest(url, body, {
346
+ timeout: this.options.timeout,
347
+ maxRetries: this.options.maxRetries,
348
+ logger: this.options.logger,
349
+ idempotencyKey
350
+ });
351
+ }
352
+ /**
353
+ * Generate a payment link URL (alias for create)
354
+ */
355
+ async generateUrl(options) {
356
+ const response = await this.create(options);
357
+ return response.url;
358
+ }
359
+ };
360
+
361
+ // src/modules/hosted-checkout.ts
362
+ import crypto3 from "crypto";
363
+ var HostedCheckoutModule = class {
364
+ constructor(config, _options) {
365
+ this.config = config;
366
+ }
367
+ /**
368
+ * Create a hosted checkout session
369
+ */
370
+ async create(checkoutOptions) {
371
+ try {
372
+ validateRequiredFields(checkoutOptions, ["order"]);
373
+ validateRequiredFields(checkoutOptions.order, ["amount", "currency"]);
374
+ if (checkoutOptions.order.customer?.email) {
375
+ if (!validateEmail(checkoutOptions.order.customer.email)) {
376
+ throw new Error("Invalid customer email format");
377
+ }
378
+ }
379
+ const orderId = checkoutOptions.order.id || generateOrderId();
380
+ const amount = checkoutOptions.order.amount;
381
+ const currency = checkoutOptions.order.currency || this.config.currency;
382
+ const params = {
383
+ command: "PURCHASE",
384
+ access_code: this.config.accessCode,
385
+ merchant_identifier: this.config.merchantId,
386
+ merchant_reference: orderId,
387
+ amount: amount.toString(),
388
+ currency,
389
+ language: this.config.language || "en",
390
+ customer_email: checkoutOptions.order.customer?.email || "customer@example.com"
391
+ // Required by APS
392
+ };
393
+ if (checkoutOptions.order.description) {
394
+ params.order_description = checkoutOptions.order.description;
395
+ }
396
+ if (checkoutOptions.order.customer?.email) {
397
+ params.customer_email = checkoutOptions.order.customer.email;
398
+ }
399
+ if (checkoutOptions.order.customer?.name) {
400
+ params.customer_name = checkoutOptions.order.customer.name;
401
+ }
402
+ if (checkoutOptions.order.customer?.phone) {
403
+ params.customer_phone = checkoutOptions.order.customer.phone;
404
+ }
405
+ if (checkoutOptions.order.customer?.billingAddress) {
406
+ const addr = checkoutOptions.order.customer.billingAddress;
407
+ if (addr.street) params.billing_address = addr.street;
408
+ if (addr.city) params.billing_city = addr.city;
409
+ if (addr.state) params.billing_state = addr.state;
410
+ if (addr.country) params.billing_country = addr.country;
411
+ if (addr.postalCode) params.billing_postal_code = addr.postalCode;
412
+ }
413
+ if (checkoutOptions.successUrl) {
414
+ params.return_url = checkoutOptions.successUrl;
415
+ } else if (checkoutOptions.failureUrl) {
416
+ params.return_url = checkoutOptions.failureUrl;
417
+ } else if (checkoutOptions.cancelUrl) {
418
+ params.return_url = checkoutOptions.cancelUrl;
419
+ }
420
+ if (checkoutOptions.allowedPaymentMethods && checkoutOptions.allowedPaymentMethods.length > 0) {
421
+ params.payment_option = String(checkoutOptions.allowedPaymentMethods[0]);
422
+ }
423
+ if (checkoutOptions.hideShipping) {
424
+ params.hide_shipping = "YES";
425
+ }
426
+ if (checkoutOptions.metadata) {
427
+ for (const [key, value] of Object.entries(checkoutOptions.metadata)) {
428
+ params[`merchant_param_${key}`] = value;
429
+ }
430
+ }
431
+ const sortedKeys = Object.keys(params).sort();
432
+ const concatenated = sortedKeys.map((key) => `${key}=${params[key]}`).join("");
433
+ const signatureString = `${this.config.requestSecret}${concatenated}${this.config.requestSecret}`;
434
+ params.signature = crypto3.createHash("sha256").update(signatureString).digest("hex");
435
+ const checkoutUrl = getHostedCheckoutUrl(this.config.environment);
436
+ const status = "pending";
437
+ return {
438
+ transactionId: orderId,
439
+ orderId,
440
+ status,
441
+ amount,
442
+ currency,
443
+ redirectForm: {
444
+ url: checkoutUrl,
445
+ method: "POST",
446
+ params
447
+ },
448
+ rawResponse: params
449
+ };
450
+ } catch (error) {
451
+ const apsError = {
452
+ code: "HOSTED_CHECKOUT_ERROR",
453
+ message: error instanceof Error ? error.message : "Failed to create hosted checkout",
454
+ rawResponse: error
455
+ };
456
+ throw new APSException(apsError);
457
+ }
458
+ }
459
+ /**
460
+ * Get the redirect URL for hosted checkout
461
+ */
462
+ async getRedirectUrl(options) {
463
+ const response = await this.create(options);
464
+ if (response.redirectForm) {
465
+ return response.redirectForm.url;
466
+ }
467
+ throw new APSException({
468
+ code: "NO_REDIRECT_URL",
469
+ message: "No redirect URL available"
470
+ });
471
+ }
472
+ };
473
+
474
+ // src/modules/custom-payment-page.ts
475
+ import crypto4 from "crypto";
476
+ var CustomPaymentPageModule = class {
477
+ constructor(config, options) {
478
+ this.config = config;
479
+ this.options = options;
480
+ }
481
+ /**
482
+ * Get tokenization form data
483
+ * This form should be submitted from the frontend to APS
484
+ */
485
+ getTokenizationForm(options) {
486
+ const merchantRef = options.merchantReference || `token_${Date.now()}`;
487
+ const params = {
488
+ service_command: "TOKENIZATION",
489
+ language: this.config.language || "en",
490
+ merchant_identifier: this.config.merchantId,
491
+ access_code: this.config.accessCode,
492
+ return_url: options.returnUrl,
493
+ merchant_reference: merchantRef
494
+ };
495
+ if (options.cardNumber) {
496
+ params.card_number = options.cardNumber;
497
+ }
498
+ if (options.expiryDate) {
499
+ params.expiry_date = options.expiryDate;
500
+ }
501
+ if (options.cardSecurityCode) {
502
+ params.card_security_code = options.cardSecurityCode;
503
+ }
504
+ if (options.cardHolderName) {
505
+ params.card_holder_name = options.cardHolderName;
506
+ }
507
+ const sortedKeys = Object.keys(params).sort();
508
+ const concatenated = sortedKeys.map((key) => `${key}=${params[key]}`).join("");
509
+ const signatureString = `${this.config.requestSecret}${concatenated}${this.config.requestSecret}`;
510
+ params.signature = crypto4.createHash("sha256").update(signatureString).digest("hex");
511
+ const url = getHostedCheckoutUrl(this.config.environment);
512
+ return {
513
+ url,
514
+ method: "POST",
515
+ params
516
+ };
517
+ }
518
+ /**
519
+ * Get create token form data (for saving cards without charging)
520
+ */
521
+ getCreateTokenForm(options) {
522
+ const merchantRef = options.merchantReference || `createtoken_${Date.now()}`;
523
+ const params = {
524
+ service_command: "CREATE_TOKEN",
525
+ language: this.config.language || "en",
526
+ merchant_identifier: this.config.merchantId,
527
+ access_code: this.config.accessCode,
528
+ return_url: options.returnUrl,
529
+ merchant_reference: merchantRef
530
+ };
531
+ if (options.cardNumber) {
532
+ params.card_number = options.cardNumber;
533
+ }
534
+ if (options.expiryDate) {
535
+ params.expiry_date = options.expiryDate;
536
+ }
537
+ if (options.cardHolderName) {
538
+ params.card_holder_name = options.cardHolderName;
539
+ }
540
+ const sortedKeys = Object.keys(params).sort();
541
+ const concatenated = sortedKeys.map((key) => `${key}=${params[key]}`).join("");
542
+ const signatureString = `${this.config.requestSecret}${concatenated}${this.config.requestSecret}`;
543
+ params.signature = crypto4.createHash("sha256").update(signatureString).digest("hex");
544
+ const url = getHostedCheckoutUrl(this.config.environment);
545
+ return {
546
+ url,
547
+ method: "POST",
548
+ params
549
+ };
550
+ }
551
+ /**
552
+ * Charge using a token received from tokenization
553
+ * This is a server-to-server call
554
+ */
555
+ async chargeWithToken(options) {
556
+ try {
557
+ validateRequiredFields(options, ["order", "tokenName", "customerEmail"]);
558
+ validateRequiredFields(options.order, ["amount", "currency"]);
559
+ if (!validateEmail(options.customerEmail)) {
560
+ throw new Error("Invalid customer email format");
561
+ }
562
+ const orderId = options.order.id || generateOrderId();
563
+ const amount = options.order.amount;
564
+ const currency = options.order.currency;
565
+ const requestBody = {
566
+ command: "PURCHASE",
567
+ access_code: this.config.accessCode,
568
+ merchant_identifier: this.config.merchantId,
569
+ merchant_reference: orderId,
570
+ amount: amount.toString(),
571
+ currency,
572
+ language: this.config.language || "en",
573
+ customer_email: options.customerEmail,
574
+ token_name: options.tokenName
575
+ };
576
+ if (options.order.description) {
577
+ requestBody.order_description = options.order.description;
578
+ }
579
+ if (options.customerName) {
580
+ requestBody.customer_name = options.customerName;
581
+ }
582
+ if (options.customerPhone) {
583
+ requestBody.customer_phone = options.customerPhone;
584
+ }
585
+ if (options.returnUrl) {
586
+ requestBody.return_url = options.returnUrl;
587
+ }
588
+ const sortedKeys = Object.keys(requestBody).sort();
589
+ const concatenated = sortedKeys.map((key) => `${key}=${requestBody[key]}`).join("");
590
+ const signatureString = `${this.config.requestSecret}${concatenated}${this.config.requestSecret}`;
591
+ requestBody.signature = crypto4.createHash("sha256").update(signatureString).digest("hex");
592
+ const apiUrl = getApiUrl(this.config.environment);
593
+ const response = await this.makeApiRequest(`${apiUrl}/FortAPI/paymentApi`, requestBody);
594
+ const isSuccess = response.status?.toString() === "20" || response.response_code?.toString() === "00000" || response.response_message?.toLowerCase() === "success";
595
+ if (!isSuccess) {
596
+ if (response["3ds_url"] || response.acs_url) {
597
+ return {
598
+ transactionId: response.fort_id || orderId,
599
+ orderId,
600
+ status: "pending",
601
+ amount,
602
+ currency,
603
+ authenticationUrl: response["3ds_url"] || response.acs_url,
604
+ redirectForm: {
605
+ url: response["3ds_url"] || response.acs_url,
606
+ method: "POST",
607
+ params: response
608
+ },
609
+ message: response.response_message,
610
+ rawResponse: response
611
+ };
612
+ }
613
+ throw new APSException({
614
+ code: response.response_code?.toString() || "PAYMENT_ERROR",
615
+ message: response.response_message || "Payment failed",
616
+ rawResponse: response
617
+ });
618
+ }
619
+ return {
620
+ transactionId: response.fort_id || orderId,
621
+ orderId,
622
+ status: "captured",
623
+ amount,
624
+ currency,
625
+ paymentMethod: response.payment_option,
626
+ message: response.response_message,
627
+ rawResponse: response
628
+ };
629
+ } catch (error) {
630
+ if (error instanceof APSException) {
631
+ throw error;
632
+ }
633
+ const apsError = {
634
+ code: "CUSTOM_PAYMENT_ERROR",
635
+ message: error instanceof Error ? error.message : "Failed to process payment",
636
+ rawResponse: error
637
+ };
638
+ throw new APSException(apsError);
639
+ }
640
+ }
641
+ /**
642
+ * Alias for chargeWithToken for backwards compatibility
643
+ */
644
+ async charge(options) {
645
+ if (options.cardToken) {
646
+ return this.chargeWithToken({
647
+ order: options.order,
648
+ tokenName: options.cardToken,
649
+ customerEmail: options.order.customer?.email || "customer@example.com",
650
+ returnUrl: options.returnUrl
651
+ });
652
+ }
653
+ throw new APSException({
654
+ code: "MISSING_TOKEN",
655
+ message: "Card token is required. Use getTokenizationForm() to collect card details first."
656
+ });
657
+ }
658
+ /**
659
+ * Make API request to APS with timeout and retry support
660
+ */
661
+ async makeApiRequest(url, body, idempotencyKey) {
662
+ return makeRequest(url, body, {
663
+ timeout: this.options.timeout,
664
+ maxRetries: this.options.maxRetries,
665
+ logger: this.options.logger,
666
+ idempotencyKey
667
+ });
668
+ }
669
+ };
670
+
671
+ // src/modules/tokenization.ts
672
+ var TokenizationModule = class {
673
+ constructor(config, options) {
674
+ this.config = config;
675
+ this.options = options;
676
+ }
677
+ /**
678
+ * Tokenize card details
679
+ */
680
+ async create(options) {
681
+ try {
682
+ validateRequiredFields(options, ["cardNumber", "expiryMonth", "expiryYear", "cvv"]);
683
+ if (!validateCardNumber(options.cardNumber)) {
684
+ throw new APSException({
685
+ code: "INVALID_CARD",
686
+ message: "Invalid card number format",
687
+ rawResponse: {}
688
+ });
689
+ }
690
+ if (!validateExpiryDate(options.expiryMonth, options.expiryYear)) {
691
+ throw new APSException({
692
+ code: "INVALID_EXPIRY",
693
+ message: "Invalid or expired card",
694
+ rawResponse: {}
695
+ });
696
+ }
697
+ if (!validateCVV(options.cvv)) {
698
+ throw new APSException({
699
+ code: "INVALID_CVV",
700
+ message: "Invalid CVV format",
701
+ rawResponse: {}
702
+ });
703
+ }
704
+ const params = {
705
+ command: "tokenize",
706
+ access_code: this.config.accessCode,
707
+ merchant_id: this.config.merchantId,
708
+ language: this.config.language,
709
+ response_format: "json"
710
+ };
711
+ params.card_number = options.cardNumber;
712
+ params.expiry_month = options.expiryMonth;
713
+ params.expiry_year = options.expiryYear;
714
+ params.cvv = options.cvv;
715
+ if (options.cardholderName) {
716
+ params.card_holder_name = options.cardholderName;
717
+ }
718
+ const signatureString = buildQueryString(params);
719
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
720
+ const apiUrl = getApiUrl(this.config.environment);
721
+ const response = await this.makeTokenizeRequest(`${apiUrl}/tokenize`, params);
722
+ if (response.response_code?.toString() !== "00") {
723
+ throw new APSException({
724
+ code: response.response_code?.toString() || "TOKENIZE_ERROR",
725
+ message: response.response_message || "Failed to tokenize card",
726
+ rawResponse: response
727
+ });
728
+ }
729
+ return {
730
+ token: response.card_token,
731
+ last4: options.cardNumber.slice(-4),
732
+ brand: this.detectCardBrand(options.cardNumber),
733
+ expiryMonth: options.expiryMonth,
734
+ expiryYear: options.expiryYear
735
+ };
736
+ } catch (error) {
737
+ if (error instanceof APSException) {
738
+ throw error;
739
+ }
740
+ const apsError = {
741
+ code: "TOKENIZE_ERROR",
742
+ message: error instanceof Error ? error.message : "Failed to tokenize card",
743
+ rawResponse: error
744
+ };
745
+ throw new APSException(apsError);
746
+ }
747
+ }
748
+ /**
749
+ * Verify a token (check if it's still valid)
750
+ */
751
+ async verify(token) {
752
+ try {
753
+ const params = {
754
+ command: "verify_token",
755
+ access_code: this.config.accessCode,
756
+ merchant_id: this.config.merchantId,
757
+ card_token: token,
758
+ response_format: "json"
759
+ };
760
+ const signatureString = buildQueryString(params);
761
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
762
+ const apiUrl = getApiUrl(this.config.environment);
763
+ const response = await this.makeTokenizeRequest(`${apiUrl}/verify_token`, params);
764
+ return response.response_code?.toString() === "00";
765
+ } catch {
766
+ return false;
767
+ }
768
+ }
769
+ /**
770
+ * Delete/Invalidate a token
771
+ */
772
+ async delete(token) {
773
+ try {
774
+ const params = {
775
+ command: "delete_token",
776
+ access_code: this.config.accessCode,
777
+ merchant_id: this.config.merchantId,
778
+ card_token: token,
779
+ response_format: "json"
780
+ };
781
+ const signatureString = buildQueryString(params);
782
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
783
+ const apiUrl = getApiUrl(this.config.environment);
784
+ const response = await this.makeTokenizeRequest(`${apiUrl}/delete_token`, params);
785
+ return response.response_code?.toString() === "00";
786
+ } catch {
787
+ return false;
788
+ }
789
+ }
790
+ /**
791
+ * List saved cards for a customer
792
+ * @param customerId - Customer identifier (email or user ID)
793
+ */
794
+ async list(customerId) {
795
+ try {
796
+ const params = {
797
+ command: "get_cards",
798
+ access_code: this.config.accessCode,
799
+ merchant_id: this.config.merchantId,
800
+ customer_email: customerId,
801
+ response_format: "json"
802
+ };
803
+ const signatureString = buildQueryString(params);
804
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
805
+ const apiUrl = getApiUrl(this.config.environment);
806
+ const response = await this.makeTokenizeRequest(`${apiUrl}/get_cards`, params);
807
+ const cards = [];
808
+ if (response.cards && Array.isArray(response.cards)) {
809
+ for (const card of response.cards) {
810
+ cards.push({
811
+ token: card.card_token,
812
+ last4: card.last4_digits || "****",
813
+ brand: card.card_brand || this.detectCardBrand(card.card_number || ""),
814
+ expiryMonth: card.expiry_month,
815
+ expiryYear: card.expiry_year,
816
+ cardholderName: card.card_holder_name,
817
+ isDefault: card.is_default === "true" || card.is_default === true
818
+ });
819
+ }
820
+ }
821
+ return {
822
+ customerId,
823
+ cards,
824
+ total: cards.length
825
+ };
826
+ } catch (error) {
827
+ if (error instanceof APSException) {
828
+ throw error;
829
+ }
830
+ const apsError = {
831
+ code: "LIST_CARDS_ERROR",
832
+ message: error instanceof Error ? error.message : "Failed to list saved cards",
833
+ rawResponse: error
834
+ };
835
+ throw new APSException(apsError);
836
+ }
837
+ }
838
+ /**
839
+ * Detect card brand from card number
840
+ */
841
+ detectCardBrand(cardNumber) {
842
+ const number = cardNumber.replace(/\D/g, "");
843
+ if (/^4/.test(number)) return "visa";
844
+ if (/^5[1-5]/.test(number)) return "mastercard";
845
+ if (/^3[47]/.test(number)) return "amex";
846
+ if (/^6(?:011|5)/.test(number)) return "discover";
847
+ if (/^(?:2131|1800|35)/.test(number)) return "jcb";
848
+ if (/^9792/.test(number)) return "troy";
849
+ return "unknown";
850
+ }
851
+ /**
852
+ * Make tokenization API request with timeout and retry support
853
+ */
854
+ async makeTokenizeRequest(url, params) {
855
+ const data = await makeRequest(url, params, {
856
+ timeout: this.options.timeout,
857
+ maxRetries: this.options.maxRetries,
858
+ logger: this.options.logger
859
+ });
860
+ if (data.response_code?.toString() !== "00" && data.response_code?.toString() !== "0") {
861
+ throw new APSException({
862
+ code: data.response_code?.toString() || "TOKENIZE_ERROR",
863
+ message: data.response_message || "Tokenization request failed",
864
+ rawResponse: data
865
+ });
866
+ }
867
+ return data;
868
+ }
869
+ };
870
+
871
+ // src/modules/payments.ts
872
+ var PaymentsModule = class {
873
+ constructor(config, options) {
874
+ this.config = config;
875
+ this.options = options;
876
+ }
877
+ /**
878
+ * Capture an authorized payment
879
+ */
880
+ async capture(options) {
881
+ try {
882
+ validateRequiredFields(options, ["transactionId"]);
883
+ const params = {
884
+ command: "capture",
885
+ access_code: this.config.accessCode,
886
+ merchant_id: this.config.merchantId,
887
+ transaction_id: options.transactionId,
888
+ response_format: "json"
889
+ };
890
+ if (options.amount) {
891
+ params.amount = options.amount.toString();
892
+ }
893
+ const signatureString = buildQueryString(params);
894
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
895
+ const apiUrl = getApiUrl(this.config.environment);
896
+ const response = await this.makeApiRequest(`${apiUrl}/capture`, params);
897
+ const status = this.mapResponseStatus(response);
898
+ return {
899
+ captureId: response.transaction_id || options.transactionId,
900
+ transactionId: options.transactionId,
901
+ amount: options.amount || parseInt(response.amount) || 0,
902
+ status,
903
+ message: response.response_message,
904
+ rawResponse: response
905
+ };
906
+ } catch (error) {
907
+ const apsError = {
908
+ code: "CAPTURE_ERROR",
909
+ message: error instanceof Error ? error.message : "Failed to capture payment",
910
+ rawResponse: error
911
+ };
912
+ throw new APSException(apsError);
913
+ }
914
+ }
915
+ /**
916
+ * Refund a payment (full or partial)
917
+ */
918
+ async refund(options) {
919
+ try {
920
+ validateRequiredFields(options, ["transactionId"]);
921
+ const params = {
922
+ command: "refund",
923
+ access_code: this.config.accessCode,
924
+ merchant_id: this.config.merchantId,
925
+ transaction_id: options.transactionId,
926
+ response_format: "json"
927
+ };
928
+ if (options.amount) {
929
+ params.amount = options.amount.toString();
930
+ }
931
+ if (options.reason) {
932
+ params.refund_reason = options.reason;
933
+ }
934
+ const signatureString = buildQueryString(params);
935
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
936
+ const apiUrl = getApiUrl(this.config.environment);
937
+ const response = await this.makeApiRequest(`${apiUrl}/refund`, params);
938
+ const status = this.mapResponseStatus(response);
939
+ return {
940
+ refundId: response.transaction_id || `refund_${Date.now()}`,
941
+ transactionId: options.transactionId,
942
+ amount: options.amount || parseInt(response.amount) || 0,
943
+ status,
944
+ message: response.response_message,
945
+ rawResponse: response
946
+ };
947
+ } catch (error) {
948
+ const apsError = {
949
+ code: "REFUND_ERROR",
950
+ message: error instanceof Error ? error.message : "Failed to process refund",
951
+ rawResponse: error
952
+ };
953
+ throw new APSException(apsError);
954
+ }
955
+ }
956
+ /**
957
+ * Void an authorized transaction
958
+ */
959
+ async void(options) {
960
+ try {
961
+ validateRequiredFields(options, ["transactionId"]);
962
+ const params = {
963
+ command: "void",
964
+ access_code: this.config.accessCode,
965
+ merchant_id: this.config.merchantId,
966
+ transaction_id: options.transactionId,
967
+ response_format: "json"
968
+ };
969
+ if (options.reason) {
970
+ params.void_reason = options.reason;
971
+ }
972
+ const signatureString = buildQueryString(params);
973
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
974
+ const apiUrl = getApiUrl(this.config.environment);
975
+ const response = await this.makeApiRequest(`${apiUrl}/void`, params);
976
+ const status = this.mapResponseStatus(response);
977
+ return {
978
+ voidId: response.transaction_id || `void_${Date.now()}`,
979
+ transactionId: options.transactionId,
980
+ status,
981
+ message: response.response_message,
982
+ rawResponse: response
983
+ };
984
+ } catch (error) {
985
+ const apsError = {
986
+ code: "VOID_ERROR",
987
+ message: error instanceof Error ? error.message : "Failed to void transaction",
988
+ rawResponse: error
989
+ };
990
+ throw new APSException(apsError);
991
+ }
992
+ }
993
+ /**
994
+ * Query transaction status
995
+ */
996
+ async query(options) {
997
+ try {
998
+ if (!options.transactionId && !options.orderId) {
999
+ throw new Error("Either transactionId or orderId is required");
1000
+ }
1001
+ const params = {
1002
+ command: "query_transaction",
1003
+ access_code: this.config.accessCode,
1004
+ merchant_id: this.config.merchantId,
1005
+ response_format: "json"
1006
+ };
1007
+ if (options.transactionId) {
1008
+ params.transaction_id = options.transactionId;
1009
+ }
1010
+ if (options.orderId) {
1011
+ params.merchant_order_id = options.orderId;
1012
+ }
1013
+ const signatureString = buildQueryString(params);
1014
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
1015
+ const apiUrl = getApiUrl(this.config.environment);
1016
+ const response = await this.makeApiRequest(`${apiUrl}/query_transaction`, params);
1017
+ return {
1018
+ transactionId: response.transaction_id,
1019
+ orderId: response.merchant_order_id,
1020
+ amount: parseInt(response.amount) || 0,
1021
+ currency: response.currency,
1022
+ status: this.mapResponseStatus(response),
1023
+ paymentMethod: response.payment_option,
1024
+ createdAt: response.transaction_date,
1025
+ rawResponse: response
1026
+ };
1027
+ } catch (error) {
1028
+ const apsError = {
1029
+ code: "QUERY_ERROR",
1030
+ message: error instanceof Error ? error.message : "Failed to query transaction",
1031
+ rawResponse: error
1032
+ };
1033
+ throw new APSException(apsError);
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Map APS response code to transaction status
1038
+ */
1039
+ mapResponseStatus(response) {
1040
+ const code = response.response_code?.toString() || "";
1041
+ const status = response.status?.toUpperCase();
1042
+ if (code === "00" || code === "0") {
1043
+ if (status === "CAPTURED") return "captured";
1044
+ if (status === "AUTHORIZED") return "authorized";
1045
+ return "captured";
1046
+ }
1047
+ if (code === "03" || status === "AUTHORIZED") {
1048
+ return "authorized";
1049
+ }
1050
+ if (status === "PENDING" || status === "3DS") {
1051
+ return "pending";
1052
+ }
1053
+ if (status === "VOIDED" || response.void_status === "true") {
1054
+ return "voided";
1055
+ }
1056
+ if (status === "REFUNDED" || response.refund_status === "true") {
1057
+ return "refunded";
1058
+ }
1059
+ if (status === "CANCELLED" || status === "CANCELED") {
1060
+ return "cancelled";
1061
+ }
1062
+ if (status === "FAILED" || code !== "00") {
1063
+ return "failed";
1064
+ }
1065
+ return "pending";
1066
+ }
1067
+ /**
1068
+ * Make API request to APS with timeout and retry support
1069
+ */
1070
+ async makeApiRequest(url, params, idempotencyKey) {
1071
+ const data = await makeRequest(url, params, {
1072
+ timeout: this.options.timeout,
1073
+ maxRetries: this.options.maxRetries,
1074
+ logger: this.options.logger,
1075
+ idempotencyKey
1076
+ });
1077
+ if (data.response_code?.toString() !== "00" && data.response_code?.toString() !== "0") {
1078
+ throw new APSException({
1079
+ code: data.response_code?.toString() || "API_ERROR",
1080
+ message: data.response_message || "API request failed",
1081
+ rawResponse: data
1082
+ });
1083
+ }
1084
+ return data;
1085
+ }
1086
+ };
1087
+
1088
+ // src/modules/webhooks.ts
1089
+ var WebhooksModule = class {
1090
+ constructor(config) {
1091
+ this.config = config;
1092
+ }
1093
+ /**
1094
+ * Verify webhook signature
1095
+ */
1096
+ verifySignature(payload, signature) {
1097
+ return verifyHMAC(payload, signature, this.config.responseSecret);
1098
+ }
1099
+ /**
1100
+ * Construct a webhook event from raw payload
1101
+ */
1102
+ constructEvent(payload) {
1103
+ try {
1104
+ const eventType = this.mapEventType(payload);
1105
+ const status = this.mapStatus(payload.status);
1106
+ return {
1107
+ id: payload.transaction_id || `evt_${Date.now()}`,
1108
+ type: eventType,
1109
+ timestamp: payload.transaction_date ? new Date(payload.transaction_date) : /* @__PURE__ */ new Date(),
1110
+ data: {
1111
+ transactionId: payload.transaction_id,
1112
+ orderId: payload.merchant_order_id,
1113
+ amount: parseInt(payload.amount) || 0,
1114
+ currency: payload.currency,
1115
+ status,
1116
+ paymentMethod: payload.payment_option,
1117
+ metadata: payload.metadata
1118
+ },
1119
+ rawPayload: payload
1120
+ };
1121
+ } catch (error) {
1122
+ const apsError = {
1123
+ code: "WEBHOOK_PARSE_ERROR",
1124
+ message: error instanceof Error ? error.message : "Failed to parse webhook event",
1125
+ rawResponse: payload
1126
+ };
1127
+ throw new APSException(apsError);
1128
+ }
1129
+ }
1130
+ /**
1131
+ * Map APS event to webhook event type
1132
+ */
1133
+ mapEventType(payload) {
1134
+ const status = payload.status?.toUpperCase();
1135
+ const command = payload.command;
1136
+ if (command === "refund") {
1137
+ if (status === "SUCCESS" || payload.response_code === "00") {
1138
+ return "refund.success";
1139
+ }
1140
+ return "refund.failed";
1141
+ }
1142
+ switch (status) {
1143
+ case "SUCCESS":
1144
+ case "CAPTURED":
1145
+ case "COMPLETED":
1146
+ return "payment.success";
1147
+ case "FAILED":
1148
+ case "DECLINED":
1149
+ return "payment.failed";
1150
+ case "PENDING":
1151
+ case "3DS":
1152
+ return "payment.pending";
1153
+ default:
1154
+ return "payment.pending";
1155
+ }
1156
+ }
1157
+ /**
1158
+ * Map APS status to transaction status
1159
+ */
1160
+ mapStatus(status) {
1161
+ if (!status) return "pending";
1162
+ const upperStatus = status.toUpperCase();
1163
+ switch (upperStatus) {
1164
+ case "SUCCESS":
1165
+ case "CAPTURED":
1166
+ case "COMPLETED":
1167
+ return "captured";
1168
+ case "AUTHORIZED":
1169
+ return "authorized";
1170
+ case "PENDING":
1171
+ case "3DS":
1172
+ return "pending";
1173
+ case "FAILED":
1174
+ case "DECLINED":
1175
+ return "failed";
1176
+ case "VOIDED":
1177
+ return "voided";
1178
+ case "REFUNDED":
1179
+ return "refunded";
1180
+ case "CANCELLED":
1181
+ case "CANCELED":
1182
+ return "cancelled";
1183
+ default:
1184
+ return "pending";
1185
+ }
1186
+ }
1187
+ /**
1188
+ * Verify and construct event in one step
1189
+ */
1190
+ safeConstructEvent(payload, signature) {
1191
+ if (!this.verifySignature(payload, signature)) {
1192
+ throw new APSException({
1193
+ code: "INVALID_SIGNATURE",
1194
+ message: "Webhook signature verification failed",
1195
+ statusCode: 401
1196
+ });
1197
+ }
1198
+ const parsedPayload = typeof payload === "string" ? JSON.parse(payload) : payload;
1199
+ return this.constructEvent(parsedPayload);
1200
+ }
1201
+ };
1202
+
1203
+ // src/modules/recurring.ts
1204
+ var RecurringModule = class {
1205
+ constructor(config, options) {
1206
+ this.config = config;
1207
+ this.options = options;
1208
+ }
1209
+ /**
1210
+ * Process a recurring payment using a saved token
1211
+ *
1212
+ * This method is designed to be called from server-side code,
1213
+ * typically in a cron job or scheduled task for subscription billing.
1214
+ *
1215
+ * @param options - Recurring payment options
1216
+ * @returns Recurring payment response
1217
+ *
1218
+ * @example
1219
+ * ```typescript
1220
+ * // Monthly subscription charge
1221
+ * const payment = await aps.recurring.process({
1222
+ * order: {
1223
+ * id: `sub_${customerId}_${Date.now()}`,
1224
+ * amount: 2999, // $29.99
1225
+ * currency: 'USD',
1226
+ * description: 'Monthly Pro Plan'
1227
+ * },
1228
+ * tokenName: savedCard.token,
1229
+ * agreementId: savedCard.agreementId,
1230
+ * customerEmail: customer.email,
1231
+ * customerName: customer.name
1232
+ * });
1233
+ *
1234
+ * if (payment.status === 'captured') {
1235
+ * await sendInvoice(customer, payment);
1236
+ * } else {
1237
+ * await notifyPaymentFailed(customer, payment);
1238
+ * }
1239
+ * ```
1240
+ */
1241
+ async process(options) {
1242
+ try {
1243
+ validateRequiredFields(options, ["tokenName", "agreementId", "customerEmail"]);
1244
+ validateRequiredFields(options.order, ["id", "amount", "currency"]);
1245
+ const params = {
1246
+ command: "PURCHASE",
1247
+ access_code: this.config.accessCode,
1248
+ merchant_identifier: this.config.merchantId,
1249
+ merchant_reference: options.order.id,
1250
+ amount: Math.round(options.order.amount).toString(),
1251
+ currency: options.order.currency,
1252
+ eci: "RECURRING",
1253
+ language: this.config.language,
1254
+ customer_email: options.customerEmail,
1255
+ token_name: options.tokenName,
1256
+ agreement_id: options.agreementId,
1257
+ response_format: "json"
1258
+ };
1259
+ if (options.order.description) {
1260
+ params.order_description = options.order.description;
1261
+ }
1262
+ if (options.customerName) {
1263
+ params.customer_name = options.customerName;
1264
+ }
1265
+ if (options.customerPhone) {
1266
+ params.phone_number = options.customerPhone;
1267
+ }
1268
+ if (options.statementDescriptor) {
1269
+ params.statement_descriptor = options.statementDescriptor;
1270
+ }
1271
+ if (options.paymentOption) {
1272
+ params.payment_option = options.paymentOption;
1273
+ }
1274
+ if (options.settlementReference) {
1275
+ params.settlement_reference = options.settlementReference;
1276
+ }
1277
+ const signatureString = buildQueryString(params);
1278
+ params.signature = generateHMAC(signatureString, this.config.requestSecret);
1279
+ this.options.logger?.info?.("Processing recurring payment", {
1280
+ orderId: options.order.id,
1281
+ amount: options.order.amount,
1282
+ currency: options.order.currency,
1283
+ agreementId: options.agreementId
1284
+ });
1285
+ const apiUrl = getApiUrl(this.config.environment);
1286
+ const response = await this.makeApiRequest(`${apiUrl}/paymentApi`, params);
1287
+ const status = this.mapResponseStatus(response);
1288
+ return {
1289
+ transactionId: response.fort_id || response.transaction_id,
1290
+ orderId: options.order.id,
1291
+ agreementId: options.agreementId,
1292
+ amount: options.order.amount,
1293
+ currency: options.order.currency,
1294
+ status,
1295
+ paymentMethod: response.payment_option,
1296
+ authorizationCode: response.authorization_code,
1297
+ message: response.response_message,
1298
+ rawResponse: response
1299
+ };
1300
+ } catch (error) {
1301
+ this.options.logger?.error?.("Recurring payment failed", { error });
1302
+ const apsError = {
1303
+ code: "RECURRING_ERROR",
1304
+ message: error instanceof Error ? error.message : "Failed to process recurring payment",
1305
+ rawResponse: error
1306
+ };
1307
+ throw new APSException(apsError);
1308
+ }
1309
+ }
1310
+ /**
1311
+ * Process multiple recurring payments in batch
1312
+ *
1313
+ * Useful for processing all due subscriptions at once.
1314
+ * Returns results for all payments, including failures.
1315
+ *
1316
+ * @param payments - Array of recurring payment options
1317
+ * @returns Array of results with success/failure status
1318
+ *
1319
+ * @example
1320
+ * ```typescript
1321
+ * // Process all due subscriptions
1322
+ * const dueSubscriptions = await getDueSubscriptions();
1323
+ *
1324
+ * const results = await aps.recurring.processBatch(
1325
+ * dueSubscriptions.map(sub => ({
1326
+ * order: {
1327
+ * id: `sub_${sub.id}_${Date.now()}`,
1328
+ * amount: sub.amount,
1329
+ * currency: sub.currency,
1330
+ * description: sub.planName
1331
+ * },
1332
+ * tokenName: sub.tokenName,
1333
+ * agreementId: sub.agreementId,
1334
+ * customerEmail: sub.customerEmail
1335
+ * }))
1336
+ * );
1337
+ *
1338
+ * // Handle results
1339
+ * const successful = results.filter(r => r.success);
1340
+ * const failed = results.filter(r => !r.success);
1341
+ *
1342
+ * console.log(`Processed: ${successful.length} succeeded, ${failed.length} failed`);
1343
+ * ```
1344
+ */
1345
+ async processBatch(payments) {
1346
+ const results = [];
1347
+ for (const payment of payments) {
1348
+ try {
1349
+ const result = await this.process(payment);
1350
+ results.push({
1351
+ success: true,
1352
+ data: result,
1353
+ orderId: payment.order.id
1354
+ });
1355
+ } catch (error) {
1356
+ results.push({
1357
+ success: false,
1358
+ error: error instanceof Error ? error.message : "Unknown error",
1359
+ orderId: payment.order.id
1360
+ });
1361
+ }
1362
+ }
1363
+ return results;
1364
+ }
1365
+ /**
1366
+ * Map APS response code to transaction status
1367
+ */
1368
+ mapResponseStatus(response) {
1369
+ const code = response.response_code?.toString() || "";
1370
+ const status = response.status?.toString();
1371
+ if (code === "14000" || code === "00000" || status === "20") {
1372
+ return "captured";
1373
+ }
1374
+ if (status === "3" || status === "PENDING") {
1375
+ return "pending";
1376
+ }
1377
+ return "failed";
1378
+ }
1379
+ /**
1380
+ * Make API request to APS
1381
+ */
1382
+ async makeApiRequest(url, params) {
1383
+ const data = await makeRequest(url, params, {
1384
+ timeout: this.options.timeout,
1385
+ maxRetries: this.options.maxRetries,
1386
+ logger: this.options.logger
1387
+ });
1388
+ if (data.response_code?.toString() !== "14000" && data.response_code?.toString() !== "00000" && data.status?.toString() !== "20") {
1389
+ throw new APSException({
1390
+ code: data.response_code?.toString() || "API_ERROR",
1391
+ message: data.response_message || "Recurring payment failed",
1392
+ rawResponse: data
1393
+ });
1394
+ }
1395
+ return data;
1396
+ }
1397
+ };
1398
+
1399
+ // src/client.ts
1400
+ var APSClient = class {
1401
+ /**
1402
+ * Create a new APS client instance
1403
+ */
1404
+ constructor(config, options = {}) {
1405
+ if (!config.merchantId) {
1406
+ throw new APSException({
1407
+ code: "MISSING_MERCHANT_ID",
1408
+ message: "Merchant ID is required"
1409
+ });
1410
+ }
1411
+ if (!config.accessCode) {
1412
+ throw new APSException({
1413
+ code: "MISSING_ACCESS_CODE",
1414
+ message: "Access code is required"
1415
+ });
1416
+ }
1417
+ if (!config.requestSecret) {
1418
+ throw new APSException({
1419
+ code: "MISSING_REQUEST_SECRET",
1420
+ message: "Request secret is required"
1421
+ });
1422
+ }
1423
+ if (!config.responseSecret) {
1424
+ throw new APSException({
1425
+ code: "MISSING_RESPONSE_SECRET",
1426
+ message: "Response secret is required"
1427
+ });
1428
+ }
1429
+ this.config = {
1430
+ ...config,
1431
+ environment: config.environment ?? "sandbox",
1432
+ currency: config.currency ?? "USD",
1433
+ language: config.language ?? "en"
1434
+ };
1435
+ this.options = {
1436
+ logger: options.logger ?? (this.config.environment === "sandbox" ? noopLogger : noopLogger),
1437
+ timeout: options.timeout ?? 3e4,
1438
+ maxRetries: options.maxRetries ?? 3,
1439
+ enableLogging: options.enableLogging ?? this.config.environment === "sandbox"
1440
+ };
1441
+ this.paymentLinks = new PaymentLinksModule(this.config, this.options);
1442
+ this.hostedCheckout = new HostedCheckoutModule(this.config, this.options);
1443
+ this.customPaymentPage = new CustomPaymentPageModule(this.config, this.options);
1444
+ this.tokens = new TokenizationModule(this.config, this.options);
1445
+ this.payments = new PaymentsModule(this.config, this.options);
1446
+ this.webhooks = new WebhooksModule(this.config);
1447
+ this.recurring = new RecurringModule(this.config, this.options);
1448
+ }
1449
+ /**
1450
+ * Get the base URL for redirects
1451
+ */
1452
+ getBaseUrl() {
1453
+ return getBaseUrl(this.config.environment);
1454
+ }
1455
+ /**
1456
+ * Get the API URL for server-to-server calls
1457
+ */
1458
+ getApiUrl() {
1459
+ return getApiUrl(this.config.environment);
1460
+ }
1461
+ /**
1462
+ * Verify a webhook signature
1463
+ */
1464
+ verifyWebhookSignature(payload, signature) {
1465
+ return this.webhooks.verifySignature(payload, signature);
1466
+ }
1467
+ /**
1468
+ * Construct a webhook event from raw payload
1469
+ */
1470
+ constructWebhookEvent(payload) {
1471
+ return this.webhooks.constructEvent(payload);
1472
+ }
1473
+ /**
1474
+ * Get the logger instance
1475
+ */
1476
+ getLogger() {
1477
+ return this.options.logger;
1478
+ }
1479
+ /**
1480
+ * Set a custom logger
1481
+ */
1482
+ setLogger(logger) {
1483
+ this.options.logger = logger;
1484
+ }
1485
+ };
1486
+
1487
+ // src/constants.ts
1488
+ var TestCards = {
1489
+ /**
1490
+ * Visa test cards
1491
+ */
1492
+ VISA: {
1493
+ /** Successful payment */
1494
+ SUCCESS: "4111111111111111",
1495
+ /** Declined payment */
1496
+ DECLINED: "4000000000000002",
1497
+ /** Insufficient funds */
1498
+ INSUFFICIENT_FUNDS: "4000000000009995",
1499
+ /** Lost card */
1500
+ LOST_CARD: "4000000000009987",
1501
+ /** Stolen card */
1502
+ STOLEN_CARD: "4000000000009979",
1503
+ /** Expired card */
1504
+ EXPIRED_CARD: "4000000000009961",
1505
+ /** Invalid CVV */
1506
+ INVALID_CVV: "4000000000000127",
1507
+ /** 3D Secure required */
1508
+ REQUIRES_3DS: "4000000000003220"
1509
+ },
1510
+ /**
1511
+ * Mastercard test cards
1512
+ */
1513
+ MASTERCARD: {
1514
+ /** Successful payment */
1515
+ SUCCESS: "5100000000000008",
1516
+ /** Declined payment */
1517
+ DECLINED: "5400000000000003",
1518
+ /** Insufficient funds */
1519
+ INSUFFICIENT_FUNDS: "5400000000000094",
1520
+ /** 3D Secure required */
1521
+ REQUIRES_3DS: "5400000000000094"
1522
+ },
1523
+ /**
1524
+ * MADA (Saudi Arabia) test cards
1525
+ */
1526
+ MADA: {
1527
+ /** Successful payment */
1528
+ SUCCESS: "5297410000000002",
1529
+ /** Declined payment */
1530
+ DECLINED: "5297410000000010",
1531
+ /** 3D Secure required */
1532
+ REQUIRES_3DS: "5297410000000028"
1533
+ },
1534
+ /**
1535
+ * American Express test cards
1536
+ */
1537
+ AMEX: {
1538
+ /** Successful payment */
1539
+ SUCCESS: "371449635398431",
1540
+ /** Declined payment */
1541
+ DECLINED: "378282246310005"
1542
+ },
1543
+ /**
1544
+ * Test card defaults
1545
+ */
1546
+ DEFAULTS: {
1547
+ /** Default expiry month (MM) */
1548
+ EXPIRY_MONTH: "12",
1549
+ /** Default expiry year (YY) */
1550
+ EXPIRY_YEAR: "25",
1551
+ /** Default CVV */
1552
+ CVV: "123",
1553
+ /** Default cardholder name */
1554
+ CARDHOLDER_NAME: "Test User"
1555
+ }
1556
+ };
1557
+ var ResponseCodes = {
1558
+ // Success Codes
1559
+ /** Transaction successful */
1560
+ SUCCESS: "00000",
1561
+ /** Payment link created successfully */
1562
+ PAYMENT_LINK_SUCCESS: "48000",
1563
+ /** Recurring payment successful */
1564
+ RECURRING_SUCCESS: "14000",
1565
+ // Authentication & Security
1566
+ /** 3D Secure authentication failed */
1567
+ AUTHENTICATION_FAILED: "10030",
1568
+ /** 3D Secure not enrolled */
1569
+ NOT_ENROLLED_3DS: "10031",
1570
+ /** Signature mismatch */
1571
+ SIGNATURE_MISMATCH: "00008",
1572
+ /** Invalid access code */
1573
+ INVALID_ACCESS_CODE: "00009",
1574
+ /** Invalid merchant identifier */
1575
+ INVALID_MERCHANT_ID: "00010",
1576
+ // Card Errors
1577
+ /** Card expired */
1578
+ CARD_EXPIRED: "10035",
1579
+ /** Invalid card number */
1580
+ INVALID_CARD_NUMBER: "10036",
1581
+ /** Invalid CVV */
1582
+ INVALID_CVV: "10037",
1583
+ /** Card not supported */
1584
+ CARD_NOT_SUPPORTED: "10038",
1585
+ /** Lost card */
1586
+ LOST_CARD: "10039",
1587
+ /** Stolen card */
1588
+ STOLEN_CARD: "10040",
1589
+ /** Restricted card */
1590
+ RESTRICTED_CARD: "10041",
1591
+ /** Card blocked */
1592
+ CARD_BLOCKED: "10042",
1593
+ /** Invalid expiry date */
1594
+ INVALID_EXPIRY: "10043",
1595
+ // Transaction Errors
1596
+ /** Transaction declined */
1597
+ DECLINED: "14001",
1598
+ /** Insufficient funds */
1599
+ INSUFFICIENT_FUNDS: "14002",
1600
+ /** Transaction limit exceeded */
1601
+ LIMIT_EXCEEDED: "14003",
1602
+ /** Invalid transaction */
1603
+ INVALID_TRANSACTION: "14004",
1604
+ /** Duplicate transaction */
1605
+ DUPLICATE_TRANSACTION: "14005",
1606
+ /** Transaction not allowed */
1607
+ TRANSACTION_NOT_ALLOWED: "14006",
1608
+ /** Transaction expired */
1609
+ TRANSACTION_EXPIRED: "14007",
1610
+ /** Transaction already captured */
1611
+ ALREADY_CAPTURED: "14008",
1612
+ /** Transaction already voided */
1613
+ ALREADY_VOIDED: "14009",
1614
+ /** Transaction already refunded */
1615
+ ALREADY_REFUNDED: "14010",
1616
+ // Amount Errors
1617
+ /** Invalid amount */
1618
+ INVALID_AMOUNT: "15001",
1619
+ /** Amount too small */
1620
+ AMOUNT_TOO_SMALL: "15002",
1621
+ /** Amount too large */
1622
+ AMOUNT_TOO_LARGE: "15003",
1623
+ /** Currency not supported */
1624
+ CURRENCY_NOT_SUPPORTED: "15004",
1625
+ // Parameter Errors
1626
+ /** Missing parameter */
1627
+ MISSING_PARAMETER: "00001",
1628
+ /** Invalid parameter format */
1629
+ INVALID_PARAMETER: "00002",
1630
+ /** Invalid command */
1631
+ INVALID_COMMAND: "00003",
1632
+ /** Invalid language */
1633
+ INVALID_LANGUAGE: "00004",
1634
+ /** Invalid currency */
1635
+ INVALID_CURRENCY: "00005",
1636
+ /** Invalid return URL */
1637
+ INVALID_RETURN_URL: "00006",
1638
+ /** Invalid customer email */
1639
+ INVALID_EMAIL: "00007",
1640
+ /** Parameter value not allowed */
1641
+ PARAMETER_VALUE_NOT_ALLOWED: "00033",
1642
+ // Tokenization Errors
1643
+ /** Token not found */
1644
+ TOKEN_NOT_FOUND: "16001",
1645
+ /** Token expired */
1646
+ TOKEN_EXPIRED: "16002",
1647
+ /** Token already used */
1648
+ TOKEN_ALREADY_USED: "16003",
1649
+ /** Invalid token */
1650
+ INVALID_TOKEN: "16004",
1651
+ // System Errors
1652
+ /** System error */
1653
+ SYSTEM_ERROR: "90001",
1654
+ /** Service unavailable */
1655
+ SERVICE_UNAVAILABLE: "90002",
1656
+ /** Timeout */
1657
+ TIMEOUT: "90003",
1658
+ /** Database error */
1659
+ DATABASE_ERROR: "90004",
1660
+ /** Internal error */
1661
+ INTERNAL_ERROR: "90005"
1662
+ };
1663
+ var ErrorCategories = {
1664
+ /** Success - no error */
1665
+ SUCCESS: "success",
1666
+ /** Card-related errors (expired, invalid, blocked) */
1667
+ CARD_ERROR: "card_error",
1668
+ /** Authentication errors (3DS, signature) */
1669
+ AUTHENTICATION_ERROR: "authentication_error",
1670
+ /** Transaction errors (declined, insufficient funds) */
1671
+ TRANSACTION_ERROR: "transaction_error",
1672
+ /** Amount/currency errors */
1673
+ AMOUNT_ERROR: "amount_error",
1674
+ /** Parameter validation errors */
1675
+ VALIDATION_ERROR: "validation_error",
1676
+ /** Tokenization errors */
1677
+ TOKEN_ERROR: "token_error",
1678
+ /** System/technical errors */
1679
+ SYSTEM_ERROR: "system_error",
1680
+ /** Errors that can be retried */
1681
+ RETRYABLE: "retryable",
1682
+ /** Errors that should not be retried */
1683
+ NON_RETRYABLE: "non_retryable"
1684
+ };
1685
+ var ERROR_CODE_TO_CATEGORY = {
1686
+ [ResponseCodes.SUCCESS]: ErrorCategories.SUCCESS,
1687
+ [ResponseCodes.PAYMENT_LINK_SUCCESS]: ErrorCategories.SUCCESS,
1688
+ [ResponseCodes.RECURRING_SUCCESS]: ErrorCategories.SUCCESS,
1689
+ // Card errors
1690
+ [ResponseCodes.CARD_EXPIRED]: ErrorCategories.CARD_ERROR,
1691
+ [ResponseCodes.INVALID_CARD_NUMBER]: ErrorCategories.CARD_ERROR,
1692
+ [ResponseCodes.INVALID_CVV]: ErrorCategories.CARD_ERROR,
1693
+ [ResponseCodes.CARD_NOT_SUPPORTED]: ErrorCategories.CARD_ERROR,
1694
+ [ResponseCodes.LOST_CARD]: ErrorCategories.CARD_ERROR,
1695
+ [ResponseCodes.STOLEN_CARD]: ErrorCategories.CARD_ERROR,
1696
+ [ResponseCodes.RESTRICTED_CARD]: ErrorCategories.CARD_ERROR,
1697
+ [ResponseCodes.CARD_BLOCKED]: ErrorCategories.CARD_ERROR,
1698
+ [ResponseCodes.INVALID_EXPIRY]: ErrorCategories.CARD_ERROR,
1699
+ // Authentication errors
1700
+ [ResponseCodes.AUTHENTICATION_FAILED]: ErrorCategories.AUTHENTICATION_ERROR,
1701
+ [ResponseCodes.NOT_ENROLLED_3DS]: ErrorCategories.AUTHENTICATION_ERROR,
1702
+ [ResponseCodes.SIGNATURE_MISMATCH]: ErrorCategories.AUTHENTICATION_ERROR,
1703
+ [ResponseCodes.INVALID_ACCESS_CODE]: ErrorCategories.AUTHENTICATION_ERROR,
1704
+ [ResponseCodes.INVALID_MERCHANT_ID]: ErrorCategories.AUTHENTICATION_ERROR,
1705
+ // Transaction errors
1706
+ [ResponseCodes.DECLINED]: ErrorCategories.TRANSACTION_ERROR,
1707
+ [ResponseCodes.INSUFFICIENT_FUNDS]: ErrorCategories.TRANSACTION_ERROR,
1708
+ [ResponseCodes.LIMIT_EXCEEDED]: ErrorCategories.TRANSACTION_ERROR,
1709
+ [ResponseCodes.INVALID_TRANSACTION]: ErrorCategories.TRANSACTION_ERROR,
1710
+ [ResponseCodes.DUPLICATE_TRANSACTION]: ErrorCategories.TRANSACTION_ERROR,
1711
+ [ResponseCodes.TRANSACTION_NOT_ALLOWED]: ErrorCategories.TRANSACTION_ERROR,
1712
+ [ResponseCodes.TRANSACTION_EXPIRED]: ErrorCategories.TRANSACTION_ERROR,
1713
+ [ResponseCodes.ALREADY_CAPTURED]: ErrorCategories.TRANSACTION_ERROR,
1714
+ [ResponseCodes.ALREADY_VOIDED]: ErrorCategories.TRANSACTION_ERROR,
1715
+ [ResponseCodes.ALREADY_REFUNDED]: ErrorCategories.TRANSACTION_ERROR,
1716
+ // Amount errors
1717
+ [ResponseCodes.INVALID_AMOUNT]: ErrorCategories.AMOUNT_ERROR,
1718
+ [ResponseCodes.AMOUNT_TOO_SMALL]: ErrorCategories.AMOUNT_ERROR,
1719
+ [ResponseCodes.AMOUNT_TOO_LARGE]: ErrorCategories.AMOUNT_ERROR,
1720
+ [ResponseCodes.CURRENCY_NOT_SUPPORTED]: ErrorCategories.AMOUNT_ERROR,
1721
+ // Validation errors
1722
+ [ResponseCodes.MISSING_PARAMETER]: ErrorCategories.VALIDATION_ERROR,
1723
+ [ResponseCodes.INVALID_PARAMETER]: ErrorCategories.VALIDATION_ERROR,
1724
+ [ResponseCodes.INVALID_COMMAND]: ErrorCategories.VALIDATION_ERROR,
1725
+ [ResponseCodes.INVALID_LANGUAGE]: ErrorCategories.VALIDATION_ERROR,
1726
+ [ResponseCodes.INVALID_CURRENCY]: ErrorCategories.VALIDATION_ERROR,
1727
+ [ResponseCodes.INVALID_RETURN_URL]: ErrorCategories.VALIDATION_ERROR,
1728
+ [ResponseCodes.INVALID_EMAIL]: ErrorCategories.VALIDATION_ERROR,
1729
+ [ResponseCodes.PARAMETER_VALUE_NOT_ALLOWED]: ErrorCategories.VALIDATION_ERROR,
1730
+ // Token errors
1731
+ [ResponseCodes.TOKEN_NOT_FOUND]: ErrorCategories.TOKEN_ERROR,
1732
+ [ResponseCodes.TOKEN_EXPIRED]: ErrorCategories.TOKEN_ERROR,
1733
+ [ResponseCodes.TOKEN_ALREADY_USED]: ErrorCategories.TOKEN_ERROR,
1734
+ [ResponseCodes.INVALID_TOKEN]: ErrorCategories.TOKEN_ERROR,
1735
+ // System errors
1736
+ [ResponseCodes.SYSTEM_ERROR]: ErrorCategories.SYSTEM_ERROR,
1737
+ [ResponseCodes.SERVICE_UNAVAILABLE]: ErrorCategories.SYSTEM_ERROR,
1738
+ [ResponseCodes.TIMEOUT]: ErrorCategories.SYSTEM_ERROR,
1739
+ [ResponseCodes.DATABASE_ERROR]: ErrorCategories.SYSTEM_ERROR,
1740
+ [ResponseCodes.INTERNAL_ERROR]: ErrorCategories.SYSTEM_ERROR
1741
+ };
1742
+ var RETRYABLE_CODES = [
1743
+ ResponseCodes.TIMEOUT,
1744
+ ResponseCodes.SERVICE_UNAVAILABLE,
1745
+ ResponseCodes.SYSTEM_ERROR,
1746
+ ResponseCodes.INTERNAL_ERROR,
1747
+ ResponseCodes.DATABASE_ERROR
1748
+ ];
1749
+ function categorizeError(code) {
1750
+ return ERROR_CODE_TO_CATEGORY[code] || ErrorCategories.SYSTEM_ERROR;
1751
+ }
1752
+ function isRetryableError(code) {
1753
+ return RETRYABLE_CODES.includes(code);
1754
+ }
1755
+ var PaymentMethodCodes = {
1756
+ /** Visa */
1757
+ VISA: "VISA",
1758
+ /** Mastercard */
1759
+ MASTERCARD: "MASTERCARD",
1760
+ /** American Express */
1761
+ AMEX: "AMEX",
1762
+ /** MADA (Saudi Arabia) */
1763
+ MADA: "MADA",
1764
+ /** Apple Pay */
1765
+ APPLE_PAY: "APPLE_PAY",
1766
+ /** STC Pay (Saudi Arabia) */
1767
+ STC_PAY: "STC_PAY",
1768
+ /** KNET (Kuwait) */
1769
+ KNET: "KNET",
1770
+ /** NAPS (Qatar) */
1771
+ NAPS: "NAPS",
1772
+ /** Fawry (Egypt) */
1773
+ FAWRY: "FAWRY",
1774
+ /** Meeza (Egypt) */
1775
+ MEEZA: "MEEZA",
1776
+ /** Sadad (Saudi Arabia) */
1777
+ SADAD: "SADAD",
1778
+ /** Aman (Egypt) */
1779
+ AMAN: "AMAN",
1780
+ /** Tabby (BNPL) */
1781
+ TABBY: "TABBY",
1782
+ /** Tamara (BNPL) */
1783
+ TAMARA: "TAMARA",
1784
+ /** valU (BNPL) */
1785
+ VALU: "VALU"
1786
+ };
1787
+ var CurrencyCodes = {
1788
+ /** Saudi Riyal */
1789
+ SAR: "SAR",
1790
+ /** UAE Dirham */
1791
+ AED: "AED",
1792
+ /** Kuwaiti Dinar */
1793
+ KWD: "KWD",
1794
+ /** Qatari Riyal */
1795
+ QAR: "QAR",
1796
+ /** Bahraini Dinar */
1797
+ BHD: "BHD",
1798
+ /** Omani Rial */
1799
+ OMR: "OMR",
1800
+ /** Jordanian Dinar */
1801
+ JOD: "JOD",
1802
+ /** Egyptian Pound */
1803
+ EGP: "EGP",
1804
+ /** US Dollar */
1805
+ USD: "USD",
1806
+ /** Euro */
1807
+ EUR: "EUR",
1808
+ /** British Pound */
1809
+ GBP: "GBP"
1810
+ };
1811
+ var LanguageCodes = {
1812
+ /** English */
1813
+ EN: "en",
1814
+ /** Arabic */
1815
+ AR: "ar"
1816
+ };
1817
+ var Commands = {
1818
+ /** Purchase (direct charge) */
1819
+ PURCHASE: "PURCHASE",
1820
+ /** Authorization (hold funds) */
1821
+ AUTHORIZATION: "AUTHORIZATION",
1822
+ /** Capture authorized funds */
1823
+ CAPTURE: "CAPTURE",
1824
+ /** Refund a transaction */
1825
+ REFUND: "REFUND",
1826
+ /** Void a transaction */
1827
+ VOID: "VOID",
1828
+ /** Query transaction status */
1829
+ QUERY: "QUERY_TRANSACTION",
1830
+ /** Tokenize a card */
1831
+ TOKENIZATION: "TOKENIZATION",
1832
+ /** Create token */
1833
+ CREATE_TOKEN: "CREATE_TOKEN",
1834
+ /** Verify token */
1835
+ VERIFY_TOKEN: "VERIFY_TOKEN",
1836
+ /** Delete token */
1837
+ DELETE_TOKEN: "DELETE_TOKEN",
1838
+ /** Get saved cards */
1839
+ GET_CARDS: "GET_CARDS",
1840
+ /** Payment link */
1841
+ PAYMENT_LINK: "PAYMENT_LINK"
1842
+ };
1843
+ var ECIValues = {
1844
+ /** Secure e-commerce with 3DS */
1845
+ SECURE_3DS: "05",
1846
+ /** Non-3DS e-commerce */
1847
+ NON_3DS: "07",
1848
+ /** Recurring payment */
1849
+ RECURRING: "RECURRING",
1850
+ /** Merchant-initiated */
1851
+ MERCHANT_INITIATED: "07"
1852
+ };
1853
+ var StatusCodes = {
1854
+ /** Success */
1855
+ SUCCESS: "20",
1856
+ /** Pending/3DS required */
1857
+ PENDING: "3",
1858
+ /** Authorized */
1859
+ AUTHORIZED: "02",
1860
+ /** Captured */
1861
+ CAPTURED: "04"
1862
+ };
1863
+
1864
+ // src/errors.ts
1865
+ var ERROR_DETAILS_MAP = {
1866
+ // Success codes
1867
+ [ResponseCodes.SUCCESS]: {
1868
+ message: "Transaction completed successfully.",
1869
+ action: "No action needed. Proceed with order fulfillment.",
1870
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html"
1871
+ },
1872
+ [ResponseCodes.PAYMENT_LINK_SUCCESS]: {
1873
+ message: "Payment link created successfully.",
1874
+ action: "Share the payment link with your customer via email, SMS, or any channel.",
1875
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html"
1876
+ },
1877
+ [ResponseCodes.RECURRING_SUCCESS]: {
1878
+ message: "Recurring payment processed successfully.",
1879
+ action: "Payment has been charged. Update subscription status in your system.",
1880
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html"
1881
+ },
1882
+ // Authentication & Security
1883
+ [ResponseCodes.AUTHENTICATION_FAILED]: {
1884
+ message: "3D Secure authentication failed. The customer could not verify their identity.",
1885
+ action: "Ask the customer to check their 3D Secure password or use a different card. Some banks require SMS verification - ensure customer has network coverage.",
1886
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#_3d_secure",
1887
+ httpStatus: 402
1888
+ },
1889
+ [ResponseCodes.NOT_ENROLLED_3DS]: {
1890
+ message: "Card is not enrolled in 3D Secure.",
1891
+ action: "The card does not support 3D Secure. You can proceed without 3DS or ask customer to use a different card.",
1892
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#_3d_secure"
1893
+ },
1894
+ [ResponseCodes.SIGNATURE_MISMATCH]: {
1895
+ message: "Request signature is invalid.",
1896
+ action: "Check that your request_secret is correct and that parameters are being signed in the correct order. Use the SDK's built-in signing methods.",
1897
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#signature_calculation",
1898
+ httpStatus: 401
1899
+ },
1900
+ [ResponseCodes.INVALID_ACCESS_CODE]: {
1901
+ message: "Invalid access code.",
1902
+ action: "Verify your APS_ACCESS_CODE environment variable matches the value in your APS dashboard under Integration Settings.",
1903
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#credentials",
1904
+ httpStatus: 401
1905
+ },
1906
+ [ResponseCodes.INVALID_MERCHANT_ID]: {
1907
+ message: "Invalid merchant identifier.",
1908
+ action: "Verify your APS_MERCHANT_ID environment variable matches your APS dashboard. Ensure you're using the correct environment (sandbox vs production).",
1909
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#credentials",
1910
+ httpStatus: 401
1911
+ },
1912
+ // Card Errors
1913
+ [ResponseCodes.CARD_EXPIRED]: {
1914
+ message: "The card has expired.",
1915
+ action: "Ask the customer to check the expiry date on their card and enter it correctly, or use a different card.",
1916
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1917
+ httpStatus: 402
1918
+ },
1919
+ [ResponseCodes.INVALID_CARD_NUMBER]: {
1920
+ message: "The card number is invalid.",
1921
+ action: "Ask the customer to check their card number and try again. Ensure no spaces or dashes are included.",
1922
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1923
+ httpStatus: 402
1924
+ },
1925
+ [ResponseCodes.INVALID_CVV]: {
1926
+ message: "The CVV code is invalid.",
1927
+ action: "Ask the customer to check the CVV on the back of their card (3 digits for Visa/MC, 4 for Amex) and enter it correctly.",
1928
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1929
+ httpStatus: 402
1930
+ },
1931
+ [ResponseCodes.CARD_NOT_SUPPORTED]: {
1932
+ message: "This card type is not supported.",
1933
+ action: "The customer is using a card type not accepted by your merchant account. Ask them to use Visa, Mastercard, or MADA.",
1934
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#payment_methods",
1935
+ httpStatus: 402
1936
+ },
1937
+ [ResponseCodes.LOST_CARD]: {
1938
+ message: "The card has been reported lost.",
1939
+ action: "Do not retry. Ask the customer to use a different card and contact their bank.",
1940
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1941
+ httpStatus: 402
1942
+ },
1943
+ [ResponseCodes.STOLEN_CARD]: {
1944
+ message: "The card has been reported stolen.",
1945
+ action: "Do not retry. Ask the customer to use a different card and contact their bank immediately.",
1946
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1947
+ httpStatus: 402
1948
+ },
1949
+ [ResponseCodes.RESTRICTED_CARD]: {
1950
+ message: "The card has restrictions that prevent this transaction.",
1951
+ action: "The card may be restricted for online or international use. Ask the customer to contact their bank or use a different card.",
1952
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1953
+ httpStatus: 402
1954
+ },
1955
+ [ResponseCodes.CARD_BLOCKED]: {
1956
+ message: "The card has been blocked by the issuing bank.",
1957
+ action: "Ask the customer to contact their bank to unblock the card or use a different card.",
1958
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1959
+ httpStatus: 402
1960
+ },
1961
+ [ResponseCodes.INVALID_EXPIRY]: {
1962
+ message: "The expiry date is invalid.",
1963
+ action: "Ask the customer to check the expiry date format (MM/YY) and ensure the card has not expired.",
1964
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#card_errors",
1965
+ httpStatus: 402
1966
+ },
1967
+ // Transaction Errors
1968
+ [ResponseCodes.DECLINED]: {
1969
+ message: "The transaction was declined by the issuing bank.",
1970
+ action: "Ask the customer to contact their bank or use a different card. The bank does not provide specific reasons for declines.",
1971
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#declined_transactions",
1972
+ httpStatus: 402
1973
+ },
1974
+ [ResponseCodes.INSUFFICIENT_FUNDS]: {
1975
+ message: "The card has insufficient funds.",
1976
+ action: "Ask the customer to use a different card or payment method, or reduce the transaction amount.",
1977
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#transaction_errors",
1978
+ httpStatus: 402
1979
+ },
1980
+ [ResponseCodes.LIMIT_EXCEEDED]: {
1981
+ message: "The transaction amount exceeds the card limit.",
1982
+ action: "The transaction may exceed the customer's daily limit or card limit. Ask them to contact their bank or use a different card.",
1983
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#transaction_errors",
1984
+ httpStatus: 402
1985
+ },
1986
+ [ResponseCodes.INVALID_TRANSACTION]: {
1987
+ message: "The transaction is invalid.",
1988
+ action: "Check that all required parameters are provided correctly. Ensure the amount is valid and currency is supported.",
1989
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#transaction_errors",
1990
+ httpStatus: 400
1991
+ },
1992
+ [ResponseCodes.DUPLICATE_TRANSACTION]: {
1993
+ message: "A duplicate transaction was detected.",
1994
+ action: "This transaction appears to be a duplicate. Use a unique merchant_reference for each transaction.",
1995
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#idempotency",
1996
+ httpStatus: 409
1997
+ },
1998
+ [ResponseCodes.TRANSACTION_NOT_ALLOWED]: {
1999
+ message: "This transaction type is not allowed for this merchant.",
2000
+ action: "Your merchant account may not be configured for this transaction type. Contact APS support to enable the required service.",
2001
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#merchant_setup",
2002
+ httpStatus: 403
2003
+ },
2004
+ [ResponseCodes.TRANSACTION_EXPIRED]: {
2005
+ message: "The transaction has expired.",
2006
+ action: "The authorization window has expired. Create a new transaction.",
2007
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#transaction_lifecycle",
2008
+ httpStatus: 410
2009
+ },
2010
+ [ResponseCodes.ALREADY_CAPTURED]: {
2011
+ message: "The transaction has already been captured.",
2012
+ action: "This transaction was already captured. Check your records or query the transaction status.",
2013
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#capture",
2014
+ httpStatus: 409
2015
+ },
2016
+ [ResponseCodes.ALREADY_VOIDED]: {
2017
+ message: "The transaction has already been voided.",
2018
+ action: "This transaction was already voided. No further action can be taken on it.",
2019
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#void",
2020
+ httpStatus: 409
2021
+ },
2022
+ [ResponseCodes.ALREADY_REFUNDED]: {
2023
+ message: "The transaction has already been refunded.",
2024
+ action: "This transaction was already refunded. Check the refund status for details.",
2025
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#refund",
2026
+ httpStatus: 409
2027
+ },
2028
+ // Amount Errors
2029
+ [ResponseCodes.INVALID_AMOUNT]: {
2030
+ message: "The transaction amount is invalid.",
2031
+ action: "Ensure the amount is a positive number in the smallest currency unit (e.g., cents, fils). Amount should not contain decimals.",
2032
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#amount_format",
2033
+ httpStatus: 400
2034
+ },
2035
+ [ResponseCodes.AMOUNT_TOO_SMALL]: {
2036
+ message: "The transaction amount is below the minimum allowed.",
2037
+ action: "The amount is below the minimum transaction limit. Increase the amount or contact APS for limit adjustments.",
2038
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#amount_limits",
2039
+ httpStatus: 400
2040
+ },
2041
+ [ResponseCodes.AMOUNT_TOO_LARGE]: {
2042
+ message: "The transaction amount exceeds the maximum allowed.",
2043
+ action: "The amount exceeds your merchant transaction limit. Contact APS support to increase your limit.",
2044
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#amount_limits",
2045
+ httpStatus: 400
2046
+ },
2047
+ [ResponseCodes.CURRENCY_NOT_SUPPORTED]: {
2048
+ message: "The currency is not supported.",
2049
+ action: "Use a supported currency (SAR, AED, USD, EUR, etc.). Check APS documentation for the full list.",
2050
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#currencies",
2051
+ httpStatus: 400
2052
+ },
2053
+ // Parameter Errors
2054
+ [ResponseCodes.MISSING_PARAMETER]: {
2055
+ message: "A required parameter is missing.",
2056
+ action: "Check that all required parameters are provided. Common missing fields: merchant_reference, amount, currency, customer_email.",
2057
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#required_parameters",
2058
+ httpStatus: 400
2059
+ },
2060
+ [ResponseCodes.INVALID_PARAMETER]: {
2061
+ message: "A parameter has an invalid format or value.",
2062
+ action: "Check parameter formats: emails must be valid, amounts must be numeric, dates must be in correct format.",
2063
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#parameter_formats",
2064
+ httpStatus: 400
2065
+ },
2066
+ [ResponseCodes.INVALID_COMMAND]: {
2067
+ message: "The command is invalid or not recognized.",
2068
+ action: "Use a valid command: PURCHASE, AUTHORIZATION, CAPTURE, REFUND, VOID, TOKENIZATION, etc.",
2069
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#commands",
2070
+ httpStatus: 400
2071
+ },
2072
+ [ResponseCodes.INVALID_LANGUAGE]: {
2073
+ message: "The language code is invalid.",
2074
+ action: 'Use "en" for English or "ar" for Arabic.',
2075
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#language_codes",
2076
+ httpStatus: 400
2077
+ },
2078
+ [ResponseCodes.INVALID_CURRENCY]: {
2079
+ message: "The currency code is invalid.",
2080
+ action: "Use a valid 3-letter ISO currency code (SAR, AED, USD, EUR, etc.).",
2081
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#currencies",
2082
+ httpStatus: 400
2083
+ },
2084
+ [ResponseCodes.INVALID_RETURN_URL]: {
2085
+ message: "The return URL is invalid.",
2086
+ action: "Ensure the return_url is a valid HTTPS URL and properly URL-encoded if needed.",
2087
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#return_url",
2088
+ httpStatus: 400
2089
+ },
2090
+ [ResponseCodes.INVALID_EMAIL]: {
2091
+ message: "The customer email is invalid.",
2092
+ action: "Ensure the customer_email is a valid email format (e.g., customer@example.com).",
2093
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#customer_email",
2094
+ httpStatus: 400
2095
+ },
2096
+ [ResponseCodes.PARAMETER_VALUE_NOT_ALLOWED]: {
2097
+ message: "A parameter value is not allowed for your merchant account.",
2098
+ action: "This error often occurs when trying to use tokenization (remember_me) but your merchant account does not have tokenization enabled. Contact APS support to enable tokenization, or set tokenize: false. Other causes: using a payment method not enabled for your account, or an invalid parameter value.",
2099
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#merchant_setup",
2100
+ httpStatus: 400
2101
+ },
2102
+ // Tokenization Errors
2103
+ [ResponseCodes.TOKEN_NOT_FOUND]: {
2104
+ message: "The card token was not found.",
2105
+ action: "The token may have been deleted or never created. Ask the customer to re-enter their card details.",
2106
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#tokenization",
2107
+ httpStatus: 404
2108
+ },
2109
+ [ResponseCodes.TOKEN_EXPIRED]: {
2110
+ message: "The card token has expired.",
2111
+ action: "Tokens expire after a period of inactivity. Ask the customer to re-enter their card details.",
2112
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#token_expiry",
2113
+ httpStatus: 410
2114
+ },
2115
+ [ResponseCodes.TOKEN_ALREADY_USED]: {
2116
+ message: "The token has already been used.",
2117
+ action: "Each token can only be used once for security. Create a new token for this transaction.",
2118
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#token_usage",
2119
+ httpStatus: 409
2120
+ },
2121
+ [ResponseCodes.INVALID_TOKEN]: {
2122
+ message: "The token is invalid.",
2123
+ action: "Check that the token was properly generated and is being passed correctly.",
2124
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#tokenization",
2125
+ httpStatus: 400
2126
+ },
2127
+ // System Errors
2128
+ [ResponseCodes.SYSTEM_ERROR]: {
2129
+ message: "A system error occurred.",
2130
+ action: "This is a temporary issue on APS side. Wait a moment and retry the transaction.",
2131
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#system_errors",
2132
+ httpStatus: 500
2133
+ },
2134
+ [ResponseCodes.SERVICE_UNAVAILABLE]: {
2135
+ message: "The service is temporarily unavailable.",
2136
+ action: "APS is experiencing high load or maintenance. Wait a moment and retry.",
2137
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#system_errors",
2138
+ httpStatus: 503
2139
+ },
2140
+ [ResponseCodes.TIMEOUT]: {
2141
+ message: "The request timed out.",
2142
+ action: "The request took too long to complete. Check your network connection and retry.",
2143
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#timeouts",
2144
+ httpStatus: 504
2145
+ },
2146
+ [ResponseCodes.DATABASE_ERROR]: {
2147
+ message: "A database error occurred.",
2148
+ action: "Temporary database issue. Wait a moment and retry the transaction.",
2149
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#system_errors",
2150
+ httpStatus: 500
2151
+ },
2152
+ [ResponseCodes.INTERNAL_ERROR]: {
2153
+ message: "An internal error occurred.",
2154
+ action: "Unexpected error on APS side. Contact APS support if this persists.",
2155
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#support",
2156
+ httpStatus: 500
2157
+ }
2158
+ };
2159
+ function getErrorDetails(code) {
2160
+ const details = ERROR_DETAILS_MAP[code];
2161
+ const category = categorizeError(code);
2162
+ const retryable = isRetryableError(code);
2163
+ if (details) {
2164
+ return {
2165
+ code,
2166
+ message: details.message,
2167
+ action: details.action,
2168
+ category,
2169
+ retryable,
2170
+ documentation: details.documentation,
2171
+ httpStatus: details.httpStatus
2172
+ };
2173
+ }
2174
+ return {
2175
+ code,
2176
+ message: `An unknown error occurred (code: ${code}).`,
2177
+ action: "Contact APS support with this error code for assistance.",
2178
+ category: ErrorCategories.SYSTEM_ERROR,
2179
+ retryable: false,
2180
+ documentation: "https://paymentservices.amazon.com/docs/EN/index.html#support",
2181
+ httpStatus: 500
2182
+ };
2183
+ }
2184
+ function isRetryableError2(code) {
2185
+ return isRetryableError(code);
2186
+ }
2187
+ function getUserFriendlyMessage(code, includeAction = true) {
2188
+ const details = getErrorDetails(code);
2189
+ if (includeAction) {
2190
+ return `${details.message} ${details.action}`;
2191
+ }
2192
+ return details.message;
2193
+ }
2194
+ function formatErrorForLogging(code, context) {
2195
+ const details = getErrorDetails(code);
2196
+ const contextStr = context ? ` (${Object.entries(context).map(([k, v]) => `${k}: ${v}`).join(", ")})` : "";
2197
+ return `[APS Error ${code}] ${details.category.toUpperCase()}: ${details.message}${contextStr}`;
2198
+ }
2199
+ function isSuccessCode(code) {
2200
+ return [
2201
+ ResponseCodes.SUCCESS,
2202
+ ResponseCodes.PAYMENT_LINK_SUCCESS,
2203
+ ResponseCodes.RECURRING_SUCCESS
2204
+ ].includes(code);
2205
+ }
2206
+ function getErrorCodesByCategory(category) {
2207
+ return Object.entries(ERROR_DETAILS_MAP).filter(([code]) => categorizeError(code) === category).map(([code]) => code);
2208
+ }
2209
+ function suggestHttpStatus(code) {
2210
+ const details = getErrorDetails(code);
2211
+ return details.httpStatus || 400;
2212
+ }
2213
+
2214
+ // src/validators.ts
2215
+ import crypto5 from "crypto";
2216
+ function isValidMerchantReference(reference) {
2217
+ if (!reference || reference.length === 0) {
2218
+ return {
2219
+ valid: false,
2220
+ error: "Merchant reference is required",
2221
+ code: ResponseCodes.MISSING_PARAMETER
2222
+ };
2223
+ }
2224
+ if (reference.length > 40) {
2225
+ return {
2226
+ valid: false,
2227
+ error: "Merchant reference must be 40 characters or less",
2228
+ code: ResponseCodes.INVALID_PARAMETER
2229
+ };
2230
+ }
2231
+ if (!/^[a-zA-Z0-9_-]+$/.test(reference)) {
2232
+ return {
2233
+ valid: false,
2234
+ error: "Merchant reference can only contain letters, numbers, underscores, and hyphens",
2235
+ code: ResponseCodes.INVALID_PARAMETER
2236
+ };
2237
+ }
2238
+ return { valid: true };
2239
+ }
2240
+ function isValidAmount(amount, _currency) {
2241
+ if (amount === void 0 || amount === null) {
2242
+ return {
2243
+ valid: false,
2244
+ error: "Amount is required",
2245
+ code: ResponseCodes.MISSING_PARAMETER
2246
+ };
2247
+ }
2248
+ if (typeof amount !== "number" || isNaN(amount)) {
2249
+ return {
2250
+ valid: false,
2251
+ error: "Amount must be a valid number",
2252
+ code: ResponseCodes.INVALID_AMOUNT
2253
+ };
2254
+ }
2255
+ if (amount <= 0) {
2256
+ return {
2257
+ valid: false,
2258
+ error: "Amount must be greater than zero",
2259
+ code: ResponseCodes.AMOUNT_TOO_SMALL
2260
+ };
2261
+ }
2262
+ if (!Number.isInteger(amount)) {
2263
+ return {
2264
+ valid: false,
2265
+ error: "Amount must be a whole number (in smallest currency unit, e.g., cents)",
2266
+ code: ResponseCodes.INVALID_AMOUNT
2267
+ };
2268
+ }
2269
+ if (amount > 999999999999) {
2270
+ return {
2271
+ valid: false,
2272
+ error: "Amount exceeds maximum allowed value",
2273
+ code: ResponseCodes.AMOUNT_TOO_LARGE
2274
+ };
2275
+ }
2276
+ return { valid: true };
2277
+ }
2278
+ function isValidCurrency(currency) {
2279
+ if (!currency || currency.length === 0) {
2280
+ return {
2281
+ valid: false,
2282
+ error: "Currency is required",
2283
+ code: ResponseCodes.MISSING_PARAMETER
2284
+ };
2285
+ }
2286
+ if (!/^[A-Z]{3}$/.test(currency)) {
2287
+ return {
2288
+ valid: false,
2289
+ error: "Currency must be a valid 3-letter ISO code (e.g., SAR, AED, USD)",
2290
+ code: ResponseCodes.INVALID_CURRENCY
2291
+ };
2292
+ }
2293
+ const supportedCurrencies = [
2294
+ "SAR",
2295
+ "AED",
2296
+ "KWD",
2297
+ "QAR",
2298
+ "BHD",
2299
+ "OMR",
2300
+ "JOD",
2301
+ "EGP",
2302
+ "USD",
2303
+ "EUR",
2304
+ "GBP",
2305
+ "CAD",
2306
+ "AUD",
2307
+ "CHF",
2308
+ "SEK",
2309
+ "NOK",
2310
+ "DKK",
2311
+ "NZD",
2312
+ "SGD",
2313
+ "HKD",
2314
+ "JPY",
2315
+ "CNY",
2316
+ "INR"
2317
+ ];
2318
+ if (!supportedCurrencies.includes(currency)) {
2319
+ return {
2320
+ valid: false,
2321
+ error: `Currency ${currency} may not be supported by APS. Supported: ${supportedCurrencies.join(", ")}`,
2322
+ code: ResponseCodes.CURRENCY_NOT_SUPPORTED
2323
+ };
2324
+ }
2325
+ return { valid: true };
2326
+ }
2327
+ function isValidEmail(email) {
2328
+ if (!email || email.length === 0) {
2329
+ return {
2330
+ valid: false,
2331
+ error: "Email is required",
2332
+ code: ResponseCodes.MISSING_PARAMETER
2333
+ };
2334
+ }
2335
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2336
+ if (!emailRegex.test(email)) {
2337
+ return {
2338
+ valid: false,
2339
+ error: "Please enter a valid email address",
2340
+ code: ResponseCodes.INVALID_EMAIL
2341
+ };
2342
+ }
2343
+ if (email.length > 254) {
2344
+ return {
2345
+ valid: false,
2346
+ error: "Email address is too long",
2347
+ code: ResponseCodes.INVALID_EMAIL
2348
+ };
2349
+ }
2350
+ return { valid: true };
2351
+ }
2352
+ function isValidCardNumber(cardNumber) {
2353
+ if (!cardNumber || cardNumber.length === 0) {
2354
+ return {
2355
+ valid: false,
2356
+ error: "Card number is required",
2357
+ code: ResponseCodes.MISSING_PARAMETER
2358
+ };
2359
+ }
2360
+ const cleaned = cardNumber.replace(/[\s-]/g, "");
2361
+ if (!/^\d+$/.test(cleaned)) {
2362
+ return {
2363
+ valid: false,
2364
+ error: "Card number can only contain digits",
2365
+ code: ResponseCodes.INVALID_CARD_NUMBER
2366
+ };
2367
+ }
2368
+ if (cleaned.length < 13 || cleaned.length > 19) {
2369
+ return {
2370
+ valid: false,
2371
+ error: "Card number must be between 13 and 19 digits",
2372
+ code: ResponseCodes.INVALID_CARD_NUMBER
2373
+ };
2374
+ }
2375
+ let sum = 0;
2376
+ let shouldDouble = false;
2377
+ for (let i = cleaned.length - 1; i >= 0; i--) {
2378
+ let digit = parseInt(cleaned.charAt(i), 10);
2379
+ if (shouldDouble) {
2380
+ digit *= 2;
2381
+ if (digit > 9) {
2382
+ digit -= 9;
2383
+ }
2384
+ }
2385
+ sum += digit;
2386
+ shouldDouble = !shouldDouble;
2387
+ }
2388
+ if (sum % 10 !== 0) {
2389
+ return {
2390
+ valid: false,
2391
+ error: "Card number is invalid (failed Luhn check)",
2392
+ code: ResponseCodes.INVALID_CARD_NUMBER
2393
+ };
2394
+ }
2395
+ return { valid: true };
2396
+ }
2397
+ function isValidExpiryDate(month, year) {
2398
+ if (!month || !year) {
2399
+ return {
2400
+ valid: false,
2401
+ error: "Expiry month and year are required",
2402
+ code: ResponseCodes.MISSING_PARAMETER
2403
+ };
2404
+ }
2405
+ const expiryMonth = parseInt(month, 10);
2406
+ let expiryYear = parseInt(year, 10);
2407
+ if (year.length === 2) {
2408
+ expiryYear = 2e3 + expiryYear;
2409
+ }
2410
+ if (isNaN(expiryMonth) || isNaN(expiryYear)) {
2411
+ return {
2412
+ valid: false,
2413
+ error: "Expiry date must be numeric",
2414
+ code: ResponseCodes.INVALID_EXPIRY
2415
+ };
2416
+ }
2417
+ if (expiryMonth < 1 || expiryMonth > 12) {
2418
+ return {
2419
+ valid: false,
2420
+ error: "Expiry month must be between 1 and 12",
2421
+ code: ResponseCodes.INVALID_EXPIRY
2422
+ };
2423
+ }
2424
+ const now = /* @__PURE__ */ new Date();
2425
+ const currentYear = now.getFullYear();
2426
+ const currentMonth = now.getMonth() + 1;
2427
+ if (expiryYear < currentYear) {
2428
+ return {
2429
+ valid: false,
2430
+ error: "Card has expired",
2431
+ code: ResponseCodes.CARD_EXPIRED
2432
+ };
2433
+ }
2434
+ if (expiryYear === currentYear && expiryMonth < currentMonth) {
2435
+ return {
2436
+ valid: false,
2437
+ error: "Card has expired",
2438
+ code: ResponseCodes.CARD_EXPIRED
2439
+ };
2440
+ }
2441
+ if (expiryYear > currentYear + 20) {
2442
+ return {
2443
+ valid: false,
2444
+ error: "Expiry date is too far in the future",
2445
+ code: ResponseCodes.INVALID_EXPIRY
2446
+ };
2447
+ }
2448
+ return { valid: true };
2449
+ }
2450
+ function isValidCVV(cvv, cardType) {
2451
+ if (!cvv || cvv.length === 0) {
2452
+ return {
2453
+ valid: false,
2454
+ error: "CVV is required",
2455
+ code: ResponseCodes.MISSING_PARAMETER
2456
+ };
2457
+ }
2458
+ if (!/^\d+$/.test(cvv)) {
2459
+ return {
2460
+ valid: false,
2461
+ error: "CVV must contain only digits",
2462
+ code: ResponseCodes.INVALID_CVV
2463
+ };
2464
+ }
2465
+ const expectedLength = cardType?.toLowerCase() === "amex" ? 4 : 3;
2466
+ if (cvv.length !== expectedLength) {
2467
+ return {
2468
+ valid: false,
2469
+ error: `CVV must be ${expectedLength} digits${cardType?.toLowerCase() === "amex" ? " for American Express" : ""}`,
2470
+ code: ResponseCodes.INVALID_CVV
2471
+ };
2472
+ }
2473
+ return { valid: true };
2474
+ }
2475
+ function isValidReturnUrl(url) {
2476
+ if (!url || url.length === 0) {
2477
+ return {
2478
+ valid: false,
2479
+ error: "Return URL is required",
2480
+ code: ResponseCodes.MISSING_PARAMETER
2481
+ };
2482
+ }
2483
+ try {
2484
+ const parsed = new URL(url);
2485
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
2486
+ return {
2487
+ valid: false,
2488
+ error: "Return URL must use HTTP or HTTPS protocol",
2489
+ code: ResponseCodes.INVALID_RETURN_URL
2490
+ };
2491
+ }
2492
+ if (url.length > 2048) {
2493
+ return {
2494
+ valid: false,
2495
+ error: "Return URL is too long (max 2048 characters)",
2496
+ code: ResponseCodes.INVALID_RETURN_URL
2497
+ };
2498
+ }
2499
+ return { valid: true };
2500
+ } catch {
2501
+ return {
2502
+ valid: false,
2503
+ error: "Return URL must be a valid URL",
2504
+ code: ResponseCodes.INVALID_RETURN_URL
2505
+ };
2506
+ }
2507
+ }
2508
+ function isValidSignature(params, signature, secret) {
2509
+ if (!signature || !secret) {
2510
+ return false;
2511
+ }
2512
+ try {
2513
+ const sortedKeys = Object.keys(params).sort();
2514
+ const concatenated = sortedKeys.filter((key) => key !== "signature").map((key) => `${key}=${params[key]}`).join("");
2515
+ const signatureString = `${secret}${concatenated}${secret}`;
2516
+ const expectedSignature = crypto5.createHash("sha256").update(signatureString).digest("hex").toUpperCase();
2517
+ return signature.toUpperCase() === expectedSignature;
2518
+ } catch {
2519
+ return false;
2520
+ }
2521
+ }
2522
+ function isValidWebhookPayload(payload, signature, secret) {
2523
+ if (!signature) {
2524
+ return {
2525
+ valid: false,
2526
+ error: "Missing signature header",
2527
+ code: ResponseCodes.SIGNATURE_MISMATCH
2528
+ };
2529
+ }
2530
+ if (!secret) {
2531
+ return {
2532
+ valid: false,
2533
+ error: "Secret is required for validation",
2534
+ code: ResponseCodes.SIGNATURE_MISMATCH
2535
+ };
2536
+ }
2537
+ const payloadStr = typeof payload === "string" ? payload : JSON.stringify(payload);
2538
+ const expectedSignature = crypto5.createHmac("sha256", secret).update(payloadStr).digest("base64");
2539
+ if (signature !== expectedSignature) {
2540
+ return {
2541
+ valid: false,
2542
+ error: "Invalid signature",
2543
+ code: ResponseCodes.SIGNATURE_MISMATCH
2544
+ };
2545
+ }
2546
+ return { valid: true };
2547
+ }
2548
+ function isValidLanguage(language) {
2549
+ if (!language || language.length === 0) {
2550
+ return {
2551
+ valid: false,
2552
+ error: "Language is required",
2553
+ code: ResponseCodes.MISSING_PARAMETER
2554
+ };
2555
+ }
2556
+ const supportedLanguages = ["en", "ar"];
2557
+ if (!supportedLanguages.includes(language.toLowerCase())) {
2558
+ return {
2559
+ valid: false,
2560
+ error: `Language must be one of: ${supportedLanguages.join(", ")}`,
2561
+ code: ResponseCodes.INVALID_LANGUAGE
2562
+ };
2563
+ }
2564
+ return { valid: true };
2565
+ }
2566
+ function isValidTokenName(tokenName) {
2567
+ if (!tokenName || tokenName.length === 0) {
2568
+ return {
2569
+ valid: false,
2570
+ error: "Token name is required",
2571
+ code: ResponseCodes.MISSING_PARAMETER
2572
+ };
2573
+ }
2574
+ if (tokenName.length < 10 || tokenName.length > 100) {
2575
+ return {
2576
+ valid: false,
2577
+ error: "Token name appears to be invalid (wrong length)",
2578
+ code: ResponseCodes.INVALID_TOKEN
2579
+ };
2580
+ }
2581
+ return { valid: true };
2582
+ }
2583
+ function isValidPhone(phone) {
2584
+ if (!phone || phone.length === 0) {
2585
+ return { valid: true };
2586
+ }
2587
+ const phoneRegex = /^\+[1-9]\d{7,14}$/;
2588
+ if (!phoneRegex.test(phone.replace(/[\s-]/g, ""))) {
2589
+ return {
2590
+ valid: false,
2591
+ error: "Phone number must be in international format (+1234567890)",
2592
+ code: ResponseCodes.INVALID_PARAMETER
2593
+ };
2594
+ }
2595
+ return { valid: true };
2596
+ }
2597
+ function isValidDescription(description) {
2598
+ if (!description || description.length === 0) {
2599
+ return { valid: true };
2600
+ }
2601
+ if (description.length > 255) {
2602
+ return {
2603
+ valid: false,
2604
+ error: "Description must be 255 characters or less",
2605
+ code: ResponseCodes.INVALID_PARAMETER
2606
+ };
2607
+ }
2608
+ return { valid: true };
2609
+ }
2610
+ function isValidCustomerName(name) {
2611
+ if (!name || name.length === 0) {
2612
+ return { valid: true };
2613
+ }
2614
+ if (name.length > 100) {
2615
+ return {
2616
+ valid: false,
2617
+ error: "Customer name must be 100 characters or less",
2618
+ code: ResponseCodes.INVALID_PARAMETER
2619
+ };
2620
+ }
2621
+ return { valid: true };
2622
+ }
2623
+ function validatePaymentParams(params) {
2624
+ const errors = [];
2625
+ if (params.merchant_reference !== void 0) {
2626
+ const result = isValidMerchantReference(params.merchant_reference);
2627
+ if (!result.valid) {
2628
+ errors.push({ field: "merchant_reference", error: result.error, code: result.code });
2629
+ }
2630
+ }
2631
+ if (params.amount !== void 0) {
2632
+ const result = isValidAmount(params.amount, params.currency);
2633
+ if (!result.valid) {
2634
+ errors.push({ field: "amount", error: result.error, code: result.code });
2635
+ }
2636
+ }
2637
+ if (params.currency !== void 0) {
2638
+ const result = isValidCurrency(params.currency);
2639
+ if (!result.valid) {
2640
+ errors.push({ field: "currency", error: result.error, code: result.code });
2641
+ }
2642
+ }
2643
+ if (params.customer_email !== void 0) {
2644
+ const result = isValidEmail(params.customer_email);
2645
+ if (!result.valid) {
2646
+ errors.push({ field: "customer_email", error: result.error, code: result.code });
2647
+ }
2648
+ }
2649
+ if (params.return_url !== void 0) {
2650
+ const result = isValidReturnUrl(params.return_url);
2651
+ if (!result.valid) {
2652
+ errors.push({ field: "return_url", error: result.error, code: result.code });
2653
+ }
2654
+ }
2655
+ if (params.description !== void 0) {
2656
+ const result = isValidDescription(params.description);
2657
+ if (!result.valid) {
2658
+ errors.push({ field: "description", error: result.error, code: result.code });
2659
+ }
2660
+ }
2661
+ if (params.language !== void 0) {
2662
+ const result = isValidLanguage(params.language);
2663
+ if (!result.valid) {
2664
+ errors.push({ field: "language", error: result.error, code: result.code });
2665
+ }
2666
+ }
2667
+ return {
2668
+ valid: errors.length === 0,
2669
+ errors
2670
+ };
2671
+ }
2672
+ var validators = {
2673
+ isValidMerchantReference,
2674
+ isValidAmount,
2675
+ isValidCurrency,
2676
+ isValidEmail,
2677
+ isValidCardNumber,
2678
+ isValidExpiryDate,
2679
+ isValidCVV,
2680
+ isValidReturnUrl,
2681
+ isValidSignature,
2682
+ isValidWebhookPayload,
2683
+ isValidLanguage,
2684
+ isValidTokenName,
2685
+ isValidPhone,
2686
+ isValidDescription,
2687
+ isValidCustomerName,
2688
+ validatePaymentParams
2689
+ };
2690
+
2691
+ // src/index.ts
2692
+ var index_default = APSClient;
2693
+ var APS = APSClient;
2694
+ export {
2695
+ APS,
2696
+ APSClient,
2697
+ APSException,
2698
+ Commands,
2699
+ CurrencyCodes,
2700
+ CustomPaymentPageModule,
2701
+ ECIValues,
2702
+ ErrorCategories,
2703
+ HostedCheckoutModule,
2704
+ LanguageCodes,
2705
+ PaymentLinksModule,
2706
+ PaymentMethodCodes,
2707
+ PaymentsModule,
2708
+ RecurringModule,
2709
+ ResponseCodes,
2710
+ StatusCodes,
2711
+ TestCards,
2712
+ TokenizationModule,
2713
+ WebhooksModule,
2714
+ categorizeError,
2715
+ isRetryableError2 as checkRetryableError,
2716
+ index_default as default,
2717
+ formatErrorForLogging,
2718
+ getErrorCodesByCategory,
2719
+ getErrorDetails,
2720
+ getUserFriendlyMessage,
2721
+ isRetryableError,
2722
+ isSuccessCode,
2723
+ isValidAmount,
2724
+ isValidCVV,
2725
+ isValidCardNumber,
2726
+ isValidCurrency,
2727
+ isValidCustomerName,
2728
+ isValidDescription,
2729
+ isValidEmail,
2730
+ isValidExpiryDate,
2731
+ isValidLanguage,
2732
+ isValidMerchantReference,
2733
+ isValidPhone,
2734
+ isValidReturnUrl,
2735
+ isValidSignature,
2736
+ isValidTokenName,
2737
+ isValidWebhookPayload,
2738
+ suggestHttpStatus,
2739
+ validatePaymentParams,
2740
+ validators
2741
+ };