@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.
@@ -0,0 +1,2007 @@
1
+ /**
2
+ * Amazon Payment Services Configuration
3
+ */
4
+ interface APSConfig {
5
+ /** Merchant identifier provided by APS */
6
+ merchantId: string;
7
+ /** Access code for API authentication */
8
+ accessCode: string;
9
+ /** Request secret key for HMAC generation */
10
+ requestSecret: string;
11
+ /** Response secret key for HMAC verification */
12
+ responseSecret: string;
13
+ /** Environment: 'sandbox' or 'production' */
14
+ environment?: 'sandbox' | 'production';
15
+ /** Currency code (e.g., 'USD', 'AED', 'SAR') */
16
+ currency?: string;
17
+ /** Language for hosted pages */
18
+ language?: 'en' | 'ar';
19
+ }
20
+ /**
21
+ * Logger interface for custom logging implementations
22
+ */
23
+ interface Logger {
24
+ /** Log debug messages (for development) */
25
+ debug?: (message: string, ...args: any[]) => void;
26
+ /** Log informational messages */
27
+ info?: (message: string, ...args: any[]) => void;
28
+ /** Log warning messages */
29
+ warn?: (message: string, ...args: any[]) => void;
30
+ /** Log error messages */
31
+ error?: (message: string, ...args: any[]) => void;
32
+ }
33
+ /**
34
+ * APS Client options
35
+ */
36
+ interface APSClientOptions {
37
+ /** Custom logger instance */
38
+ logger?: Logger;
39
+ /** Request timeout in milliseconds (default: 30000) */
40
+ timeout?: number;
41
+ /** Maximum retry attempts (default: 3) */
42
+ maxRetries?: number;
43
+ /** Enable request logging (default: false in production) */
44
+ enableLogging?: boolean;
45
+ }
46
+ /**
47
+ * Rate limit configuration
48
+ */
49
+ interface RateLimitConfig {
50
+ /** Maximum requests per window */
51
+ maxRequests: number;
52
+ /** Window duration in milliseconds */
53
+ windowMs: number;
54
+ }
55
+ /**
56
+ * Idempotency key options
57
+ */
58
+ interface IdempotencyOptions {
59
+ /** Idempotency key for the request */
60
+ idempotencyKey: string;
61
+ }
62
+ /**
63
+ * Payment method types supported by APS
64
+ */
65
+ type PaymentMethod = 'card' | 'apple_pay' | 'mada' | 'stc_pay' | 'knet' | 'naps' | 'fawry' | 'meeza' | 'sadad' | 'aman';
66
+ /**
67
+ * Transaction status
68
+ */
69
+ type TransactionStatus = 'pending' | 'authorized' | 'captured' | 'failed' | 'voided' | 'refunded' | 'cancelled';
70
+ /**
71
+ * Customer information
72
+ */
73
+ interface Customer {
74
+ /** Customer email */
75
+ email?: string;
76
+ /** Customer name */
77
+ name?: string;
78
+ /** Customer phone */
79
+ phone?: string;
80
+ /** Billing address */
81
+ billingAddress?: {
82
+ street?: string;
83
+ city?: string;
84
+ state?: string;
85
+ country?: string;
86
+ postalCode?: string;
87
+ };
88
+ }
89
+ /**
90
+ * Order/Transaction details
91
+ */
92
+ interface Order {
93
+ /** Unique order ID (merchant generated) */
94
+ id: string;
95
+ /** Amount in minor units (e.g., cents) */
96
+ amount: number;
97
+ /** Currency code */
98
+ currency: string;
99
+ /** Order description */
100
+ description?: string;
101
+ /** Customer information */
102
+ customer?: Customer;
103
+ /** Metadata for the order */
104
+ metadata?: Record<string, string>;
105
+ }
106
+ /**
107
+ * Payment link options
108
+ */
109
+ interface PaymentLinkOptions {
110
+ /** Order details */
111
+ order: Order;
112
+ /** Payment methods to allow */
113
+ allowedPaymentMethods?: PaymentMethod[];
114
+ /** URL to redirect after successful payment */
115
+ successUrl?: string;
116
+ /** URL to redirect after failed payment */
117
+ failureUrl?: string;
118
+ /** URL to redirect after user cancels */
119
+ cancelUrl?: string;
120
+ /** Enable recurring payments */
121
+ recurring?: boolean;
122
+ /** Token validity in hours */
123
+ tokenValidityHours?: number;
124
+ /** Additional parameters */
125
+ metadata?: Record<string, string>;
126
+ }
127
+ /**
128
+ * Hosted checkout options
129
+ */
130
+ interface HostedCheckoutOptions {
131
+ /** Order details */
132
+ order: Order;
133
+ /** Payment methods to allow */
134
+ allowedPaymentMethods?: PaymentMethod[];
135
+ /** URL to redirect after successful payment */
136
+ successUrl?: string;
137
+ /** URL to redirect after failed payment */
138
+ failureUrl?: string;
139
+ /** URL to redirect after user cancels */
140
+ cancelUrl?: string;
141
+ /** Hide shipping information */
142
+ hideShipping?: boolean;
143
+ /** Additional parameters */
144
+ metadata?: Record<string, string>;
145
+ }
146
+ /**
147
+ * Custom payment page options
148
+ */
149
+ interface CustomPaymentPageOptions {
150
+ /** Order details */
151
+ order: Order;
152
+ /** Payment method to use */
153
+ paymentMethod: PaymentMethod;
154
+ /** Card token (if using tokenization) */
155
+ cardToken?: string;
156
+ /** 3DS return URL */
157
+ returnUrl?: string;
158
+ /** Enable 3DS authentication */
159
+ enable3DS?: boolean;
160
+ /** Additional parameters */
161
+ metadata?: Record<string, string>;
162
+ }
163
+ /**
164
+ * Card tokenization options
165
+ */
166
+ interface TokenizeCardOptions {
167
+ /** Card number */
168
+ cardNumber: string;
169
+ /** Expiry month (MM) */
170
+ expiryMonth: string;
171
+ /** Expiry year (YY) */
172
+ expiryYear: string;
173
+ /** CVV */
174
+ cvv: string;
175
+ /** Cardholder name */
176
+ cardholderName?: string;
177
+ }
178
+ /**
179
+ * Tokenized card response
180
+ */
181
+ interface TokenizedCard {
182
+ /** Card token for future use */
183
+ token: string;
184
+ /** Last 4 digits of card */
185
+ last4: string;
186
+ /** Card brand */
187
+ brand: string;
188
+ /** Expiry month */
189
+ expiryMonth: string;
190
+ /** Expiry year */
191
+ expiryYear: string;
192
+ }
193
+ /**
194
+ * Saved card for a customer (list response)
195
+ */
196
+ interface SavedCard {
197
+ /** Card token */
198
+ token: string;
199
+ /** Last 4 digits */
200
+ last4: string;
201
+ /** Card brand */
202
+ brand: string;
203
+ /** Expiry month */
204
+ expiryMonth: string;
205
+ /** Expiry year */
206
+ expiryYear: string;
207
+ /** Cardholder name */
208
+ cardholderName?: string;
209
+ /** Is this the default card */
210
+ isDefault?: boolean;
211
+ }
212
+ /**
213
+ * List saved cards response
214
+ */
215
+ interface SavedCardsList {
216
+ /** Customer identifier */
217
+ customerId: string;
218
+ /** List of saved cards */
219
+ cards: SavedCard[];
220
+ /** Total count */
221
+ total: number;
222
+ }
223
+ /**
224
+ * Payment response
225
+ */
226
+ interface PaymentResponse {
227
+ /** Transaction ID */
228
+ transactionId: string;
229
+ /** Order ID */
230
+ orderId: string;
231
+ /** Transaction status */
232
+ status: TransactionStatus;
233
+ /** Amount */
234
+ amount: number;
235
+ /** Currency */
236
+ currency: string;
237
+ /** Payment method used */
238
+ paymentMethod?: string;
239
+ /** 3DS URL (if authentication required) */
240
+ authenticationUrl?: string;
241
+ /** Form data for redirect (if applicable) */
242
+ redirectForm?: {
243
+ url: string;
244
+ method: 'POST' | 'GET';
245
+ params: Record<string, string>;
246
+ };
247
+ /** Error message if failed */
248
+ message?: string;
249
+ /** Raw APS response */
250
+ rawResponse: Record<string, any>;
251
+ }
252
+ /**
253
+ * Payment link response
254
+ */
255
+ interface PaymentLinkResponse {
256
+ /** Payment link URL */
257
+ url: string;
258
+ /** Link ID */
259
+ linkId: string;
260
+ /** Order ID */
261
+ orderId: string;
262
+ /** Expiry date */
263
+ expiresAt?: Date;
264
+ /** Raw APS response */
265
+ rawResponse: Record<string, any>;
266
+ }
267
+ /**
268
+ * Refund options
269
+ */
270
+ interface RefundOptions {
271
+ /** Original transaction ID */
272
+ transactionId: string;
273
+ /** Refund amount (optional for full refund) */
274
+ amount?: number;
275
+ /** Refund reason */
276
+ reason?: string;
277
+ }
278
+ /**
279
+ * Refund response
280
+ */
281
+ interface RefundResponse {
282
+ /** Refund transaction ID */
283
+ refundId: string;
284
+ /** Original transaction ID */
285
+ transactionId: string;
286
+ /** Refund amount */
287
+ amount: number;
288
+ /** Status */
289
+ status: TransactionStatus;
290
+ /** Message */
291
+ message?: string;
292
+ /** Raw APS response */
293
+ rawResponse: Record<string, any>;
294
+ }
295
+ /**
296
+ * Void options
297
+ */
298
+ interface VoidOptions {
299
+ /** Transaction ID to void */
300
+ transactionId: string;
301
+ /** Void reason */
302
+ reason?: string;
303
+ }
304
+ /**
305
+ * Void response
306
+ */
307
+ interface VoidResponse {
308
+ /** Void transaction ID */
309
+ voidId: string;
310
+ /** Original transaction ID */
311
+ transactionId: string;
312
+ /** Status */
313
+ status: TransactionStatus;
314
+ /** Message */
315
+ message?: string;
316
+ /** Raw APS response */
317
+ rawResponse: Record<string, any>;
318
+ }
319
+ /**
320
+ * Capture options
321
+ */
322
+ interface CaptureOptions {
323
+ /** Transaction ID to capture */
324
+ transactionId: string;
325
+ /** Capture amount (optional for full capture) */
326
+ amount?: number;
327
+ }
328
+ /**
329
+ * Capture response
330
+ */
331
+ interface CaptureResponse {
332
+ /** Capture transaction ID */
333
+ captureId: string;
334
+ /** Original transaction ID */
335
+ transactionId: string;
336
+ /** Capture amount */
337
+ amount: number;
338
+ /** Status */
339
+ status: TransactionStatus;
340
+ /** Message */
341
+ message?: string;
342
+ /** Raw APS response */
343
+ rawResponse: Record<string, any>;
344
+ }
345
+ /**
346
+ * Query transaction options
347
+ */
348
+ interface QueryOptions {
349
+ /** Transaction ID to query */
350
+ transactionId: string;
351
+ /** Or order ID */
352
+ orderId?: string;
353
+ }
354
+ /**
355
+ * Webhook event types
356
+ */
357
+ type WebhookEventType = 'payment.success' | 'payment.failed' | 'payment.pending' | 'refund.success' | 'refund.failed' | 'chargeback.created' | 'subscription.renewed' | 'subscription.cancelled';
358
+ /**
359
+ * Webhook event
360
+ */
361
+ interface WebhookEvent {
362
+ /** Event ID */
363
+ id: string;
364
+ /** Event type */
365
+ type: WebhookEventType;
366
+ /** Event timestamp */
367
+ timestamp: Date;
368
+ /** Transaction data */
369
+ data: {
370
+ transactionId: string;
371
+ orderId: string;
372
+ amount: number;
373
+ currency: string;
374
+ status: TransactionStatus;
375
+ paymentMethod?: string;
376
+ metadata?: Record<string, any>;
377
+ };
378
+ /** Raw webhook payload */
379
+ rawPayload: Record<string, any>;
380
+ }
381
+ /**
382
+ * APS Error
383
+ */
384
+ interface APSError {
385
+ /** Error code */
386
+ code: string;
387
+ /** Error message */
388
+ message: string;
389
+ /** HTTP status code */
390
+ statusCode?: number;
391
+ /** Raw error response */
392
+ rawResponse?: Record<string, any>;
393
+ }
394
+ /**
395
+ * APS Exception class
396
+ */
397
+ declare class APSException extends Error {
398
+ code: string;
399
+ statusCode?: number;
400
+ rawResponse?: Record<string, any>;
401
+ constructor(error: APSError);
402
+ }
403
+ /**
404
+ * Recurring payment options
405
+ */
406
+ interface RecurringPaymentOptions {
407
+ /** Order details */
408
+ order: {
409
+ /** Unique order ID */
410
+ id: string;
411
+ /** Amount in minor units (e.g., cents) */
412
+ amount: number;
413
+ /** Currency code */
414
+ currency: string;
415
+ /** Order description */
416
+ description?: string;
417
+ };
418
+ /** Card token from previous tokenization */
419
+ tokenName: string;
420
+ /** Agreement ID from original transaction */
421
+ agreementId: string;
422
+ /** Customer email */
423
+ customerEmail: string;
424
+ /** Customer name */
425
+ customerName?: string;
426
+ /** Customer phone */
427
+ customerPhone?: string;
428
+ /** Statement descriptor for bank statement */
429
+ statementDescriptor?: string;
430
+ /** Restrict payment method (e.g., 'VISA', 'MASTERCARD', 'MADA') */
431
+ paymentOption?: string;
432
+ /** Settlement reference */
433
+ settlementReference?: string;
434
+ }
435
+ /**
436
+ * Recurring payment response
437
+ */
438
+ interface RecurringPaymentResponse {
439
+ /** Transaction ID */
440
+ transactionId: string;
441
+ /** Order ID */
442
+ orderId: string;
443
+ /** Agreement ID used */
444
+ agreementId: string;
445
+ /** Amount charged */
446
+ amount: number;
447
+ /** Currency */
448
+ currency: string;
449
+ /** Transaction status */
450
+ status: 'captured' | 'failed' | 'pending';
451
+ /** Payment method used */
452
+ paymentMethod?: string;
453
+ /** Authorization code */
454
+ authorizationCode?: string;
455
+ /** Response message */
456
+ message?: string;
457
+ /** Raw APS response */
458
+ rawResponse: Record<string, any>;
459
+ }
460
+
461
+ /**
462
+ * Payment Links Module
463
+ *
464
+ * Create payment links using the official APS Payment Links API.
465
+ * This is a server-to-server API that returns a payment link URL.
466
+ *
467
+ * @example
468
+ * ```typescript
469
+ * const link = await aps.paymentLinks.create({
470
+ * order: {
471
+ * id: 'order_123',
472
+ * amount: 10000,
473
+ * currency: 'USD',
474
+ * description: 'Product purchase'
475
+ * },
476
+ * customer: {
477
+ * email: 'customer@example.com',
478
+ * name: 'John Doe'
479
+ * }
480
+ * });
481
+ *
482
+ * console.log(link.url); // Payment link to share with customer
483
+ * ```
484
+ */
485
+ declare class PaymentLinksModule {
486
+ private config;
487
+ private options;
488
+ constructor(config: Required<APSConfig>, options: Required<Omit<APSClientOptions, 'logger'>> & {
489
+ logger: Logger;
490
+ });
491
+ /**
492
+ * Create a new payment link using APS Payment Links API
493
+ */
494
+ create(options: PaymentLinkOptions): Promise<PaymentLinkResponse>;
495
+ /**
496
+ * Generate signature for APS API requests
497
+ * Following official APS documentation:
498
+ * 1. Sort all parameters alphabetically
499
+ * 2. Concatenate as param_name=param_value
500
+ * 3. Wrap with SHA phrase at beginning and end
501
+ * 4. Hash with SHA-256
502
+ */
503
+ private generateSignature;
504
+ /**
505
+ * Make API request to APS with timeout and retry support
506
+ */
507
+ private makeApiRequest;
508
+ /**
509
+ * Generate a payment link URL (alias for create)
510
+ */
511
+ generateUrl(options: PaymentLinkOptions): Promise<string>;
512
+ }
513
+
514
+ /**
515
+ * Hosted Checkout Module
516
+ *
517
+ * Redirect customers to a hosted checkout page managed by APS.
518
+ * Handles the entire payment flow including 3DS authentication.
519
+ *
520
+ * @example
521
+ * ```typescript
522
+ * const checkout = await aps.hostedCheckout.create({
523
+ * order: {
524
+ * id: 'order_123',
525
+ * amount: 10000,
526
+ * currency: 'USD'
527
+ * },
528
+ * successUrl: 'https://yoursite.com/success',
529
+ * failureUrl: 'https://yoursite.com/failure',
530
+ * tokenize: true // Enable card tokenization for future payments
531
+ * });
532
+ *
533
+ * // Redirect user to checkout.url or use checkout.redirectForm
534
+ * ```
535
+ */
536
+ declare class HostedCheckoutModule {
537
+ private config;
538
+ constructor(config: Required<APSConfig>, _options: Required<Omit<APSClientOptions, 'logger'>> & {
539
+ logger: Logger;
540
+ });
541
+ /**
542
+ * Create a hosted checkout session
543
+ */
544
+ create(checkoutOptions: HostedCheckoutOptions): Promise<PaymentResponse>;
545
+ /**
546
+ * Get the redirect URL for hosted checkout
547
+ */
548
+ getRedirectUrl(options: HostedCheckoutOptions): Promise<string>;
549
+ }
550
+
551
+ /**
552
+ * Custom Payment Page Module (Non-PCI)
553
+ *
554
+ * Process payments with a custom UI while APS handles PCI compliance.
555
+ * Uses tokenization to securely collect card details without storing them.
556
+ *
557
+ * Flow:
558
+ * 1. Create tokenization form to collect card details
559
+ * 2. Submit form to APS to get token
560
+ * 3. Use token to process payment via server-to-server API
561
+ *
562
+ * @example
563
+ * ```typescript
564
+ * // Step 1: Get tokenization form
565
+ * const tokenizationForm = aps.customPaymentPage.getTokenizationForm({
566
+ * returnUrl: 'https://yoursite.com/token-result'
567
+ * });
568
+ *
569
+ * // Step 2: Submit form (from frontend) to get token
570
+ * // Token is returned in response as token_name
571
+ *
572
+ * // Step 3: Process payment with token
573
+ * const payment = await aps.customPaymentPage.chargeWithToken({
574
+ * order: {
575
+ * id: 'order_123',
576
+ * amount: 10000,
577
+ * currency: 'SAR'
578
+ * },
579
+ * tokenName: 'token_from_step_2',
580
+ * customerEmail: 'customer@example.com'
581
+ * });
582
+ * ```
583
+ */
584
+ declare class CustomPaymentPageModule {
585
+ private config;
586
+ private options;
587
+ constructor(config: Required<APSConfig>, options: Required<Omit<APSClientOptions, 'logger'>> & {
588
+ logger: Logger;
589
+ });
590
+ /**
591
+ * Get tokenization form data
592
+ * This form should be submitted from the frontend to APS
593
+ */
594
+ getTokenizationForm(options: {
595
+ returnUrl: string;
596
+ merchantReference?: string;
597
+ cardNumber?: string;
598
+ expiryDate?: string;
599
+ cardSecurityCode?: string;
600
+ cardHolderName?: string;
601
+ }): {
602
+ url: string;
603
+ method: 'POST';
604
+ params: Record<string, string>;
605
+ };
606
+ /**
607
+ * Get create token form data (for saving cards without charging)
608
+ */
609
+ getCreateTokenForm(options: {
610
+ returnUrl: string;
611
+ merchantReference?: string;
612
+ cardNumber?: string;
613
+ expiryDate?: string;
614
+ cardHolderName?: string;
615
+ }): {
616
+ url: string;
617
+ method: 'POST';
618
+ params: Record<string, string>;
619
+ };
620
+ /**
621
+ * Charge using a token received from tokenization
622
+ * This is a server-to-server call
623
+ */
624
+ chargeWithToken(options: {
625
+ order: {
626
+ id: string;
627
+ amount: number;
628
+ currency: string;
629
+ description?: string;
630
+ };
631
+ tokenName: string;
632
+ customerEmail: string;
633
+ customerName?: string;
634
+ customerPhone?: string;
635
+ returnUrl?: string;
636
+ }): Promise<PaymentResponse>;
637
+ /**
638
+ * Alias for chargeWithToken for backwards compatibility
639
+ */
640
+ charge(options: CustomPaymentPageOptions): Promise<PaymentResponse>;
641
+ /**
642
+ * Make API request to APS with timeout and retry support
643
+ */
644
+ private makeApiRequest;
645
+ }
646
+
647
+ /**
648
+ * Tokenization Module
649
+ *
650
+ * Securely tokenize card details for future payments without storing sensitive data.
651
+ * Tokenized cards can be used for recurring payments or one-click checkout.
652
+ *
653
+ * @example
654
+ * ```typescript
655
+ * // Tokenize a card
656
+ * const token = await aps.tokens.create({
657
+ * cardNumber: '4111111111111111',
658
+ * expiryMonth: '12',
659
+ * expiryYear: '25',
660
+ * cvv: '123',
661
+ * cardholderName: 'John Doe'
662
+ * });
663
+ *
664
+ * console.log(token.token); // Use this for future payments
665
+ * console.log(token.last4); // "1111"
666
+ * ```
667
+ */
668
+ declare class TokenizationModule {
669
+ private config;
670
+ private options;
671
+ constructor(config: Required<APSConfig>, options: Required<Omit<APSClientOptions, 'logger'>> & {
672
+ logger: Logger;
673
+ });
674
+ /**
675
+ * Tokenize card details
676
+ */
677
+ create(options: TokenizeCardOptions): Promise<TokenizedCard>;
678
+ /**
679
+ * Verify a token (check if it's still valid)
680
+ */
681
+ verify(token: string): Promise<boolean>;
682
+ /**
683
+ * Delete/Invalidate a token
684
+ */
685
+ delete(token: string): Promise<boolean>;
686
+ /**
687
+ * List saved cards for a customer
688
+ * @param customerId - Customer identifier (email or user ID)
689
+ */
690
+ list(customerId: string): Promise<SavedCardsList>;
691
+ /**
692
+ * Detect card brand from card number
693
+ */
694
+ private detectCardBrand;
695
+ /**
696
+ * Make tokenization API request with timeout and retry support
697
+ */
698
+ private makeTokenizeRequest;
699
+ }
700
+
701
+ /**
702
+ * Payments Module
703
+ *
704
+ * Manage existing transactions: capture authorized payments, process refunds, void transactions.
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * // Capture an authorized payment
709
+ * const capture = await aps.payments.capture({
710
+ * transactionId: 'txn_123',
711
+ * amount: 10000 // Optional, defaults to full amount
712
+ * });
713
+ *
714
+ * // Refund a payment
715
+ * const refund = await aps.payments.refund({
716
+ * transactionId: 'txn_123',
717
+ * amount: 5000, // Optional, defaults to full refund
718
+ * reason: 'Customer request'
719
+ * });
720
+ *
721
+ * // Void an authorization
722
+ * const voided = await aps.payments.void({
723
+ * transactionId: 'txn_123',
724
+ * reason: 'Order cancelled'
725
+ * });
726
+ *
727
+ * // Query transaction status
728
+ * const transaction = await aps.payments.query({ transactionId: 'txn_123' });
729
+ * ```
730
+ */
731
+ declare class PaymentsModule {
732
+ private config;
733
+ private options;
734
+ constructor(config: Required<APSConfig>, options: Required<Omit<APSClientOptions, 'logger'>> & {
735
+ logger: Logger;
736
+ });
737
+ /**
738
+ * Capture an authorized payment
739
+ */
740
+ capture(options: CaptureOptions): Promise<CaptureResponse>;
741
+ /**
742
+ * Refund a payment (full or partial)
743
+ */
744
+ refund(options: RefundOptions): Promise<RefundResponse>;
745
+ /**
746
+ * Void an authorized transaction
747
+ */
748
+ void(options: VoidOptions): Promise<VoidResponse>;
749
+ /**
750
+ * Query transaction status
751
+ */
752
+ query(options: QueryOptions): Promise<Record<string, any>>;
753
+ /**
754
+ * Map APS response code to transaction status
755
+ */
756
+ private mapResponseStatus;
757
+ /**
758
+ * Make API request to APS with timeout and retry support
759
+ */
760
+ private makeApiRequest;
761
+ }
762
+
763
+ /**
764
+ * Webhooks Module
765
+ *
766
+ * Verify and parse webhook events from Amazon Payment Services.
767
+ *
768
+ * @example
769
+ * ```typescript
770
+ * // In your API route handler
771
+ * app.post('/api/webhooks/aps', (req, res) => {
772
+ * const signature = req.headers['x-aps-signature'] as string;
773
+ * const payload = req.body;
774
+ *
775
+ * // Verify the webhook signature
776
+ * const isValid = aps.webhooks.verifySignature(
777
+ * JSON.stringify(payload),
778
+ * signature
779
+ * );
780
+ *
781
+ * if (!isValid) {
782
+ * return res.status(401).send('Invalid signature');
783
+ * }
784
+ *
785
+ * // Construct the event
786
+ * const event = aps.webhooks.constructEvent(payload);
787
+ *
788
+ * // Handle the event
789
+ * switch (event.type) {
790
+ * case 'payment.success':
791
+ * // Handle successful payment
792
+ * break;
793
+ * case 'payment.failed':
794
+ * // Handle failed payment
795
+ * break;
796
+ * }
797
+ *
798
+ * res.send('OK');
799
+ * });
800
+ * ```
801
+ */
802
+ declare class WebhooksModule {
803
+ private config;
804
+ constructor(config: Required<APSConfig>);
805
+ /**
806
+ * Verify webhook signature
807
+ */
808
+ verifySignature(payload: string, signature: string): boolean;
809
+ /**
810
+ * Construct a webhook event from raw payload
811
+ */
812
+ constructEvent(payload: Record<string, any>): WebhookEvent;
813
+ /**
814
+ * Map APS event to webhook event type
815
+ */
816
+ private mapEventType;
817
+ /**
818
+ * Map APS status to transaction status
819
+ */
820
+ private mapStatus;
821
+ /**
822
+ * Verify and construct event in one step
823
+ */
824
+ safeConstructEvent(payload: string, signature: string): WebhookEvent;
825
+ }
826
+
827
+ /**
828
+ * Recurring Payments Module
829
+ *
830
+ * Process recurring payments using saved card tokens.
831
+ * Designed to be called from server-side cron jobs or scheduled tasks.
832
+ *
833
+ * @example
834
+ * ```typescript
835
+ * // Process a recurring payment (e.g., monthly subscription)
836
+ * const payment = await aps.recurring.process({
837
+ * order: {
838
+ * id: 'sub_123_monthly',
839
+ * amount: 9900, // $99.00
840
+ * currency: 'USD',
841
+ * description: 'Monthly Subscription'
842
+ * },
843
+ * tokenName: 'token_from_original_transaction',
844
+ * agreementId: 'agr_12345',
845
+ * customerEmail: 'customer@example.com'
846
+ * });
847
+ *
848
+ * // Use in a cron job
849
+ * // 0 0 1 * * node process-recurring-payments.js
850
+ * ```
851
+ */
852
+ declare class RecurringModule {
853
+ private config;
854
+ private options;
855
+ constructor(config: Required<APSConfig>, options: Required<Omit<APSClientOptions, 'logger'>> & {
856
+ logger: Logger;
857
+ });
858
+ /**
859
+ * Process a recurring payment using a saved token
860
+ *
861
+ * This method is designed to be called from server-side code,
862
+ * typically in a cron job or scheduled task for subscription billing.
863
+ *
864
+ * @param options - Recurring payment options
865
+ * @returns Recurring payment response
866
+ *
867
+ * @example
868
+ * ```typescript
869
+ * // Monthly subscription charge
870
+ * const payment = await aps.recurring.process({
871
+ * order: {
872
+ * id: `sub_${customerId}_${Date.now()}`,
873
+ * amount: 2999, // $29.99
874
+ * currency: 'USD',
875
+ * description: 'Monthly Pro Plan'
876
+ * },
877
+ * tokenName: savedCard.token,
878
+ * agreementId: savedCard.agreementId,
879
+ * customerEmail: customer.email,
880
+ * customerName: customer.name
881
+ * });
882
+ *
883
+ * if (payment.status === 'captured') {
884
+ * await sendInvoice(customer, payment);
885
+ * } else {
886
+ * await notifyPaymentFailed(customer, payment);
887
+ * }
888
+ * ```
889
+ */
890
+ process(options: RecurringPaymentOptions): Promise<RecurringPaymentResponse>;
891
+ /**
892
+ * Process multiple recurring payments in batch
893
+ *
894
+ * Useful for processing all due subscriptions at once.
895
+ * Returns results for all payments, including failures.
896
+ *
897
+ * @param payments - Array of recurring payment options
898
+ * @returns Array of results with success/failure status
899
+ *
900
+ * @example
901
+ * ```typescript
902
+ * // Process all due subscriptions
903
+ * const dueSubscriptions = await getDueSubscriptions();
904
+ *
905
+ * const results = await aps.recurring.processBatch(
906
+ * dueSubscriptions.map(sub => ({
907
+ * order: {
908
+ * id: `sub_${sub.id}_${Date.now()}`,
909
+ * amount: sub.amount,
910
+ * currency: sub.currency,
911
+ * description: sub.planName
912
+ * },
913
+ * tokenName: sub.tokenName,
914
+ * agreementId: sub.agreementId,
915
+ * customerEmail: sub.customerEmail
916
+ * }))
917
+ * );
918
+ *
919
+ * // Handle results
920
+ * const successful = results.filter(r => r.success);
921
+ * const failed = results.filter(r => !r.success);
922
+ *
923
+ * console.log(`Processed: ${successful.length} succeeded, ${failed.length} failed`);
924
+ * ```
925
+ */
926
+ processBatch(payments: RecurringPaymentOptions[]): Promise<Array<{
927
+ success: boolean;
928
+ data?: RecurringPaymentResponse;
929
+ error?: string;
930
+ orderId: string;
931
+ }>>;
932
+ /**
933
+ * Map APS response code to transaction status
934
+ */
935
+ private mapResponseStatus;
936
+ /**
937
+ * Make API request to APS
938
+ */
939
+ private makeApiRequest;
940
+ }
941
+
942
+ /**
943
+ * Amazon Payment Services Client
944
+ *
945
+ * A Stripe-like SDK for seamless APS integration
946
+ *
947
+ * @example
948
+ * ```typescript
949
+ * import APS from 'amazon-payment-services';
950
+ *
951
+ * const aps = new APS({
952
+ * merchantId: 'your-merchant-id',
953
+ * accessCode: 'your-access-code',
954
+ * requestSecret: 'your-request-secret',
955
+ * responseSecret: 'your-response-secret',
956
+ * environment: 'sandbox'
957
+ * }, {
958
+ * logger: console, // Optional: custom logger
959
+ * timeout: 30000, // Optional: request timeout in ms
960
+ * maxRetries: 3 // Optional: max retry attempts
961
+ * });
962
+ *
963
+ * // Create a payment link
964
+ * const link = await aps.paymentLinks.create({
965
+ * order: {
966
+ * id: 'order_123',
967
+ * amount: 10000, // $100.00
968
+ * currency: 'USD'
969
+ * }
970
+ * });
971
+ * ```
972
+ */
973
+ declare class APSClient {
974
+ /** Payment Links module */
975
+ readonly paymentLinks: PaymentLinksModule;
976
+ /** Hosted Checkout module */
977
+ readonly hostedCheckout: HostedCheckoutModule;
978
+ /** Custom Payment Page module */
979
+ readonly customPaymentPage: CustomPaymentPageModule;
980
+ /** Tokenization module */
981
+ readonly tokens: TokenizationModule;
982
+ /** Payments module (capture, refund, void) */
983
+ readonly payments: PaymentsModule;
984
+ /** Webhooks module */
985
+ readonly webhooks: WebhooksModule;
986
+ /** Recurring payments module */
987
+ readonly recurring: RecurringModule;
988
+ /** Configuration */
989
+ readonly config: Required<APSConfig>;
990
+ /** Client options */
991
+ readonly options: Required<Omit<APSClientOptions, 'logger'>> & {
992
+ logger: Logger;
993
+ };
994
+ /**
995
+ * Create a new APS client instance
996
+ */
997
+ constructor(config: APSConfig, options?: APSClientOptions);
998
+ /**
999
+ * Get the base URL for redirects
1000
+ */
1001
+ getBaseUrl(): string;
1002
+ /**
1003
+ * Get the API URL for server-to-server calls
1004
+ */
1005
+ getApiUrl(): string;
1006
+ /**
1007
+ * Verify a webhook signature
1008
+ */
1009
+ verifyWebhookSignature(payload: string, signature: string): boolean;
1010
+ /**
1011
+ * Construct a webhook event from raw payload
1012
+ */
1013
+ constructWebhookEvent(payload: Record<string, any>): any;
1014
+ /**
1015
+ * Get the logger instance
1016
+ */
1017
+ getLogger(): Logger;
1018
+ /**
1019
+ * Set a custom logger
1020
+ */
1021
+ setLogger(logger: Logger): void;
1022
+ }
1023
+
1024
+ /**
1025
+ * Constants for Amazon Payment Services
1026
+ *
1027
+ * Test cards, response codes, and other constants used throughout the SDK.
1028
+ *
1029
+ * @example
1030
+ * ```typescript
1031
+ * import { TestCards, ResponseCodes, ErrorCategories } from '@sikka/aps';
1032
+ *
1033
+ * // Use test cards in development
1034
+ * const cardNumber = TestCards.VISA.SUCCESS;
1035
+ *
1036
+ * // Check response codes
1037
+ * if (response.response_code === ResponseCodes.SUCCESS) {
1038
+ * // Payment successful
1039
+ * }
1040
+ * ```
1041
+ */
1042
+ /**
1043
+ * Test card numbers for sandbox environment
1044
+ *
1045
+ * These cards can be used in the sandbox environment to simulate different scenarios.
1046
+ *
1047
+ * @example
1048
+ * ```typescript
1049
+ * import { TestCards } from '@sikka/aps';
1050
+ *
1051
+ * // Successful Visa payment
1052
+ * const payment = await aps.tokens.create({
1053
+ * cardNumber: TestCards.VISA.SUCCESS,
1054
+ * expiryMonth: '12',
1055
+ * expiryYear: '25',
1056
+ * cvv: '123'
1057
+ * });
1058
+ *
1059
+ * // Declined Mastercard
1060
+ * const declined = await aps.tokens.create({
1061
+ * cardNumber: TestCards.MASTERCARD.DECLINED,
1062
+ * expiryMonth: '12',
1063
+ * expiryYear: '25',
1064
+ * cvv: '123'
1065
+ * });
1066
+ * ```
1067
+ */
1068
+ declare const TestCards: {
1069
+ /**
1070
+ * Visa test cards
1071
+ */
1072
+ readonly VISA: {
1073
+ /** Successful payment */
1074
+ readonly SUCCESS: "4111111111111111";
1075
+ /** Declined payment */
1076
+ readonly DECLINED: "4000000000000002";
1077
+ /** Insufficient funds */
1078
+ readonly INSUFFICIENT_FUNDS: "4000000000009995";
1079
+ /** Lost card */
1080
+ readonly LOST_CARD: "4000000000009987";
1081
+ /** Stolen card */
1082
+ readonly STOLEN_CARD: "4000000000009979";
1083
+ /** Expired card */
1084
+ readonly EXPIRED_CARD: "4000000000009961";
1085
+ /** Invalid CVV */
1086
+ readonly INVALID_CVV: "4000000000000127";
1087
+ /** 3D Secure required */
1088
+ readonly REQUIRES_3DS: "4000000000003220";
1089
+ };
1090
+ /**
1091
+ * Mastercard test cards
1092
+ */
1093
+ readonly MASTERCARD: {
1094
+ /** Successful payment */
1095
+ readonly SUCCESS: "5100000000000008";
1096
+ /** Declined payment */
1097
+ readonly DECLINED: "5400000000000003";
1098
+ /** Insufficient funds */
1099
+ readonly INSUFFICIENT_FUNDS: "5400000000000094";
1100
+ /** 3D Secure required */
1101
+ readonly REQUIRES_3DS: "5400000000000094";
1102
+ };
1103
+ /**
1104
+ * MADA (Saudi Arabia) test cards
1105
+ */
1106
+ readonly MADA: {
1107
+ /** Successful payment */
1108
+ readonly SUCCESS: "5297410000000002";
1109
+ /** Declined payment */
1110
+ readonly DECLINED: "5297410000000010";
1111
+ /** 3D Secure required */
1112
+ readonly REQUIRES_3DS: "5297410000000028";
1113
+ };
1114
+ /**
1115
+ * American Express test cards
1116
+ */
1117
+ readonly AMEX: {
1118
+ /** Successful payment */
1119
+ readonly SUCCESS: "371449635398431";
1120
+ /** Declined payment */
1121
+ readonly DECLINED: "378282246310005";
1122
+ };
1123
+ /**
1124
+ * Test card defaults
1125
+ */
1126
+ readonly DEFAULTS: {
1127
+ /** Default expiry month (MM) */
1128
+ readonly EXPIRY_MONTH: "12";
1129
+ /** Default expiry year (YY) */
1130
+ readonly EXPIRY_YEAR: "25";
1131
+ /** Default CVV */
1132
+ readonly CVV: "123";
1133
+ /** Default cardholder name */
1134
+ readonly CARDHOLDER_NAME: "Test User";
1135
+ };
1136
+ };
1137
+ /**
1138
+ * APS Response Codes
1139
+ *
1140
+ * Complete list of response codes from Amazon Payment Services API.
1141
+ *
1142
+ * @example
1143
+ * ```typescript
1144
+ * import { ResponseCodes } from '@sikka/aps';
1145
+ *
1146
+ * if (response.response_code === ResponseCodes.SUCCESS) {
1147
+ * // Handle success
1148
+ * } else if (response.response_code === ResponseCodes.INSUFFICIENT_FUNDS) {
1149
+ * // Handle insufficient funds
1150
+ * }
1151
+ * ```
1152
+ */
1153
+ declare const ResponseCodes: {
1154
+ /** Transaction successful */
1155
+ readonly SUCCESS: "00000";
1156
+ /** Payment link created successfully */
1157
+ readonly PAYMENT_LINK_SUCCESS: "48000";
1158
+ /** Recurring payment successful */
1159
+ readonly RECURRING_SUCCESS: "14000";
1160
+ /** 3D Secure authentication failed */
1161
+ readonly AUTHENTICATION_FAILED: "10030";
1162
+ /** 3D Secure not enrolled */
1163
+ readonly NOT_ENROLLED_3DS: "10031";
1164
+ /** Signature mismatch */
1165
+ readonly SIGNATURE_MISMATCH: "00008";
1166
+ /** Invalid access code */
1167
+ readonly INVALID_ACCESS_CODE: "00009";
1168
+ /** Invalid merchant identifier */
1169
+ readonly INVALID_MERCHANT_ID: "00010";
1170
+ /** Card expired */
1171
+ readonly CARD_EXPIRED: "10035";
1172
+ /** Invalid card number */
1173
+ readonly INVALID_CARD_NUMBER: "10036";
1174
+ /** Invalid CVV */
1175
+ readonly INVALID_CVV: "10037";
1176
+ /** Card not supported */
1177
+ readonly CARD_NOT_SUPPORTED: "10038";
1178
+ /** Lost card */
1179
+ readonly LOST_CARD: "10039";
1180
+ /** Stolen card */
1181
+ readonly STOLEN_CARD: "10040";
1182
+ /** Restricted card */
1183
+ readonly RESTRICTED_CARD: "10041";
1184
+ /** Card blocked */
1185
+ readonly CARD_BLOCKED: "10042";
1186
+ /** Invalid expiry date */
1187
+ readonly INVALID_EXPIRY: "10043";
1188
+ /** Transaction declined */
1189
+ readonly DECLINED: "14001";
1190
+ /** Insufficient funds */
1191
+ readonly INSUFFICIENT_FUNDS: "14002";
1192
+ /** Transaction limit exceeded */
1193
+ readonly LIMIT_EXCEEDED: "14003";
1194
+ /** Invalid transaction */
1195
+ readonly INVALID_TRANSACTION: "14004";
1196
+ /** Duplicate transaction */
1197
+ readonly DUPLICATE_TRANSACTION: "14005";
1198
+ /** Transaction not allowed */
1199
+ readonly TRANSACTION_NOT_ALLOWED: "14006";
1200
+ /** Transaction expired */
1201
+ readonly TRANSACTION_EXPIRED: "14007";
1202
+ /** Transaction already captured */
1203
+ readonly ALREADY_CAPTURED: "14008";
1204
+ /** Transaction already voided */
1205
+ readonly ALREADY_VOIDED: "14009";
1206
+ /** Transaction already refunded */
1207
+ readonly ALREADY_REFUNDED: "14010";
1208
+ /** Invalid amount */
1209
+ readonly INVALID_AMOUNT: "15001";
1210
+ /** Amount too small */
1211
+ readonly AMOUNT_TOO_SMALL: "15002";
1212
+ /** Amount too large */
1213
+ readonly AMOUNT_TOO_LARGE: "15003";
1214
+ /** Currency not supported */
1215
+ readonly CURRENCY_NOT_SUPPORTED: "15004";
1216
+ /** Missing parameter */
1217
+ readonly MISSING_PARAMETER: "00001";
1218
+ /** Invalid parameter format */
1219
+ readonly INVALID_PARAMETER: "00002";
1220
+ /** Invalid command */
1221
+ readonly INVALID_COMMAND: "00003";
1222
+ /** Invalid language */
1223
+ readonly INVALID_LANGUAGE: "00004";
1224
+ /** Invalid currency */
1225
+ readonly INVALID_CURRENCY: "00005";
1226
+ /** Invalid return URL */
1227
+ readonly INVALID_RETURN_URL: "00006";
1228
+ /** Invalid customer email */
1229
+ readonly INVALID_EMAIL: "00007";
1230
+ /** Parameter value not allowed */
1231
+ readonly PARAMETER_VALUE_NOT_ALLOWED: "00033";
1232
+ /** Token not found */
1233
+ readonly TOKEN_NOT_FOUND: "16001";
1234
+ /** Token expired */
1235
+ readonly TOKEN_EXPIRED: "16002";
1236
+ /** Token already used */
1237
+ readonly TOKEN_ALREADY_USED: "16003";
1238
+ /** Invalid token */
1239
+ readonly INVALID_TOKEN: "16004";
1240
+ /** System error */
1241
+ readonly SYSTEM_ERROR: "90001";
1242
+ /** Service unavailable */
1243
+ readonly SERVICE_UNAVAILABLE: "90002";
1244
+ /** Timeout */
1245
+ readonly TIMEOUT: "90003";
1246
+ /** Database error */
1247
+ readonly DATABASE_ERROR: "90004";
1248
+ /** Internal error */
1249
+ readonly INTERNAL_ERROR: "90005";
1250
+ };
1251
+ /**
1252
+ * Error Categories
1253
+ *
1254
+ * Group response codes into categories for easier handling.
1255
+ *
1256
+ * @example
1257
+ * ```typescript
1258
+ * import { ErrorCategories, categorizeError } from '@sikka/aps';
1259
+ *
1260
+ * const category = categorizeError(response.response_code);
1261
+ *
1262
+ * if (category === ErrorCategories.CARD_ERROR) {
1263
+ * // Ask customer to check card details
1264
+ * } else if (category === ErrorCategories.RETRYABLE) {
1265
+ * // Can retry the transaction
1266
+ * }
1267
+ * ```
1268
+ */
1269
+ declare const ErrorCategories: {
1270
+ /** Success - no error */
1271
+ readonly SUCCESS: "success";
1272
+ /** Card-related errors (expired, invalid, blocked) */
1273
+ readonly CARD_ERROR: "card_error";
1274
+ /** Authentication errors (3DS, signature) */
1275
+ readonly AUTHENTICATION_ERROR: "authentication_error";
1276
+ /** Transaction errors (declined, insufficient funds) */
1277
+ readonly TRANSACTION_ERROR: "transaction_error";
1278
+ /** Amount/currency errors */
1279
+ readonly AMOUNT_ERROR: "amount_error";
1280
+ /** Parameter validation errors */
1281
+ readonly VALIDATION_ERROR: "validation_error";
1282
+ /** Tokenization errors */
1283
+ readonly TOKEN_ERROR: "token_error";
1284
+ /** System/technical errors */
1285
+ readonly SYSTEM_ERROR: "system_error";
1286
+ /** Errors that can be retried */
1287
+ readonly RETRYABLE: "retryable";
1288
+ /** Errors that should not be retried */
1289
+ readonly NON_RETRYABLE: "non_retryable";
1290
+ };
1291
+ /**
1292
+ * Categorize an error code
1293
+ *
1294
+ * @param code - The APS response code
1295
+ * @returns The error category
1296
+ *
1297
+ * @example
1298
+ * ```typescript
1299
+ * import { categorizeError, ErrorCategories } from '@sikka/aps';
1300
+ *
1301
+ * const category = categorizeError('14002');
1302
+ * console.log(category); // 'transaction_error'
1303
+ *
1304
+ * if (category === ErrorCategories.CARD_ERROR) {
1305
+ * // Show card error message to customer
1306
+ * }
1307
+ * ```
1308
+ */
1309
+ declare function categorizeError(code: string): string;
1310
+ /**
1311
+ * Check if an error code is retryable
1312
+ *
1313
+ * @param code - The APS response code
1314
+ * @returns True if the error can be retried
1315
+ *
1316
+ * @example
1317
+ * ```typescript
1318
+ * import { isRetryableError } from '@sikka/aps';
1319
+ *
1320
+ * if (isRetryableError(response.response_code)) {
1321
+ * // Retry the transaction
1322
+ * await retryPayment();
1323
+ * }
1324
+ * ```
1325
+ */
1326
+ declare function isRetryableError$1(code: string): boolean;
1327
+ /**
1328
+ * Payment method codes used by APS
1329
+ */
1330
+ declare const PaymentMethodCodes: {
1331
+ /** Visa */
1332
+ readonly VISA: "VISA";
1333
+ /** Mastercard */
1334
+ readonly MASTERCARD: "MASTERCARD";
1335
+ /** American Express */
1336
+ readonly AMEX: "AMEX";
1337
+ /** MADA (Saudi Arabia) */
1338
+ readonly MADA: "MADA";
1339
+ /** Apple Pay */
1340
+ readonly APPLE_PAY: "APPLE_PAY";
1341
+ /** STC Pay (Saudi Arabia) */
1342
+ readonly STC_PAY: "STC_PAY";
1343
+ /** KNET (Kuwait) */
1344
+ readonly KNET: "KNET";
1345
+ /** NAPS (Qatar) */
1346
+ readonly NAPS: "NAPS";
1347
+ /** Fawry (Egypt) */
1348
+ readonly FAWRY: "FAWRY";
1349
+ /** Meeza (Egypt) */
1350
+ readonly MEEZA: "MEEZA";
1351
+ /** Sadad (Saudi Arabia) */
1352
+ readonly SADAD: "SADAD";
1353
+ /** Aman (Egypt) */
1354
+ readonly AMAN: "AMAN";
1355
+ /** Tabby (BNPL) */
1356
+ readonly TABBY: "TABBY";
1357
+ /** Tamara (BNPL) */
1358
+ readonly TAMARA: "TAMARA";
1359
+ /** valU (BNPL) */
1360
+ readonly VALU: "VALU";
1361
+ };
1362
+ /**
1363
+ * Currency codes supported by APS
1364
+ */
1365
+ declare const CurrencyCodes: {
1366
+ /** Saudi Riyal */
1367
+ readonly SAR: "SAR";
1368
+ /** UAE Dirham */
1369
+ readonly AED: "AED";
1370
+ /** Kuwaiti Dinar */
1371
+ readonly KWD: "KWD";
1372
+ /** Qatari Riyal */
1373
+ readonly QAR: "QAR";
1374
+ /** Bahraini Dinar */
1375
+ readonly BHD: "BHD";
1376
+ /** Omani Rial */
1377
+ readonly OMR: "OMR";
1378
+ /** Jordanian Dinar */
1379
+ readonly JOD: "JOD";
1380
+ /** Egyptian Pound */
1381
+ readonly EGP: "EGP";
1382
+ /** US Dollar */
1383
+ readonly USD: "USD";
1384
+ /** Euro */
1385
+ readonly EUR: "EUR";
1386
+ /** British Pound */
1387
+ readonly GBP: "GBP";
1388
+ };
1389
+ /**
1390
+ * Language codes supported by APS
1391
+ */
1392
+ declare const LanguageCodes: {
1393
+ /** English */
1394
+ readonly EN: "en";
1395
+ /** Arabic */
1396
+ readonly AR: "ar";
1397
+ };
1398
+ /**
1399
+ * Transaction commands
1400
+ */
1401
+ declare const Commands: {
1402
+ /** Purchase (direct charge) */
1403
+ readonly PURCHASE: "PURCHASE";
1404
+ /** Authorization (hold funds) */
1405
+ readonly AUTHORIZATION: "AUTHORIZATION";
1406
+ /** Capture authorized funds */
1407
+ readonly CAPTURE: "CAPTURE";
1408
+ /** Refund a transaction */
1409
+ readonly REFUND: "REFUND";
1410
+ /** Void a transaction */
1411
+ readonly VOID: "VOID";
1412
+ /** Query transaction status */
1413
+ readonly QUERY: "QUERY_TRANSACTION";
1414
+ /** Tokenize a card */
1415
+ readonly TOKENIZATION: "TOKENIZATION";
1416
+ /** Create token */
1417
+ readonly CREATE_TOKEN: "CREATE_TOKEN";
1418
+ /** Verify token */
1419
+ readonly VERIFY_TOKEN: "VERIFY_TOKEN";
1420
+ /** Delete token */
1421
+ readonly DELETE_TOKEN: "DELETE_TOKEN";
1422
+ /** Get saved cards */
1423
+ readonly GET_CARDS: "GET_CARDS";
1424
+ /** Payment link */
1425
+ readonly PAYMENT_LINK: "PAYMENT_LINK";
1426
+ };
1427
+ /**
1428
+ * ECI (Electronic Commerce Indicator) values
1429
+ */
1430
+ declare const ECIValues: {
1431
+ /** Secure e-commerce with 3DS */
1432
+ readonly SECURE_3DS: "05";
1433
+ /** Non-3DS e-commerce */
1434
+ readonly NON_3DS: "07";
1435
+ /** Recurring payment */
1436
+ readonly RECURRING: "RECURRING";
1437
+ /** Merchant-initiated */
1438
+ readonly MERCHANT_INITIATED: "07";
1439
+ };
1440
+ /**
1441
+ * Status codes returned by APS
1442
+ */
1443
+ declare const StatusCodes: {
1444
+ /** Success */
1445
+ readonly SUCCESS: "20";
1446
+ /** Pending/3DS required */
1447
+ readonly PENDING: "3";
1448
+ /** Authorized */
1449
+ readonly AUTHORIZED: "02";
1450
+ /** Captured */
1451
+ readonly CAPTURED: "04";
1452
+ };
1453
+
1454
+ /**
1455
+ * Error Handling for Amazon Payment Services
1456
+ *
1457
+ * Provides human-readable error messages, suggested actions, and error categorization
1458
+ * for all APS response codes.
1459
+ *
1460
+ * @example
1461
+ * ```typescript
1462
+ * import { getErrorDetails, isRetryableError } from '@sikka/aps';
1463
+ *
1464
+ * try {
1465
+ * await aps.paymentLinks.create({...});
1466
+ * } catch (error) {
1467
+ * if (error instanceof APSException) {
1468
+ * const details = getErrorDetails(error.code);
1469
+ * console.log(details.message); // Human-readable message
1470
+ * console.log(details.action); // Suggested action
1471
+ * console.log(details.category); // Error category
1472
+ * console.log(details.documentation); // Link to docs
1473
+ * }
1474
+ * }
1475
+ * ```
1476
+ */
1477
+ /**
1478
+ * Error details interface
1479
+ */
1480
+ interface ErrorDetails {
1481
+ /** The error code */
1482
+ code: string;
1483
+ /** Human-readable error message */
1484
+ message: string;
1485
+ /** Suggested action to resolve */
1486
+ action: string;
1487
+ /** Error category */
1488
+ category: string;
1489
+ /** Whether this error can be retried */
1490
+ retryable: boolean;
1491
+ /** Link to APS documentation */
1492
+ documentation: string;
1493
+ /** HTTP status code (if applicable) */
1494
+ httpStatus?: number;
1495
+ }
1496
+ /**
1497
+ * Get detailed error information for an APS response code
1498
+ *
1499
+ * @param code - The APS response code
1500
+ * @returns Error details with message, action, and documentation link
1501
+ *
1502
+ * @example
1503
+ * ```typescript
1504
+ * import { getErrorDetails } from '@sikka/aps';
1505
+ *
1506
+ * const details = getErrorDetails('14002');
1507
+ * console.log(details.message); // "The card has insufficient funds."
1508
+ * console.log(details.action); // "Ask the customer to use a different card..."
1509
+ * console.log(details.retryable); // false
1510
+ * ```
1511
+ */
1512
+ declare function getErrorDetails(code: string): ErrorDetails;
1513
+ /**
1514
+ * Check if an error code is retryable
1515
+ *
1516
+ * @param code - The APS response code
1517
+ * @returns True if the error can be safely retried
1518
+ *
1519
+ * @example
1520
+ * ```typescript
1521
+ * import { isRetryableError } from '@sikka/aps';
1522
+ *
1523
+ * if (isRetryableError(error.code)) {
1524
+ * await retryPayment();
1525
+ * }
1526
+ * ```
1527
+ */
1528
+ declare function isRetryableError(code: string): boolean;
1529
+ /**
1530
+ * Get a user-friendly error message for display
1531
+ *
1532
+ * @param code - The APS response code
1533
+ * @param includeAction - Whether to include the suggested action (default: true)
1534
+ * @returns Formatted error message
1535
+ *
1536
+ * @example
1537
+ * ```typescript
1538
+ * import { getUserFriendlyMessage } from '@sikka/aps';
1539
+ *
1540
+ * const message = getUserFriendlyMessage('14002');
1541
+ * // "The card has insufficient funds. Ask the customer to use a different card..."
1542
+ *
1543
+ * const shortMessage = getUserFriendlyMessage('14002', false);
1544
+ * // "The card has insufficient funds."
1545
+ * ```
1546
+ */
1547
+ declare function getUserFriendlyMessage(code: string, includeAction?: boolean): string;
1548
+ /**
1549
+ * Format an error for logging
1550
+ *
1551
+ * @param code - The APS response code
1552
+ * @param context - Additional context (order ID, transaction ID, etc.)
1553
+ * @returns Formatted log message
1554
+ *
1555
+ * @example
1556
+ * ```typescript
1557
+ * import { formatErrorForLogging } from '@sikka/aps';
1558
+ *
1559
+ * const logMessage = formatErrorForLogging('14002', {
1560
+ * orderId: 'order_123',
1561
+ * customerEmail: 'customer@example.com'
1562
+ * });
1563
+ * // "[APS Error 14002] INSUFFICIENT_FUNDS: The card has insufficient funds. (orderId: order_123)"
1564
+ * ```
1565
+ */
1566
+ declare function formatErrorForLogging(code: string, context?: Record<string, string>): string;
1567
+ /**
1568
+ * Check if the response code indicates success
1569
+ *
1570
+ * @param code - The APS response code
1571
+ * @returns True if the code indicates success
1572
+ *
1573
+ * @example
1574
+ * ```typescript
1575
+ * import { isSuccessCode } from '@sikka/aps';
1576
+ *
1577
+ * if (isSuccessCode(response.response_code)) {
1578
+ * // Handle success
1579
+ * }
1580
+ * ```
1581
+ */
1582
+ declare function isSuccessCode(code: string): boolean;
1583
+ /**
1584
+ * Get all error codes for a category
1585
+ *
1586
+ * @param category - The error category
1587
+ * @returns Array of error codes in that category
1588
+ *
1589
+ * @example
1590
+ * ```typescript
1591
+ * import { getErrorCodesByCategory, ErrorCategories } from '@sikka/aps';
1592
+ *
1593
+ * const cardErrors = getErrorCodesByCategory(ErrorCategories.CARD_ERROR);
1594
+ * // ['10035', '10036', '10037', ...]
1595
+ * ```
1596
+ */
1597
+ declare function getErrorCodesByCategory(category: string): string[];
1598
+ /**
1599
+ * Suggest HTTP status code for an APS error
1600
+ *
1601
+ * @param code - The APS response code
1602
+ * @returns Suggested HTTP status code
1603
+ *
1604
+ * @example
1605
+ * ```typescript
1606
+ * import { suggestHttpStatus } from '@sikka/aps';
1607
+ *
1608
+ * const status = suggestHttpStatus('14002');
1609
+ * // 402 (Payment Required)
1610
+ * ```
1611
+ */
1612
+ declare function suggestHttpStatus(code: string): number;
1613
+
1614
+ /**
1615
+ * Validation Utilities for Amazon Payment Services
1616
+ *
1617
+ * Provides validation functions for APS-specific data formats and requirements.
1618
+ *
1619
+ * @example
1620
+ * ```typescript
1621
+ * import { validators } from '@sikka/aps';
1622
+ *
1623
+ * // Validate merchant reference
1624
+ * if (!validators.isValidMerchantReference(ref)) {
1625
+ * throw new Error('Invalid merchant reference format');
1626
+ * }
1627
+ *
1628
+ * // Validate signature
1629
+ * if (!validators.isValidSignature(payload, signature, secret)) {
1630
+ * throw new Error('Invalid signature');
1631
+ * }
1632
+ * ```
1633
+ */
1634
+ /**
1635
+ * Validation result interface
1636
+ */
1637
+ interface ValidationResult {
1638
+ /** Whether validation passed */
1639
+ valid: boolean;
1640
+ /** Error message if validation failed */
1641
+ error?: string;
1642
+ /** Error code if validation failed */
1643
+ code?: string;
1644
+ }
1645
+ /**
1646
+ * Validate a merchant reference
1647
+ *
1648
+ * APS has specific requirements for merchant_reference:
1649
+ * - Must be unique per transaction
1650
+ * - Max 40 characters
1651
+ * - Alphanumeric and underscores only
1652
+ *
1653
+ * @param reference - The merchant reference to validate
1654
+ * @returns Validation result
1655
+ *
1656
+ * @example
1657
+ * ```typescript
1658
+ * import { validators } from '@sikka/aps';
1659
+ *
1660
+ * const result = validators.isValidMerchantReference('order_123');
1661
+ * if (!result.valid) {
1662
+ * console.log(result.error); // "Merchant reference must be 40 characters or less"
1663
+ * }
1664
+ * ```
1665
+ */
1666
+ declare function isValidMerchantReference(reference: string): ValidationResult;
1667
+ /**
1668
+ * Validate an amount for APS
1669
+ *
1670
+ * APS requires amounts in the smallest currency unit (cents, fils)
1671
+ * without decimal points.
1672
+ *
1673
+ * @param amount - The amount to validate
1674
+ * @param currency - The currency code
1675
+ * @returns Validation result
1676
+ *
1677
+ * @example
1678
+ * ```typescript
1679
+ * import { validators } from '@sikka/aps';
1680
+ *
1681
+ * // Valid: 10000 = 100.00 SAR
1682
+ * const result = validators.isValidAmount(10000, 'SAR');
1683
+ *
1684
+ * // Invalid: decimal amounts not allowed
1685
+ * const result2 = validators.isValidAmount(100.50, 'SAR');
1686
+ * ```
1687
+ */
1688
+ declare function isValidAmount(amount: number, _currency?: string): ValidationResult;
1689
+ /**
1690
+ * Validate a currency code
1691
+ *
1692
+ * @param currency - The currency code to validate
1693
+ * @returns Validation result
1694
+ *
1695
+ * @example
1696
+ * ```typescript
1697
+ * import { validators } from '@sikka/aps';
1698
+ *
1699
+ * const result = validators.isValidCurrency('SAR'); // valid
1700
+ * const result2 = validators.isValidCurrency('INVALID'); // invalid
1701
+ * ```
1702
+ */
1703
+ declare function isValidCurrency(currency: string): ValidationResult;
1704
+ /**
1705
+ * Validate an email address
1706
+ *
1707
+ * @param email - The email to validate
1708
+ * @returns Validation result
1709
+ *
1710
+ * @example
1711
+ * ```typescript
1712
+ * import { validators } from '@sikka/aps';
1713
+ *
1714
+ * const result = validators.isValidEmail('customer@example.com');
1715
+ * ```
1716
+ */
1717
+ declare function isValidEmail(email: string): ValidationResult;
1718
+ /**
1719
+ * Validate a card number using Luhn algorithm
1720
+ *
1721
+ * @param cardNumber - The card number to validate
1722
+ * @returns Validation result
1723
+ *
1724
+ * @example
1725
+ * ```typescript
1726
+ * import { validators } from '@sikka/aps';
1727
+ *
1728
+ * const result = validators.isValidCardNumber('4111111111111111');
1729
+ * ```
1730
+ */
1731
+ declare function isValidCardNumber(cardNumber: string): ValidationResult;
1732
+ /**
1733
+ * Validate expiry date
1734
+ *
1735
+ * @param month - Expiry month (1-12 or 01-12)
1736
+ * @param year - Expiry year (2-digit or 4-digit)
1737
+ * @returns Validation result
1738
+ *
1739
+ * @example
1740
+ * ```typescript
1741
+ * import { validators } from '@sikka/aps';
1742
+ *
1743
+ * const result = validators.isValidExpiryDate('12', '25');
1744
+ * const result2 = validators.isValidExpiryDate('12', '2025');
1745
+ * ```
1746
+ */
1747
+ declare function isValidExpiryDate(month: string, year: string): ValidationResult;
1748
+ /**
1749
+ * Validate CVV
1750
+ *
1751
+ * @param cvv - The CVV to validate
1752
+ * @param cardType - Optional card type (affects CVV length)
1753
+ * @returns Validation result
1754
+ *
1755
+ * @example
1756
+ * ```typescript
1757
+ * import { validators } from '@sikka/aps';
1758
+ *
1759
+ * const result = validators.isValidCVV('123'); // Visa/MC
1760
+ * const result2 = validators.isValidCVV('1234'); // Amex
1761
+ * ```
1762
+ */
1763
+ declare function isValidCVV(cvv: string, cardType?: string): ValidationResult;
1764
+ /**
1765
+ * Validate a return URL
1766
+ *
1767
+ * @param url - The URL to validate
1768
+ * @returns Validation result
1769
+ *
1770
+ * @example
1771
+ * ```typescript
1772
+ * import { validators } from '@sikka/aps';
1773
+ *
1774
+ * const result = validators.isValidReturnUrl('https://example.com/result');
1775
+ * ```
1776
+ */
1777
+ declare function isValidReturnUrl(url: string): ValidationResult;
1778
+ /**
1779
+ * Validate an APS signature
1780
+ *
1781
+ * @param params - The parameters that were signed
1782
+ * @param signature - The signature to validate
1783
+ * @param secret - The secret key used for signing
1784
+ * @returns Whether the signature is valid
1785
+ *
1786
+ * @example
1787
+ * ```typescript
1788
+ * import { validators } from '@sikka/aps';
1789
+ *
1790
+ * const isValid = validators.isValidSignature(
1791
+ * params,
1792
+ * response.signature,
1793
+ * process.env.APS_RESPONSE_SECRET
1794
+ * );
1795
+ * ```
1796
+ */
1797
+ declare function isValidSignature(params: Record<string, string>, signature: string, secret: string): boolean;
1798
+ /**
1799
+ * Validate webhook payload
1800
+ *
1801
+ * @param payload - The webhook payload
1802
+ * @param signature - The signature from headers
1803
+ * @param secret - The response secret
1804
+ * @returns Validation result
1805
+ *
1806
+ * @example
1807
+ * ```typescript
1808
+ * import { validators } from '@sikka/aps';
1809
+ *
1810
+ * const result = validators.isValidWebhookPayload(
1811
+ * req.body,
1812
+ * req.headers['x-aps-signature'],
1813
+ * process.env.APS_RESPONSE_SECRET
1814
+ * );
1815
+ *
1816
+ * if (!result.valid) {
1817
+ * return res.status(401).send('Invalid signature');
1818
+ * }
1819
+ * ```
1820
+ */
1821
+ declare function isValidWebhookPayload(payload: Record<string, any>, signature: string, secret: string): ValidationResult;
1822
+ /**
1823
+ * Validate language code
1824
+ *
1825
+ * @param language - The language code to validate
1826
+ * @returns Validation result
1827
+ *
1828
+ * @example
1829
+ * ```typescript
1830
+ * import { validators } from '@sikka/aps';
1831
+ *
1832
+ * const result = validators.isValidLanguage('en');
1833
+ * const result2 = validators.isValidLanguage('ar');
1834
+ * ```
1835
+ */
1836
+ declare function isValidLanguage(language: string): ValidationResult;
1837
+ /**
1838
+ * Validate token name
1839
+ *
1840
+ * @param tokenName - The token name to validate
1841
+ * @returns Validation result
1842
+ *
1843
+ * @example
1844
+ * ```typescript
1845
+ * import { validators } from '@sikka/aps';
1846
+ *
1847
+ * const result = validators.isValidTokenName('token_abc123');
1848
+ * ```
1849
+ */
1850
+ declare function isValidTokenName(tokenName: string): ValidationResult;
1851
+ /**
1852
+ * Validate phone number
1853
+ *
1854
+ * @param phone - The phone number to validate
1855
+ * @returns Validation result
1856
+ *
1857
+ * @example
1858
+ * ```typescript
1859
+ * import { validators } from '@sikka/aps';
1860
+ *
1861
+ * const result = validators.isValidPhone('+966501234567');
1862
+ * ```
1863
+ */
1864
+ declare function isValidPhone(phone: string): ValidationResult;
1865
+ /**
1866
+ * Validate order description
1867
+ *
1868
+ * @param description - The description to validate
1869
+ * @returns Validation result
1870
+ *
1871
+ * @example
1872
+ * ```typescript
1873
+ * import { validators } from '@sikka/aps';
1874
+ *
1875
+ * const result = validators.isValidDescription('Premium Plan Subscription');
1876
+ * ```
1877
+ */
1878
+ declare function isValidDescription(description: string): ValidationResult;
1879
+ /**
1880
+ * Validate customer name
1881
+ *
1882
+ * @param name - The customer name to validate
1883
+ * @returns Validation result
1884
+ *
1885
+ * @example
1886
+ * ```typescript
1887
+ * import { validators } from '@sikka/aps';
1888
+ *
1889
+ * const result = validators.isValidCustomerName('John Doe');
1890
+ * ```
1891
+ */
1892
+ declare function isValidCustomerName(name: string): ValidationResult;
1893
+ /**
1894
+ * Validate all payment parameters at once
1895
+ *
1896
+ * @param params - The payment parameters to validate
1897
+ * @returns Validation result with all errors
1898
+ *
1899
+ * @example
1900
+ * ```typescript
1901
+ * import { validators } from '@sikka/aps';
1902
+ *
1903
+ * const result = validators.validatePaymentParams({
1904
+ * merchant_reference: 'order_123',
1905
+ * amount: 10000,
1906
+ * currency: 'SAR',
1907
+ * customer_email: 'customer@example.com'
1908
+ * });
1909
+ *
1910
+ * if (!result.valid) {
1911
+ * console.log(result.errors);
1912
+ * }
1913
+ * ```
1914
+ */
1915
+ declare function validatePaymentParams(params: {
1916
+ merchant_reference?: string;
1917
+ amount?: number;
1918
+ currency?: string;
1919
+ customer_email?: string;
1920
+ return_url?: string;
1921
+ description?: string;
1922
+ language?: string;
1923
+ }): {
1924
+ valid: boolean;
1925
+ errors: Array<{
1926
+ field: string;
1927
+ error: string;
1928
+ code: string;
1929
+ }>;
1930
+ };
1931
+ /**
1932
+ * Export all validators as a namespace
1933
+ */
1934
+ declare const validators: {
1935
+ isValidMerchantReference: typeof isValidMerchantReference;
1936
+ isValidAmount: typeof isValidAmount;
1937
+ isValidCurrency: typeof isValidCurrency;
1938
+ isValidEmail: typeof isValidEmail;
1939
+ isValidCardNumber: typeof isValidCardNumber;
1940
+ isValidExpiryDate: typeof isValidExpiryDate;
1941
+ isValidCVV: typeof isValidCVV;
1942
+ isValidReturnUrl: typeof isValidReturnUrl;
1943
+ isValidSignature: typeof isValidSignature;
1944
+ isValidWebhookPayload: typeof isValidWebhookPayload;
1945
+ isValidLanguage: typeof isValidLanguage;
1946
+ isValidTokenName: typeof isValidTokenName;
1947
+ isValidPhone: typeof isValidPhone;
1948
+ isValidDescription: typeof isValidDescription;
1949
+ isValidCustomerName: typeof isValidCustomerName;
1950
+ validatePaymentParams: typeof validatePaymentParams;
1951
+ };
1952
+
1953
+ /**
1954
+ * Amazon Payment Services SDK
1955
+ *
1956
+ * A Stripe-like developer-friendly SDK for Amazon Payment Services integration.
1957
+ *
1958
+ * @example
1959
+ * ```typescript
1960
+ * import APS from 'amazon-payment-services';
1961
+ *
1962
+ * // Initialize the client
1963
+ * const aps = new APS({
1964
+ * merchantId: process.env.APS_MERCHANT_ID,
1965
+ * accessCode: process.env.APS_ACCESS_CODE,
1966
+ * requestSecret: process.env.APS_REQUEST_SECRET,
1967
+ * responseSecret: process.env.APS_RESPONSE_SECRET,
1968
+ * environment: 'sandbox' // or 'production'
1969
+ * });
1970
+ *
1971
+ * // Create a payment link
1972
+ * const link = await aps.paymentLinks.create({
1973
+ * order: {
1974
+ * id: 'order_123',
1975
+ * amount: 10000, // $100.00
1976
+ * currency: 'USD'
1977
+ * },
1978
+ * successUrl: 'https://yoursite.com/success'
1979
+ * });
1980
+ *
1981
+ * // Create hosted checkout
1982
+ * const checkout = await aps.hostedCheckout.create({
1983
+ * order: { ... },
1984
+ * successUrl: 'https://yoursite.com/success'
1985
+ * });
1986
+ *
1987
+ * // Tokenize a card
1988
+ * const token = await aps.tokens.create({
1989
+ * cardNumber: '4111111111111111',
1990
+ * expiryMonth: '12',
1991
+ * expiryYear: '25',
1992
+ * cvv: '123'
1993
+ * });
1994
+ *
1995
+ * // Capture, refund, void payments
1996
+ * await aps.payments.capture({ transactionId: 'txn_123' });
1997
+ * await aps.payments.refund({ transactionId: 'txn_123', amount: 5000 });
1998
+ * await aps.payments.void({ transactionId: 'txn_123' });
1999
+ *
2000
+ * // Handle webhooks
2001
+ * const event = aps.webhooks.constructEvent(payload);
2002
+ * ```
2003
+ */
2004
+
2005
+ declare const APS: typeof APSClient;
2006
+
2007
+ export { APS, APSClient, type APSClientOptions, type APSConfig, type APSError, APSException, type CaptureOptions, type CaptureResponse, Commands, CurrencyCodes, CustomPaymentPageModule, type CustomPaymentPageOptions, type Customer, ECIValues, ErrorCategories, type ErrorDetails, HostedCheckoutModule, type HostedCheckoutOptions, type IdempotencyOptions, LanguageCodes, type Logger, type Order, type PaymentLinkOptions, type PaymentLinkResponse, PaymentLinksModule, type PaymentMethod, PaymentMethodCodes, type PaymentResponse, PaymentsModule, type QueryOptions, type RateLimitConfig, RecurringModule, type RecurringPaymentOptions, type RecurringPaymentResponse, type RefundOptions, type RefundResponse, ResponseCodes, type SavedCard, type SavedCardsList, StatusCodes, TestCards, TokenizationModule, type TokenizeCardOptions, type TokenizedCard, type TransactionStatus, type ValidationResult, type VoidOptions, type VoidResponse, type WebhookEvent, type WebhookEventType, WebhooksModule, categorizeError, isRetryableError as checkRetryableError, APSClient as default, formatErrorForLogging, getErrorCodesByCategory, getErrorDetails, getUserFriendlyMessage, isRetryableError$1 as isRetryableError, isSuccessCode, isValidAmount, isValidCVV, isValidCardNumber, isValidCurrency, isValidCustomerName, isValidDescription, isValidEmail, isValidExpiryDate, isValidLanguage, isValidMerchantReference, isValidPhone, isValidReturnUrl, isValidSignature, isValidTokenName, isValidWebhookPayload, suggestHttpStatus, validatePaymentParams, validators };