@unify-payment/node 0.0.11 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { EventEntity } from '@paddle/paddle-node-sdk';
1
2
  import Stripe$1, { Stripe as Stripe$2 } from 'stripe';
2
3
 
3
4
  interface IBkashCheckoutOptions {
@@ -279,6 +280,117 @@ declare class Paypal extends UnifyFetch {
279
280
  getCheckoutUrl(payload: IPaypalPayload): Promise<string>;
280
281
  }
281
282
 
283
+ interface IPolarOptions {
284
+ accessToken: string;
285
+ sandbox?: boolean;
286
+ }
287
+ interface IPolarCheckoutCreatePayload {
288
+ products: Array<{
289
+ product_id: string;
290
+ quantity?: number;
291
+ }>;
292
+ customer_email?: string;
293
+ customer_name?: string;
294
+ customer_external_id?: string;
295
+ success_url?: string;
296
+ metadata?: Record<string, string>;
297
+ allow_discount_codes?: boolean;
298
+ discount_id?: string;
299
+ }
300
+
301
+ declare class Polar extends UnifyFetch {
302
+ private accessToken;
303
+ private sandbox;
304
+ constructor(options: IPolarOptions);
305
+ private getApiBaseUrl;
306
+ private getApiRequestHeaders;
307
+ getCheckoutUrl(payload: IPolarCheckoutCreatePayload): Promise<string>;
308
+ verifySignature(payload: {
309
+ body: string;
310
+ signature: string;
311
+ secret: string;
312
+ webhookId: string;
313
+ timestamp: string;
314
+ }): Promise<{
315
+ type: string;
316
+ event: unknown;
317
+ } | {
318
+ error: Error;
319
+ }>;
320
+ }
321
+
322
+ interface IRazorpayOptions {
323
+ keyId: string;
324
+ keySecret: string;
325
+ }
326
+ interface IRazorpayPaymentLinkPayload {
327
+ amount: number;
328
+ currency: string;
329
+ description?: string;
330
+ customer?: {
331
+ name?: string;
332
+ email?: string;
333
+ contact?: string;
334
+ };
335
+ notify?: {
336
+ sms?: boolean;
337
+ email?: boolean;
338
+ };
339
+ callback_url: string;
340
+ callback_method: "get";
341
+ notes?: Record<string, string>;
342
+ }
343
+
344
+ declare class Razorpay extends UnifyFetch {
345
+ private keyId;
346
+ private keySecret;
347
+ constructor(options: IRazorpayOptions);
348
+ private getApiBaseUrl;
349
+ private getApiRequestHeaders;
350
+ getCheckoutUrl(payload: IRazorpayPaymentLinkPayload): Promise<string>;
351
+ verifySignature(payload: {
352
+ body: string;
353
+ signature: string;
354
+ secret: string;
355
+ }): Promise<{
356
+ type: string;
357
+ event: unknown;
358
+ } | {
359
+ error: Error;
360
+ }>;
361
+ }
362
+
363
+ interface IPaddleOptions {
364
+ apiKey: string;
365
+ sandbox?: boolean;
366
+ }
367
+
368
+ declare class Paddle {
369
+ private sdk;
370
+ constructor(options: IPaddleOptions);
371
+ createTransaction(params: {
372
+ items: Array<{
373
+ priceId: string;
374
+ quantity: number;
375
+ }>;
376
+ customerId?: string;
377
+ customData?: Record<string, string>;
378
+ }): Promise<{
379
+ id: string;
380
+ url: string;
381
+ }>;
382
+ verifySignature(payload: {
383
+ body: string;
384
+ secret: string;
385
+ signature: string;
386
+ }): Promise<{
387
+ type: string;
388
+ event: EventEntity;
389
+ } | {
390
+ error: Error;
391
+ }>;
392
+ }
393
+
282
394
  type ISSLCommerzCreateCheckoutPayload = {
283
395
  tran_id: string;
284
396
  store_id: string;
@@ -371,13 +483,222 @@ declare class Stripe {
371
483
  }): Promise<TStripeWebhookEventResponse>;
372
484
  }
373
485
 
486
+ interface ICoinbaseOptions {
487
+ apiKey: string;
488
+ }
489
+ interface ICoinbaseChargePayload {
490
+ name: string;
491
+ description: string;
492
+ pricing_type: "fixed_price" | "no_price";
493
+ local_price: {
494
+ amount: string;
495
+ currency: string;
496
+ };
497
+ redirect_url?: string;
498
+ cancel_url?: string;
499
+ metadata?: Record<string, string>;
500
+ }
501
+
502
+ declare class Coinbase extends UnifyFetch {
503
+ private apiKey;
504
+ constructor(options: ICoinbaseOptions);
505
+ private getApiBaseUrl;
506
+ private getApiRequestHeaders;
507
+ createCharge(payload: ICoinbaseChargePayload): Promise<{
508
+ id: string;
509
+ code: string;
510
+ url: string;
511
+ }>;
512
+ verifySignature(payload: {
513
+ body: string;
514
+ signature: string;
515
+ secret: string;
516
+ }): Promise<{
517
+ type: string;
518
+ event: unknown;
519
+ } | {
520
+ error: Error;
521
+ }>;
522
+ }
523
+
524
+ type StripeConfig = {
525
+ provider: "stripe";
526
+ apiKey: string;
527
+ config?: Stripe$2.StripeConfig;
528
+ };
529
+ type PaypalConfig = {
530
+ provider: "paypal";
531
+ clientId: string;
532
+ clientSecret: string;
533
+ sandbox?: boolean;
534
+ };
535
+ type LemonSqueezyConfig = {
536
+ provider: "lemonsqueezy";
537
+ apiKey: string;
538
+ };
539
+ type BkashConfig = {
540
+ provider: "bkash";
541
+ apiUrl: string;
542
+ username: string;
543
+ password: string;
544
+ appKey: string;
545
+ appSecret: string;
546
+ };
547
+ type SSLCommerzConfig = {
548
+ provider: "sslcommerz";
549
+ apiUrl: string;
550
+ storeId: string;
551
+ storePassword: string;
552
+ };
553
+ type NagadConfig = {
554
+ provider: "nagad";
555
+ merchantId: string;
556
+ merchantNumber: string;
557
+ privateKey: string;
558
+ publicKey: string;
559
+ callbackUrl: string;
560
+ apiVersion: string;
561
+ isLive?: boolean;
562
+ };
563
+ type PolarConfig = {
564
+ provider: "polar";
565
+ accessToken: string;
566
+ sandbox?: boolean;
567
+ };
568
+ type RazorpayConfig = {
569
+ provider: "razorpay";
570
+ keyId: string;
571
+ keySecret: string;
572
+ };
573
+ type PaddleConfig = {
574
+ provider: "paddle";
575
+ apiKey: string;
576
+ sandbox?: boolean;
577
+ };
578
+ type CoinbaseConfig = {
579
+ provider: "coinbase";
580
+ apiKey: string;
581
+ };
582
+ type PaymentConfig = StripeConfig | PaypalConfig | LemonSqueezyConfig | BkashConfig | SSLCommerzConfig | NagadConfig | PolarConfig | RazorpayConfig | PaddleConfig | CoinbaseConfig;
583
+ interface CreateCheckoutSessionParams {
584
+ amount: number;
585
+ currency: string;
586
+ successUrl: string;
587
+ cancelUrl: string;
588
+ }
589
+ interface StripeCheckoutSessionParams extends CreateCheckoutSessionParams {
590
+ provider?: "stripe";
591
+ productName?: string;
592
+ metadata?: Record<string, string>;
593
+ overrides?: Partial<Stripe$2.Checkout.SessionCreateParams>;
594
+ }
595
+ interface PaypalCheckoutSessionParams extends CreateCheckoutSessionParams {
596
+ provider?: "paypal";
597
+ description?: string;
598
+ brandName?: string;
599
+ }
600
+ interface LemonSqueezyCheckoutSessionParams extends CreateCheckoutSessionParams {
601
+ provider?: "lemonsqueezy";
602
+ storeId: string;
603
+ variantId: string;
604
+ redirectUrl?: string;
605
+ }
606
+ interface BkashCheckoutSessionParams extends CreateCheckoutSessionParams {
607
+ provider?: "bkash";
608
+ payerReference: string;
609
+ merchantInvoiceNumber: string;
610
+ }
611
+ interface SSLCommerzCheckoutSessionParams extends CreateCheckoutSessionParams {
612
+ provider?: "sslcommerz";
613
+ transactionId: string;
614
+ customerName: string;
615
+ customerEmail: string;
616
+ customerAddress: string;
617
+ customerCity: string;
618
+ customerState: string;
619
+ customerPostcode: string;
620
+ customerCountry: string;
621
+ customerPhone: string;
622
+ productName: string;
623
+ productCategory: string;
624
+ productProfile?: "general" | "physical-goods" | "non-physical-goods" | "airline-tickets" | "travel-vertical" | "telecom-vertical";
625
+ shippingMethod?: "NO" | "YES";
626
+ }
627
+ interface NagadCheckoutSessionParams extends CreateCheckoutSessionParams {
628
+ provider?: "nagad";
629
+ orderId: string;
630
+ ip: string;
631
+ clientType?: "PC_WEB" | "MOBILE_WEB" | "MOBILE_APP" | "WALLET_WEB_VIEW" | "BILL_KEY";
632
+ productDetails?: Record<string, string>;
633
+ }
634
+ interface RazorpayCheckoutSessionParams extends CreateCheckoutSessionParams {
635
+ provider?: "razorpay";
636
+ description?: string;
637
+ customerName?: string;
638
+ customerEmail?: string;
639
+ customerContact?: string;
640
+ notes?: Record<string, string>;
641
+ }
642
+ interface PaddleCheckoutSessionParams extends CreateCheckoutSessionParams {
643
+ provider?: "paddle";
644
+ priceId: string;
645
+ quantity?: number;
646
+ customerId?: string;
647
+ customData?: Record<string, string>;
648
+ }
649
+ interface CoinbaseCheckoutSessionParams extends CreateCheckoutSessionParams {
650
+ provider?: "coinbase";
651
+ name?: string;
652
+ description?: string;
653
+ metadata?: Record<string, string>;
654
+ }
655
+ interface PolarCheckoutSessionParams extends CreateCheckoutSessionParams {
656
+ provider?: "polar";
657
+ productId: string;
658
+ quantity?: number;
659
+ customerEmail?: string;
660
+ customerName?: string;
661
+ customerExternalId?: string;
662
+ metadata?: Record<string, string>;
663
+ discountId?: string;
664
+ allowDiscountCodes?: boolean;
665
+ }
666
+ interface CheckoutSession {
667
+ url: string;
668
+ sessionId?: string;
669
+ raw?: unknown;
670
+ }
671
+ interface VerifyWebhookParams {
672
+ body: string;
673
+ signature: string;
674
+ secret: string;
675
+ webhookId?: string;
676
+ timestamp?: string;
677
+ }
678
+ interface WebhookEvent {
679
+ type: string;
680
+ data: unknown;
681
+ raw: unknown;
682
+ }
683
+ type CheckoutParamsForConfig<T extends PaymentConfig> = T extends StripeConfig ? StripeCheckoutSessionParams : T extends PaypalConfig ? PaypalCheckoutSessionParams : T extends LemonSqueezyConfig ? LemonSqueezyCheckoutSessionParams : T extends BkashConfig ? BkashCheckoutSessionParams : T extends SSLCommerzConfig ? SSLCommerzCheckoutSessionParams : T extends NagadConfig ? NagadCheckoutSessionParams : T extends PolarConfig ? PolarCheckoutSessionParams : T extends RazorpayConfig ? RazorpayCheckoutSessionParams : T extends PaddleConfig ? PaddleCheckoutSessionParams : T extends CoinbaseConfig ? CoinbaseCheckoutSessionParams : CreateCheckoutSessionParams;
684
+ interface PaymentInstance<T extends PaymentConfig = PaymentConfig> {
685
+ createCheckoutSession(params: CheckoutParamsForConfig<T>): Promise<CheckoutSession>;
686
+ verifyWebhook?(params: VerifyWebhookParams): Promise<WebhookEvent>;
687
+ }
688
+
689
+ declare function createPayment<T extends PaymentConfig>(config: T): PaymentInstance<T>;
690
+
374
691
  declare const UnifyPayment: {
375
692
  LemonSqueezy: typeof LemonSqueezy;
376
693
  Bkash: typeof Bkash;
377
694
  Paypal: typeof Paypal;
695
+ Polar: typeof Polar;
696
+ Razorpay: typeof Razorpay;
697
+ Paddle: typeof Paddle;
378
698
  SSLCommerz: typeof SSLCommerz;
379
699
  Stripe: typeof Stripe;
380
700
  Nagad: typeof Nagad;
701
+ Coinbase: typeof Coinbase;
381
702
  };
382
703
 
383
- export { UnifyPayment };
704
+ export { type BkashCheckoutSessionParams, type BkashConfig, type CheckoutSession, type CoinbaseCheckoutSessionParams, type CoinbaseConfig, type CreateCheckoutSessionParams, type LemonSqueezyCheckoutSessionParams, type LemonSqueezyConfig, type NagadCheckoutSessionParams, type NagadConfig, type PaddleCheckoutSessionParams, type PaddleConfig, type PaymentConfig, type PaymentInstance, type PaypalCheckoutSessionParams, type PaypalConfig, type PolarCheckoutSessionParams, type PolarConfig, type RazorpayCheckoutSessionParams, type RazorpayConfig, type SSLCommerzCheckoutSessionParams, type SSLCommerzConfig, type StripeCheckoutSessionParams, type StripeConfig, UnifyPayment, type VerifyWebhookParams, type WebhookEvent, createPayment };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { EventEntity } from '@paddle/paddle-node-sdk';
1
2
  import Stripe$1, { Stripe as Stripe$2 } from 'stripe';
2
3
 
3
4
  interface IBkashCheckoutOptions {
@@ -279,6 +280,117 @@ declare class Paypal extends UnifyFetch {
279
280
  getCheckoutUrl(payload: IPaypalPayload): Promise<string>;
280
281
  }
281
282
 
283
+ interface IPolarOptions {
284
+ accessToken: string;
285
+ sandbox?: boolean;
286
+ }
287
+ interface IPolarCheckoutCreatePayload {
288
+ products: Array<{
289
+ product_id: string;
290
+ quantity?: number;
291
+ }>;
292
+ customer_email?: string;
293
+ customer_name?: string;
294
+ customer_external_id?: string;
295
+ success_url?: string;
296
+ metadata?: Record<string, string>;
297
+ allow_discount_codes?: boolean;
298
+ discount_id?: string;
299
+ }
300
+
301
+ declare class Polar extends UnifyFetch {
302
+ private accessToken;
303
+ private sandbox;
304
+ constructor(options: IPolarOptions);
305
+ private getApiBaseUrl;
306
+ private getApiRequestHeaders;
307
+ getCheckoutUrl(payload: IPolarCheckoutCreatePayload): Promise<string>;
308
+ verifySignature(payload: {
309
+ body: string;
310
+ signature: string;
311
+ secret: string;
312
+ webhookId: string;
313
+ timestamp: string;
314
+ }): Promise<{
315
+ type: string;
316
+ event: unknown;
317
+ } | {
318
+ error: Error;
319
+ }>;
320
+ }
321
+
322
+ interface IRazorpayOptions {
323
+ keyId: string;
324
+ keySecret: string;
325
+ }
326
+ interface IRazorpayPaymentLinkPayload {
327
+ amount: number;
328
+ currency: string;
329
+ description?: string;
330
+ customer?: {
331
+ name?: string;
332
+ email?: string;
333
+ contact?: string;
334
+ };
335
+ notify?: {
336
+ sms?: boolean;
337
+ email?: boolean;
338
+ };
339
+ callback_url: string;
340
+ callback_method: "get";
341
+ notes?: Record<string, string>;
342
+ }
343
+
344
+ declare class Razorpay extends UnifyFetch {
345
+ private keyId;
346
+ private keySecret;
347
+ constructor(options: IRazorpayOptions);
348
+ private getApiBaseUrl;
349
+ private getApiRequestHeaders;
350
+ getCheckoutUrl(payload: IRazorpayPaymentLinkPayload): Promise<string>;
351
+ verifySignature(payload: {
352
+ body: string;
353
+ signature: string;
354
+ secret: string;
355
+ }): Promise<{
356
+ type: string;
357
+ event: unknown;
358
+ } | {
359
+ error: Error;
360
+ }>;
361
+ }
362
+
363
+ interface IPaddleOptions {
364
+ apiKey: string;
365
+ sandbox?: boolean;
366
+ }
367
+
368
+ declare class Paddle {
369
+ private sdk;
370
+ constructor(options: IPaddleOptions);
371
+ createTransaction(params: {
372
+ items: Array<{
373
+ priceId: string;
374
+ quantity: number;
375
+ }>;
376
+ customerId?: string;
377
+ customData?: Record<string, string>;
378
+ }): Promise<{
379
+ id: string;
380
+ url: string;
381
+ }>;
382
+ verifySignature(payload: {
383
+ body: string;
384
+ secret: string;
385
+ signature: string;
386
+ }): Promise<{
387
+ type: string;
388
+ event: EventEntity;
389
+ } | {
390
+ error: Error;
391
+ }>;
392
+ }
393
+
282
394
  type ISSLCommerzCreateCheckoutPayload = {
283
395
  tran_id: string;
284
396
  store_id: string;
@@ -371,13 +483,222 @@ declare class Stripe {
371
483
  }): Promise<TStripeWebhookEventResponse>;
372
484
  }
373
485
 
486
+ interface ICoinbaseOptions {
487
+ apiKey: string;
488
+ }
489
+ interface ICoinbaseChargePayload {
490
+ name: string;
491
+ description: string;
492
+ pricing_type: "fixed_price" | "no_price";
493
+ local_price: {
494
+ amount: string;
495
+ currency: string;
496
+ };
497
+ redirect_url?: string;
498
+ cancel_url?: string;
499
+ metadata?: Record<string, string>;
500
+ }
501
+
502
+ declare class Coinbase extends UnifyFetch {
503
+ private apiKey;
504
+ constructor(options: ICoinbaseOptions);
505
+ private getApiBaseUrl;
506
+ private getApiRequestHeaders;
507
+ createCharge(payload: ICoinbaseChargePayload): Promise<{
508
+ id: string;
509
+ code: string;
510
+ url: string;
511
+ }>;
512
+ verifySignature(payload: {
513
+ body: string;
514
+ signature: string;
515
+ secret: string;
516
+ }): Promise<{
517
+ type: string;
518
+ event: unknown;
519
+ } | {
520
+ error: Error;
521
+ }>;
522
+ }
523
+
524
+ type StripeConfig = {
525
+ provider: "stripe";
526
+ apiKey: string;
527
+ config?: Stripe$2.StripeConfig;
528
+ };
529
+ type PaypalConfig = {
530
+ provider: "paypal";
531
+ clientId: string;
532
+ clientSecret: string;
533
+ sandbox?: boolean;
534
+ };
535
+ type LemonSqueezyConfig = {
536
+ provider: "lemonsqueezy";
537
+ apiKey: string;
538
+ };
539
+ type BkashConfig = {
540
+ provider: "bkash";
541
+ apiUrl: string;
542
+ username: string;
543
+ password: string;
544
+ appKey: string;
545
+ appSecret: string;
546
+ };
547
+ type SSLCommerzConfig = {
548
+ provider: "sslcommerz";
549
+ apiUrl: string;
550
+ storeId: string;
551
+ storePassword: string;
552
+ };
553
+ type NagadConfig = {
554
+ provider: "nagad";
555
+ merchantId: string;
556
+ merchantNumber: string;
557
+ privateKey: string;
558
+ publicKey: string;
559
+ callbackUrl: string;
560
+ apiVersion: string;
561
+ isLive?: boolean;
562
+ };
563
+ type PolarConfig = {
564
+ provider: "polar";
565
+ accessToken: string;
566
+ sandbox?: boolean;
567
+ };
568
+ type RazorpayConfig = {
569
+ provider: "razorpay";
570
+ keyId: string;
571
+ keySecret: string;
572
+ };
573
+ type PaddleConfig = {
574
+ provider: "paddle";
575
+ apiKey: string;
576
+ sandbox?: boolean;
577
+ };
578
+ type CoinbaseConfig = {
579
+ provider: "coinbase";
580
+ apiKey: string;
581
+ };
582
+ type PaymentConfig = StripeConfig | PaypalConfig | LemonSqueezyConfig | BkashConfig | SSLCommerzConfig | NagadConfig | PolarConfig | RazorpayConfig | PaddleConfig | CoinbaseConfig;
583
+ interface CreateCheckoutSessionParams {
584
+ amount: number;
585
+ currency: string;
586
+ successUrl: string;
587
+ cancelUrl: string;
588
+ }
589
+ interface StripeCheckoutSessionParams extends CreateCheckoutSessionParams {
590
+ provider?: "stripe";
591
+ productName?: string;
592
+ metadata?: Record<string, string>;
593
+ overrides?: Partial<Stripe$2.Checkout.SessionCreateParams>;
594
+ }
595
+ interface PaypalCheckoutSessionParams extends CreateCheckoutSessionParams {
596
+ provider?: "paypal";
597
+ description?: string;
598
+ brandName?: string;
599
+ }
600
+ interface LemonSqueezyCheckoutSessionParams extends CreateCheckoutSessionParams {
601
+ provider?: "lemonsqueezy";
602
+ storeId: string;
603
+ variantId: string;
604
+ redirectUrl?: string;
605
+ }
606
+ interface BkashCheckoutSessionParams extends CreateCheckoutSessionParams {
607
+ provider?: "bkash";
608
+ payerReference: string;
609
+ merchantInvoiceNumber: string;
610
+ }
611
+ interface SSLCommerzCheckoutSessionParams extends CreateCheckoutSessionParams {
612
+ provider?: "sslcommerz";
613
+ transactionId: string;
614
+ customerName: string;
615
+ customerEmail: string;
616
+ customerAddress: string;
617
+ customerCity: string;
618
+ customerState: string;
619
+ customerPostcode: string;
620
+ customerCountry: string;
621
+ customerPhone: string;
622
+ productName: string;
623
+ productCategory: string;
624
+ productProfile?: "general" | "physical-goods" | "non-physical-goods" | "airline-tickets" | "travel-vertical" | "telecom-vertical";
625
+ shippingMethod?: "NO" | "YES";
626
+ }
627
+ interface NagadCheckoutSessionParams extends CreateCheckoutSessionParams {
628
+ provider?: "nagad";
629
+ orderId: string;
630
+ ip: string;
631
+ clientType?: "PC_WEB" | "MOBILE_WEB" | "MOBILE_APP" | "WALLET_WEB_VIEW" | "BILL_KEY";
632
+ productDetails?: Record<string, string>;
633
+ }
634
+ interface RazorpayCheckoutSessionParams extends CreateCheckoutSessionParams {
635
+ provider?: "razorpay";
636
+ description?: string;
637
+ customerName?: string;
638
+ customerEmail?: string;
639
+ customerContact?: string;
640
+ notes?: Record<string, string>;
641
+ }
642
+ interface PaddleCheckoutSessionParams extends CreateCheckoutSessionParams {
643
+ provider?: "paddle";
644
+ priceId: string;
645
+ quantity?: number;
646
+ customerId?: string;
647
+ customData?: Record<string, string>;
648
+ }
649
+ interface CoinbaseCheckoutSessionParams extends CreateCheckoutSessionParams {
650
+ provider?: "coinbase";
651
+ name?: string;
652
+ description?: string;
653
+ metadata?: Record<string, string>;
654
+ }
655
+ interface PolarCheckoutSessionParams extends CreateCheckoutSessionParams {
656
+ provider?: "polar";
657
+ productId: string;
658
+ quantity?: number;
659
+ customerEmail?: string;
660
+ customerName?: string;
661
+ customerExternalId?: string;
662
+ metadata?: Record<string, string>;
663
+ discountId?: string;
664
+ allowDiscountCodes?: boolean;
665
+ }
666
+ interface CheckoutSession {
667
+ url: string;
668
+ sessionId?: string;
669
+ raw?: unknown;
670
+ }
671
+ interface VerifyWebhookParams {
672
+ body: string;
673
+ signature: string;
674
+ secret: string;
675
+ webhookId?: string;
676
+ timestamp?: string;
677
+ }
678
+ interface WebhookEvent {
679
+ type: string;
680
+ data: unknown;
681
+ raw: unknown;
682
+ }
683
+ type CheckoutParamsForConfig<T extends PaymentConfig> = T extends StripeConfig ? StripeCheckoutSessionParams : T extends PaypalConfig ? PaypalCheckoutSessionParams : T extends LemonSqueezyConfig ? LemonSqueezyCheckoutSessionParams : T extends BkashConfig ? BkashCheckoutSessionParams : T extends SSLCommerzConfig ? SSLCommerzCheckoutSessionParams : T extends NagadConfig ? NagadCheckoutSessionParams : T extends PolarConfig ? PolarCheckoutSessionParams : T extends RazorpayConfig ? RazorpayCheckoutSessionParams : T extends PaddleConfig ? PaddleCheckoutSessionParams : T extends CoinbaseConfig ? CoinbaseCheckoutSessionParams : CreateCheckoutSessionParams;
684
+ interface PaymentInstance<T extends PaymentConfig = PaymentConfig> {
685
+ createCheckoutSession(params: CheckoutParamsForConfig<T>): Promise<CheckoutSession>;
686
+ verifyWebhook?(params: VerifyWebhookParams): Promise<WebhookEvent>;
687
+ }
688
+
689
+ declare function createPayment<T extends PaymentConfig>(config: T): PaymentInstance<T>;
690
+
374
691
  declare const UnifyPayment: {
375
692
  LemonSqueezy: typeof LemonSqueezy;
376
693
  Bkash: typeof Bkash;
377
694
  Paypal: typeof Paypal;
695
+ Polar: typeof Polar;
696
+ Razorpay: typeof Razorpay;
697
+ Paddle: typeof Paddle;
378
698
  SSLCommerz: typeof SSLCommerz;
379
699
  Stripe: typeof Stripe;
380
700
  Nagad: typeof Nagad;
701
+ Coinbase: typeof Coinbase;
381
702
  };
382
703
 
383
- export { UnifyPayment };
704
+ export { type BkashCheckoutSessionParams, type BkashConfig, type CheckoutSession, type CoinbaseCheckoutSessionParams, type CoinbaseConfig, type CreateCheckoutSessionParams, type LemonSqueezyCheckoutSessionParams, type LemonSqueezyConfig, type NagadCheckoutSessionParams, type NagadConfig, type PaddleCheckoutSessionParams, type PaddleConfig, type PaymentConfig, type PaymentInstance, type PaypalCheckoutSessionParams, type PaypalConfig, type PolarCheckoutSessionParams, type PolarConfig, type RazorpayCheckoutSessionParams, type RazorpayConfig, type SSLCommerzCheckoutSessionParams, type SSLCommerzConfig, type StripeCheckoutSessionParams, type StripeConfig, UnifyPayment, type VerifyWebhookParams, type WebhookEvent, createPayment };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var K=Object.create;var m=Object.defineProperty,x=Object.defineProperties,D=Object.getOwnPropertyDescriptor,$=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertyNames,P=Object.getOwnPropertySymbols,z=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty,M=Object.prototype.propertyIsEnumerable;var U=(s,t,e)=>t in s?m(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,y=(s,t)=>{for(var e in t||(t={}))R.call(t,e)&&U(s,e,t[e]);if(P)for(var e of P(t))M.call(t,e)&&U(s,e,t[e]);return s},T=(s,t)=>x(s,$(t));var F=(s,t)=>{for(var e in t)m(s,e,{get:t[e],enumerable:!0})},w=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of j(t))!R.call(s,a)&&a!==e&&m(s,a,{get:()=>t[a],enumerable:!(r=D(t,a))||r.enumerable});return s};var u=(s,t,e)=>(e=s!=null?K(z(s)):{},w(t||!s||!s.__esModule?m(e,"default",{value:s,enumerable:!0}):e,s)),H=s=>w(m({},"__esModule",{value:!0}),s);var i=(s,t,e)=>new Promise((r,a)=>{var n=p=>{try{c(e.next(p))}catch(l){a(l)}},h=p=>{try{c(e.throw(p))}catch(l){a(l)}},c=p=>p.done?r(p.value):Promise.resolve(p.value).then(n,h);c((e=e.apply(s,t)).next())});var L={};F(L,{UnifyPayment:()=>_});module.exports=H(L);var b=u(require("axios"));var o=class{jsonFetch(t,e){return i(this,null,function*(){let r=yield fetch(t,e);return[yield r.json(),r]})}axios(t,e){return i(this,null,function*(){let r=yield(0,b.default)({url:t,method:e==null?void 0:e.method,headers:e==null?void 0:e.headers,data:e==null?void 0:e.body});return[r.data,r.request]})}};var I=class extends o{constructor(e){super();this.options=e}getAppKey(){return this.options.app_key}getApiBaseUrl(){return this.options.apiUrl}getApiRequestHeaders(){return{"Content-Type":"application/json",Accept:"application/json",username:this.options.username,password:this.options.password}}getAccessToken(){return i(this,null,function*(){let[e]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/token/grant`,{method:"POST",headers:this.getApiRequestHeaders(),body:JSON.stringify({app_key:this.options.app_key,app_secret:this.options.app_secret})});if("errorMessage"in e)throw new Error(e.errorMessage);return e.id_token})}getCheckoutUrl(e){return i(this,null,function*(){let r=yield this.getAccessToken(),[a]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/create`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-App-Key":this.getAppKey(),Authorization:`Bearer ${r}`},body:JSON.stringify(e)});if("errorMessage"in a)throw new Error(a.errorMessage);return a.bkashURL})}};var v=class extends o{constructor(e){super();this.apiKey=e}getApiBaseUrl(){return"https://api.lemonsqueezy.com/v1"}getApiRequestHeaders(){return{Accept:"application/vnd.api+json","Content-Type":"application/vnd.api+json",Authorization:`Bearer ${this.apiKey}`}}getCheckoutUrl(e){return i(this,null,function*(){let[r]=yield this.jsonFetch(`${this.getApiBaseUrl()}/checkouts`,{method:"POST",body:JSON.stringify({data:e}),headers:this.getApiRequestHeaders()});if("errors"in r)throw new Error(r.errors[0].detail);return r.data.attributes.url})}verifySignature(e){return i(this,null,function*(){try{let r=new TextEncoder,a=yield crypto.subtle.importKey("raw",r.encode(e.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=yield crypto.subtle.sign("HMAC",a,r.encode(e.body));if(Array.from(new Uint8Array(n)).map(c=>c.toString(16).padStart(2,"0")).join("")!==e.signature)throw new Error("Invalid signature");return{event:JSON.parse(e.body),type:e.x_event}}catch(r){return{error:r}}})}};var A=u(require("dayjs")),B=u(require("dayjs/plugin/timezone")),E=u(require("dayjs/plugin/utc"));var g=u(require("crypto")),N=u(require("node-rsa"));var k=class extends o{constructor(e){super();this.options=e;A.default.extend(B.default),A.default.extend(E.default)}getApiBaseUrl(){return this.options.is_live?"https://api.mynagad.com/api/dfs":"http://sandbox.mynagad.com:10080/remote-payment-gateway-1.0/api/dfs"}getMerchantId(){return this.options.merchant_id}getMerchantNumber(){return this.options.merchant_number}getPrivateKey(){return this.options.private_key}getPublicKey(){return this.options.public_key}getTimeStamp(){return(0,A.default)().tz("Asia/Dhaka").format("YYYYMMDDHHmmss")}getCallbackUrl(){return this.options.callbackURL}getApiHeaders(){return{Accept:"application/json","Content-Type":"application/json","X-KM-Api-Version":this.options.apiVersion}}createHash(e){return g.default.createHash("sha1").update(e).digest("hex").toUpperCase()}encrypt(e){let r=`-----BEGIN PUBLIC KEY-----
1
+ "use strict";var F=Object.create;var A=Object.defineProperty,j=Object.defineProperties,W=Object.getOwnPropertyDescriptor,M=Object.getOwnPropertyDescriptors,V=Object.getOwnPropertyNames,x=Object.getOwnPropertySymbols,J=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable;var B=(s,r,t)=>r in s?A(s,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[r]=t,y=(s,r)=>{for(var t in r||(r={}))N.call(r,t)&&B(s,t,r[t]);if(x)for(var t of x(r))Y.call(r,t)&&B(s,t,r[t]);return s},R=(s,r)=>j(s,M(r));var G=(s,r)=>{for(var t in r)A(s,t,{get:r[t],enumerable:!0})},z=(s,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of V(r))!N.call(s,n)&&n!==t&&A(s,n,{get:()=>r[n],enumerable:!(e=W(r,n))||e.enumerable});return s};var m=(s,r,t)=>(t=s!=null?F(J(s)):{},z(r||!s||!s.__esModule?A(t,"default",{value:s,enumerable:!0}):t,s)),X=s=>z(A({},"__esModule",{value:!0}),s);var o=(s,r,t)=>new Promise((e,n)=>{var a=u=>{try{p(t.next(u))}catch(h){n(h)}},i=u=>{try{p(t.throw(u))}catch(h){n(h)}},p=u=>u.done?e(u.value):Promise.resolve(u.value).then(a,i);p((t=t.apply(s,r)).next())});var ue={};G(ue,{UnifyPayment:()=>ce,createPayment:()=>H});module.exports=X(ue);var O=m(require("axios"));var c=class{jsonFetch(r,t){return o(this,null,function*(){let e=yield fetch(r,t);return[yield e.json(),e]})}axios(r,t){return o(this,null,function*(){let e=yield(0,O.default)({url:r,method:t==null?void 0:t.method,headers:t==null?void 0:t.headers,data:t==null?void 0:t.body});return[e.data,e.request]})}};var l=class extends c{constructor(t){super();this.options=t}getAppKey(){return this.options.app_key}getApiBaseUrl(){return this.options.apiUrl}getApiRequestHeaders(){return{"Content-Type":"application/json",Accept:"application/json",username:this.options.username,password:this.options.password}}getAccessToken(){return o(this,null,function*(){let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/token/grant`,{method:"POST",headers:this.getApiRequestHeaders(),body:JSON.stringify({app_key:this.options.app_key,app_secret:this.options.app_secret})});if("errorMessage"in t)throw new Error(t.errorMessage);return t.id_token})}getCheckoutUrl(t){return o(this,null,function*(){let e=yield this.getAccessToken(),[n]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/create`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-App-Key":this.getAppKey(),Authorization:`Bearer ${e}`},body:JSON.stringify(t)});if("errorMessage"in n)throw new Error(n.errorMessage);return n.bkashURL})}};var g=class extends c{constructor(t){super();this.apiKey=t}getApiBaseUrl(){return"https://api.lemonsqueezy.com/v1"}getApiRequestHeaders(){return{Accept:"application/vnd.api+json","Content-Type":"application/vnd.api+json",Authorization:`Bearer ${this.apiKey}`}}getCheckoutUrl(t){return o(this,null,function*(){let[e]=yield this.jsonFetch(`${this.getApiBaseUrl()}/checkouts`,{method:"POST",body:JSON.stringify({data:t}),headers:this.getApiRequestHeaders()});if("errors"in e)throw new Error(e.errors[0].detail);return e.data.attributes.url})}verifySignature(t){return o(this,null,function*(){try{let e=new TextEncoder,n=yield crypto.subtle.importKey("raw",e.encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=yield crypto.subtle.sign("HMAC",n,e.encode(t.body));if(Array.from(new Uint8Array(a)).map(p=>p.toString(16).padStart(2,"0")).join("")!==t.signature)throw new Error("Invalid signature");return{event:JSON.parse(t.body),type:t.x_event}}catch(e){return{error:e}}})}};var _=m(require("dayjs")),K=m(require("dayjs/plugin/timezone")),D=m(require("dayjs/plugin/utc"));var U=m(require("crypto")),L=m(require("node-rsa"));var C=class extends c{constructor(t){super();this.options=t;_.default.extend(K.default),_.default.extend(D.default)}getApiBaseUrl(){return this.options.is_live?"https://api.mynagad.com/api/dfs":"http://sandbox.mynagad.com:10080/remote-payment-gateway-1.0/api/dfs"}getMerchantId(){return this.options.merchant_id}getMerchantNumber(){return this.options.merchant_number}getPrivateKey(){return this.options.private_key}getPublicKey(){return this.options.public_key}getTimeStamp(){return(0,_.default)().tz("Asia/Dhaka").format("YYYYMMDDHHmmss")}getCallbackUrl(){return this.options.callbackURL}getApiHeaders(){return{Accept:"application/json","Content-Type":"application/json","X-KM-Api-Version":this.options.apiVersion}}createHash(t){return U.default.createHash("sha1").update(t).digest("hex").toUpperCase()}encrypt(t){let e=`-----BEGIN PUBLIC KEY-----
2
2
  ${this.getPublicKey()}
3
- -----END PUBLIC KEY-----`;return g.default.publicEncrypt({key:r,padding:g.default.constants.RSA_PKCS1_PADDING},Buffer.from(JSON.stringify(e),"utf8")).toString("base64")}decrypt(e){let r=`-----BEGIN PRIVATE KEY-----
3
+ -----END PUBLIC KEY-----`;return U.default.publicEncrypt({key:e,padding:U.default.constants.RSA_PKCS1_PADDING},Buffer.from(JSON.stringify(t),"utf8")).toString("base64")}decrypt(t){let e=`-----BEGIN PRIVATE KEY-----
4
4
  ${this.getPrivateKey()}
5
- -----END PRIVATE KEY-----`,a=new N.default(r,"pkcs8",{encryptionScheme:"pkcs1"});a.setOptions({environment:"browser"});let n=a.decrypt(e).toString("utf8");return JSON.parse(n)}sign(e){let r=`-----BEGIN PRIVATE KEY-----
5
+ -----END PRIVATE KEY-----`,n=new L.default(e,"pkcs8",{encryptionScheme:"pkcs1"});n.setOptions({environment:"browser"});let a=n.decrypt(t).toString("utf8");return JSON.parse(a)}sign(t){let e=`-----BEGIN PRIVATE KEY-----
6
6
  ${this.getPrivateKey()}
7
- -----END PRIVATE KEY-----`,a=g.default.createSign("SHA256");return a.update(JSON.stringify(e)),a.end(),a.sign(r,"base64")}confirmPayment(e){return i(this,null,function*(){let r={currencyCode:"050",amount:e.amount,orderId:e.orderId,challenge:e.challenge,merchantId:this.getMerchantId()},a={signature:this.sign(r),paymentRefId:e.paymentReferenceId,sensitiveData:this.encrypt(r),merchantCallbackURL:this.getCallbackUrl(),additionalMerchantInfo:y({},e.productDetails)},[n]=yield this.axios(`${this.getApiBaseUrl()}/check-out/complete/${e.paymentReferenceId}`,{method:"POST",headers:T(y({},this.getApiHeaders()),{"X-KM-IP-V4":e.ip,"X-KM-Client-Type":e.clientType}),body:JSON.stringify(a)});return n})}getCheckoutUrl(e){return i(this,null,function*(){let r=this.getTimeStamp(),a=`${this.getApiBaseUrl()}/check-out/initialize/${this.getMerchantId()}/${e.orderId}`,n={datetime:r,orderId:e.orderId,merchantId:this.getMerchantId(),challenge:this.createHash(e.orderId)},h={dateTime:r,signature:this.sign(n),sensitiveData:this.encrypt(n),accountNumber:this.getMerchantNumber()},[c]=yield this.axios(a,{method:"POST",headers:T(y({},this.getApiHeaders()),{"X-KM-IP-V4":e.ip,"X-KM-Client-Type":e.clientType}),body:JSON.stringify(h)}),p=this.decrypt(c.sensitiveData);return(yield this.confirmPayment({ip:e.ip,challenge:p.challenge,amount:e.amount,orderId:e.orderId,clientType:e.clientType,paymentReferenceId:p.paymentReferenceId,productDetails:e.productDetails})).callBackUrl})}};var f=class extends o{constructor(e){super();this.options=e}getApiBaseUrl(){return this.options.sandbox?"https://api-m.sandbox.paypal.com":"https://api.paypal.com"}getClientId(){return this.options.clientId}getClientSecret(){return this.options.clientSecret}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/v2/checkout/orders`}getAccessToken(){return i(this,null,function*(){let e=`${this.getApiBaseUrl()}/v1/oauth2/token`,r=btoa(`${this.getClientId()}:${this.getClientSecret()}`),[a]=yield this.jsonFetch(e,{method:"POST",headers:{Authorization:`Basic ${r}`,"Content-Type":"application/x-www-form-urlencoded"},body:"grant_type=client_credentials"});return a.access_token})}getCheckoutUrl(e){return i(this,null,function*(){var h;let r=yield this.getAccessToken(),[a]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}}),n=(h=a.links.find(c=>c.rel==="approve"))==null?void 0:h.href;if(!n)throw new Error("Failed to get checkout url");return n})}};var S=class extends o{constructor(e){super();this.options=e}getApiBaseUrl(){return this.options.apiUrl}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/gwprocess/v4/api.php`}getApiValidationUrl(){return`${this.getApiBaseUrl()}/validator/api/validationserverAPI.php`}getApiRefundUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiRefundQueryUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryBySessionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryByTransactionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiHeaders(){return{"Content-Type":"application/x-www-form-urlencoded"}}urlFormEncode(e){return Object.entries(e).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}getCheckoutUrl(e){return i(this,null,function*(){let[r]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:this.urlFormEncode(e),headers:this.getApiHeaders()});if(r.status==="FAILED")throw new Error(r.failedreason);return r.redirectGatewayURL})}};var O=require("stripe");var C=class{constructor(t,e){this.apiKey=t;this.stripe=new O.Stripe(t,e)}getCheckoutUrl(t){return i(this,null,function*(){let e=yield this.stripe.checkout.sessions.create(t);if(!e.url)throw new Error("Failed to get checkout url");return e.url})}verifySignature(t){return i(this,null,function*(){try{return{event:yield this.stripe.webhooks.constructEventAsync(t.body,t.signature,t.secret)}}catch(e){return{error:e}}})}};var _={LemonSqueezy:v,Bkash:I,Paypal:f,SSLCommerz:S,Stripe:C,Nagad:k};0&&(module.exports={UnifyPayment});
7
+ -----END PRIVATE KEY-----`,n=U.default.createSign("SHA256");return n.update(JSON.stringify(t)),n.end(),n.sign(e,"base64")}confirmPayment(t){return o(this,null,function*(){let e={currencyCode:"050",amount:t.amount,orderId:t.orderId,challenge:t.challenge,merchantId:this.getMerchantId()},n={signature:this.sign(e),paymentRefId:t.paymentReferenceId,sensitiveData:this.encrypt(e),merchantCallbackURL:this.getCallbackUrl(),additionalMerchantInfo:y({},t.productDetails)},[a]=yield this.axios(`${this.getApiBaseUrl()}/check-out/complete/${t.paymentReferenceId}`,{method:"POST",headers:R(y({},this.getApiHeaders()),{"X-KM-IP-V4":t.ip,"X-KM-Client-Type":t.clientType}),body:JSON.stringify(n)});return a})}getCheckoutUrl(t){return o(this,null,function*(){let e=this.getTimeStamp(),n=`${this.getApiBaseUrl()}/check-out/initialize/${this.getMerchantId()}/${t.orderId}`,a={datetime:e,orderId:t.orderId,merchantId:this.getMerchantId(),challenge:this.createHash(t.orderId)},i={dateTime:e,signature:this.sign(a),sensitiveData:this.encrypt(a),accountNumber:this.getMerchantNumber()},[p]=yield this.axios(n,{method:"POST",headers:R(y({},this.getApiHeaders()),{"X-KM-IP-V4":t.ip,"X-KM-Client-Type":t.clientType}),body:JSON.stringify(i)}),u=this.decrypt(p.sensitiveData);return(yield this.confirmPayment({ip:t.ip,challenge:u.challenge,amount:t.amount,orderId:t.orderId,clientType:t.clientType,paymentReferenceId:u.paymentReferenceId,productDetails:t.productDetails})).callBackUrl})}};var k=class extends c{constructor(t){super();this.options=t}getApiBaseUrl(){return this.options.sandbox?"https://api-m.sandbox.paypal.com":"https://api.paypal.com"}getClientId(){return this.options.clientId}getClientSecret(){return this.options.clientSecret}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/v2/checkout/orders`}getAccessToken(){return o(this,null,function*(){let t=`${this.getApiBaseUrl()}/v1/oauth2/token`,e=btoa(`${this.getClientId()}:${this.getClientSecret()}`),[n]=yield this.jsonFetch(t,{method:"POST",headers:{Authorization:`Basic ${e}`,"Content-Type":"application/x-www-form-urlencoded"},body:"grant_type=client_credentials"});return n.access_token})}getCheckoutUrl(t){return o(this,null,function*(){var i;let e=yield this.getAccessToken(),[n]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}}),a=(i=n.links.find(p=>p.rel==="approve"))==null?void 0:i.href;if(!a)throw new Error("Failed to get checkout url");return a})}};var P=class extends c{constructor(r){var t;super(),this.accessToken=r.accessToken,this.sandbox=(t=r.sandbox)!=null?t:!1}getApiBaseUrl(){return this.sandbox?"https://sandbox-api.polar.sh/v1":"https://api.polar.sh/v1"}getApiRequestHeaders(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`}}getCheckoutUrl(r){return o(this,null,function*(){let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/checkouts/`,{method:"POST",body:JSON.stringify(r),headers:this.getApiRequestHeaders()});if(!t.url)throw new Error("Failed to create Polar checkout session");return t.url})}verifySignature(r){return o(this,null,function*(){try{let t=`${r.webhookId}.${r.timestamp}.${r.body}`,e=new TextEncoder,n=r.secret.startsWith("whsec_")?r.secret.slice(6):r.secret,a=Uint8Array.from(atob(n),w=>w.charCodeAt(0)),i=yield crypto.subtle.importKey("raw",a,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),p=yield crypto.subtle.sign("HMAC",i,e.encode(t)),u=btoa(String.fromCharCode(...new Uint8Array(p)));if(!r.signature.split(" ").some(w=>(w.startsWith("v1,")?w.slice(3):w)===u))throw new Error("Invalid webhook signature");let E=JSON.parse(r.body);return{type:E.type,event:E.data}}catch(t){return{error:t}}})}};var S=class extends c{constructor(r){super(),this.keyId=r.keyId,this.keySecret=r.keySecret}getApiBaseUrl(){return"https://api.razorpay.com/v1"}getApiRequestHeaders(){return{"Content-Type":"application/json",Authorization:`Basic ${btoa(`${this.keyId}:${this.keySecret}`)}`}}getCheckoutUrl(r){return o(this,null,function*(){let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/payment_links`,{method:"POST",body:JSON.stringify(r),headers:this.getApiRequestHeaders()});if(!t.short_url)throw new Error("Failed to create Razorpay payment link");return t.short_url})}verifySignature(r){return o(this,null,function*(){try{let t=new TextEncoder,e=yield crypto.subtle.importKey("raw",t.encode(r.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=yield crypto.subtle.sign("HMAC",e,t.encode(r.body));if(Array.from(new Uint8Array(n)).map(p=>p.toString(16).padStart(2,"0")).join("")!==r.signature)throw new Error("Invalid webhook signature");let i=JSON.parse(r.body);return{type:i.event,event:i.payload}}catch(t){return{error:t}}})}};var T=require("@paddle/paddle-node-sdk");var f=class{constructor(r){this.sdk=new T.Paddle(r.apiKey,{environment:r.sandbox?T.Environment.sandbox:T.Environment.production})}createTransaction(r){return o(this,null,function*(){var n;let t=yield this.sdk.transactions.create(y(y({items:r.items.map(a=>({priceId:a.priceId,quantity:a.quantity}))},r.customerId&&{customerId:r.customerId}),r.customData&&{customData:r.customData})),e=(n=t.checkout)==null?void 0:n.url;if(!e)throw new Error("Failed to create Paddle checkout session");return{id:t.id,url:e}})}verifySignature(r){return o(this,null,function*(){try{let t=this.sdk.webhooks.unmarshal(r.body,r.secret,r.signature);if(!t)throw new Error("Invalid webhook signature");return{type:t.eventType,event:t}}catch(t){return{error:t}}})}};var I=class extends c{constructor(t){super();this.options=t}getApiBaseUrl(){return this.options.apiUrl}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/gwprocess/v4/api.php`}getApiValidationUrl(){return`${this.getApiBaseUrl()}/validator/api/validationserverAPI.php`}getApiRefundUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiRefundQueryUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryBySessionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryByTransactionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiHeaders(){return{"Content-Type":"application/x-www-form-urlencoded"}}urlFormEncode(t){return Object.entries(t).map(([e,n])=>`${encodeURIComponent(e)}=${encodeURIComponent(n)}`).join("&")}getCheckoutUrl(t){return o(this,null,function*(){let[e]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:this.urlFormEncode(t),headers:this.getApiHeaders()});if(e.status==="FAILED")throw new Error(e.failedreason);return e.redirectGatewayURL})}};var $=require("stripe");var v=class{constructor(r,t){this.apiKey=r;this.stripe=new $.Stripe(r,t)}getCheckoutUrl(r){return o(this,null,function*(){let t=yield this.stripe.checkout.sessions.create(r);if(!t.url)throw new Error("Failed to get checkout url");return t.url})}verifySignature(r){return o(this,null,function*(){try{return{event:yield this.stripe.webhooks.constructEventAsync(r.body,r.signature,r.secret)}}catch(t){return{error:t}}})}};var b=class extends c{constructor(r){super(),this.apiKey=r.apiKey}getApiBaseUrl(){return"https://api.commerce.coinbase.com"}getApiRequestHeaders(){return{"Content-Type":"application/json","X-CC-Api-Key":this.apiKey,"X-CC-Version":"2018-03-22"}}createCharge(r){return o(this,null,function*(){var e;let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/charges`,{method:"POST",body:JSON.stringify(r),headers:this.getApiRequestHeaders()});if(!((e=t.data)!=null&&e.hosted_url))throw new Error("Failed to create Coinbase Commerce charge");return{id:t.data.id,code:t.data.code,url:t.data.hosted_url}})}verifySignature(r){return o(this,null,function*(){var t,e;try{let n=new TextEncoder,a=yield crypto.subtle.importKey("raw",n.encode(r.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=yield crypto.subtle.sign("HMAC",a,n.encode(r.body));if(Array.from(new Uint8Array(i)).map(h=>h.toString(16).padStart(2,"0")).join("")!==r.signature)throw new Error("Invalid webhook signature");let u=JSON.parse(r.body);return{type:(t=u.event)==null?void 0:t.type,event:(e=u.event)==null?void 0:e.data}}catch(n){return{error:n}}})}};var q=require("stripe");function Q(s){let r=new v(s.apiKey,s.config),t=new q.Stripe(s.apiKey,s.config);return{createCheckoutSession(n){return o(this,null,function*(){let a=y({mode:"payment",line_items:[{price_data:{currency:n.currency,unit_amount:n.amount,product_data:{name:n.productName||"Payment"}},quantity:1}],success_url:n.successUrl,cancel_url:n.cancelUrl,metadata:n.metadata},n.overrides),i=yield t.checkout.sessions.create(a);if(!i.url)throw new Error("Failed to create checkout session");return{url:i.url,sessionId:i.id,raw:i}})},verifyWebhook(n){return o(this,null,function*(){let a=yield r.verifySignature({body:n.body,signature:n.signature,secret:n.secret});if("error"in a)throw a.error;return{type:a.event.type,data:a.event.data.object,raw:a.event}})}}}function Z(s){let r=new k({clientId:s.clientId,clientSecret:s.clientSecret,sandbox:s.sandbox});return{createCheckoutSession(e){return o(this,null,function*(){let n=(e.amount/100).toFixed(2),a=e.currency.toUpperCase();return{url:yield r.getCheckoutUrl({intent:"CAPTURE",purchase_units:[{items:[{name:e.description||"Payment",description:e.description||"Payment",quantity:1,unit_amount:{currency_code:a,value:n}}],amount:{currency_code:a,value:n,breakdown:{item_total:{currency_code:a,value:n}}}}],application_context:{return_url:e.successUrl,cancel_url:e.cancelUrl,shipping_preference:"NO_SHIPPING",user_action:"PAY_NOW",brand_name:e.brandName}})}})}}}function ee(s){let r=new g(s.apiKey);return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({type:"checkouts",attributes:{custom_price:e.amount,product_options:{redirect_url:e.redirectUrl||e.successUrl}},relationships:{store:{data:{type:"stores",id:e.storeId}},variant:{data:{type:"variants",id:e.variantId}}}})}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret,x_event:""});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function te(s){let r=new l({apiUrl:s.apiUrl,username:s.username,password:s.password,app_key:s.appKey,app_secret:s.appSecret});return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({mode:"0011",payerReference:e.payerReference,callbackURL:e.successUrl,amount:String(e.amount),currency:"BDT",intent:"sale",merchantInvoiceNumber:e.merchantInvoiceNumber})}})}}}function re(s){let r=new I({apiUrl:s.apiUrl,store_id:s.storeId,store_passwd:s.storePassword});return{createCheckoutSession(e){return o(this,null,function*(){let n=e.currency.toUpperCase();return{url:yield r.getCheckoutUrl({tran_id:e.transactionId,store_id:s.storeId,store_passwd:s.storePassword,total_amount:e.amount/100,currency:n,success_url:e.successUrl,cancel_url:e.cancelUrl,cus_name:e.customerName,cus_email:e.customerEmail,cus_add1:e.customerAddress,cus_city:e.customerCity,cus_state:e.customerState,cus_postcode:e.customerPostcode,cus_country:e.customerCountry,cus_phone:e.customerPhone,shipping_method:"NO",product_name:e.productName,product_category:e.productCategory,product_profile:e.productProfile||"general"})}})}}}function ne(s){var t;let r=new C({merchant_id:s.merchantId,merchant_number:s.merchantNumber,private_key:s.privateKey,public_key:s.publicKey,callbackURL:s.callbackUrl,apiVersion:s.apiVersion,is_live:(t=s.isLive)!=null?t:!1});return{createCheckoutSession(n){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({orderId:n.orderId,amount:String(n.amount),ip:n.ip,clientType:n.clientType||"PC_WEB",productDetails:n.productDetails||{}})}})}}}function se(s){let r=new P({accessToken:s.accessToken,sandbox:s.sandbox});return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({products:[{product_id:e.productId,quantity:e.quantity}],success_url:e.successUrl,customer_email:e.customerEmail,customer_name:e.customerName,customer_external_id:e.customerExternalId,metadata:e.metadata,discount_id:e.discountId,allow_discount_codes:e.allowDiscountCodes})}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret,webhookId:e.webhookId||"",timestamp:e.timestamp||""});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function oe(s){let r=new S({keyId:s.keyId,keySecret:s.keySecret});return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({amount:e.amount,currency:e.currency.toUpperCase(),description:e.description,customer:{name:e.customerName,email:e.customerEmail,contact:e.customerContact},notify:{sms:!1,email:!1},callback_url:e.successUrl,callback_method:"get",notes:e.notes})}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function ae(s){let r=new f({apiKey:s.apiKey,sandbox:s.sandbox});return{createCheckoutSession(e){return o(this,null,function*(){var a;let n=yield r.createTransaction({items:[{priceId:e.priceId,quantity:(a=e.quantity)!=null?a:1}],customerId:e.customerId,customData:e.customData});return{url:n.url,sessionId:n.id}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,secret:e.secret,signature:e.signature});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function ie(s){let r=new b({apiKey:s.apiKey});return{createCheckoutSession(e){return o(this,null,function*(){let n=(e.amount/100).toFixed(2),a=yield r.createCharge({name:e.name||"Payment",description:e.description||"Payment",pricing_type:"fixed_price",local_price:{amount:n,currency:e.currency.toUpperCase()},redirect_url:e.successUrl,cancel_url:e.cancelUrl,metadata:e.metadata});return{url:a.url,sessionId:a.code}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function H(s){switch(s.provider){case"stripe":return Q(s);case"paypal":return Z(s);case"lemonsqueezy":return ee(s);case"bkash":return te(s);case"sslcommerz":return re(s);case"nagad":return ne(s);case"polar":return se(s);case"razorpay":return oe(s);case"paddle":return ae(s);case"coinbase":return ie(s);default:throw new Error(`Unsupported payment provider: ${s.provider}`)}}var ce={LemonSqueezy:g,Bkash:l,Paypal:k,Polar:P,Razorpay:S,Paddle:f,SSLCommerz:I,Stripe:v,Nagad:C,Coinbase:b};0&&(module.exports={UnifyPayment,createPayment});
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var U=Object.defineProperty,R=Object.defineProperties;var w=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var b=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var P=(i,r,e)=>r in i?U(i,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[r]=e,g=(i,r)=>{for(var e in r||(r={}))b.call(r,e)&&P(i,e,r[e]);if(T)for(var e of T(r))B.call(r,e)&&P(i,e,r[e]);return i},S=(i,r)=>R(i,w(r));var a=(i,r,e)=>new Promise((t,s)=>{var n=p=>{try{c(e.next(p))}catch(m){s(m)}},h=p=>{try{c(e.throw(p))}catch(m){s(m)}},c=p=>p.done?t(p.value):Promise.resolve(p.value).then(n,h);c((e=e.apply(i,r)).next())});import E from"axios";var o=class{jsonFetch(r,e){return a(this,null,function*(){let t=yield fetch(r,e);return[yield t.json(),t]})}axios(r,e){return a(this,null,function*(){let t=yield E({url:r,method:e==null?void 0:e.method,headers:e==null?void 0:e.headers,data:e==null?void 0:e.body});return[t.data,t.request]})}};var l=class extends o{constructor(e){super();this.options=e}getAppKey(){return this.options.app_key}getApiBaseUrl(){return this.options.apiUrl}getApiRequestHeaders(){return{"Content-Type":"application/json",Accept:"application/json",username:this.options.username,password:this.options.password}}getAccessToken(){return a(this,null,function*(){let[e]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/token/grant`,{method:"POST",headers:this.getApiRequestHeaders(),body:JSON.stringify({app_key:this.options.app_key,app_secret:this.options.app_secret})});if("errorMessage"in e)throw new Error(e.errorMessage);return e.id_token})}getCheckoutUrl(e){return a(this,null,function*(){let t=yield this.getAccessToken(),[s]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/create`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-App-Key":this.getAppKey(),Authorization:`Bearer ${t}`},body:JSON.stringify(e)});if("errorMessage"in s)throw new Error(s.errorMessage);return s.bkashURL})}};var y=class extends o{constructor(e){super();this.apiKey=e}getApiBaseUrl(){return"https://api.lemonsqueezy.com/v1"}getApiRequestHeaders(){return{Accept:"application/vnd.api+json","Content-Type":"application/vnd.api+json",Authorization:`Bearer ${this.apiKey}`}}getCheckoutUrl(e){return a(this,null,function*(){let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/checkouts`,{method:"POST",body:JSON.stringify({data:e}),headers:this.getApiRequestHeaders()});if("errors"in t)throw new Error(t.errors[0].detail);return t.data.attributes.url})}verifySignature(e){return a(this,null,function*(){try{let t=new TextEncoder,s=yield crypto.subtle.importKey("raw",t.encode(e.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=yield crypto.subtle.sign("HMAC",s,t.encode(e.body));if(Array.from(new Uint8Array(n)).map(c=>c.toString(16).padStart(2,"0")).join("")!==e.signature)throw new Error("Invalid signature");return{event:JSON.parse(e.body),type:e.x_event}}catch(t){return{error:t}}})}};import C from"dayjs";import N from"dayjs/plugin/timezone";import O from"dayjs/plugin/utc";import I from"node:crypto";import K from"node-rsa";var v=class extends o{constructor(e){super();this.options=e;C.extend(N),C.extend(O)}getApiBaseUrl(){return this.options.is_live?"https://api.mynagad.com/api/dfs":"http://sandbox.mynagad.com:10080/remote-payment-gateway-1.0/api/dfs"}getMerchantId(){return this.options.merchant_id}getMerchantNumber(){return this.options.merchant_number}getPrivateKey(){return this.options.private_key}getPublicKey(){return this.options.public_key}getTimeStamp(){return C().tz("Asia/Dhaka").format("YYYYMMDDHHmmss")}getCallbackUrl(){return this.options.callbackURL}getApiHeaders(){return{Accept:"application/json","Content-Type":"application/json","X-KM-Api-Version":this.options.apiVersion}}createHash(e){return I.createHash("sha1").update(e).digest("hex").toUpperCase()}encrypt(e){let t=`-----BEGIN PUBLIC KEY-----
1
+ var B=Object.defineProperty,N=Object.defineProperties;var z=Object.getOwnPropertyDescriptors;var R=Object.getOwnPropertySymbols;var O=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var E=(s,r,t)=>r in s?B(s,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[r]=t,h=(s,r)=>{for(var t in r||(r={}))O.call(r,t)&&E(s,t,r[t]);if(R)for(var t of R(r))K.call(r,t)&&E(s,t,r[t]);return s},U=(s,r)=>N(s,z(r));var o=(s,r,t)=>new Promise((e,n)=>{var a=u=>{try{p(t.next(u))}catch(m){n(m)}},i=u=>{try{p(t.throw(u))}catch(m){n(m)}},p=u=>u.done?e(u.value):Promise.resolve(u.value).then(a,i);p((t=t.apply(s,r)).next())});import D from"axios";var c=class{jsonFetch(r,t){return o(this,null,function*(){let e=yield fetch(r,t);return[yield e.json(),e]})}axios(r,t){return o(this,null,function*(){let e=yield D({url:r,method:t==null?void 0:t.method,headers:t==null?void 0:t.headers,data:t==null?void 0:t.body});return[e.data,e.request]})}};var l=class extends c{constructor(t){super();this.options=t}getAppKey(){return this.options.app_key}getApiBaseUrl(){return this.options.apiUrl}getApiRequestHeaders(){return{"Content-Type":"application/json",Accept:"application/json",username:this.options.username,password:this.options.password}}getAccessToken(){return o(this,null,function*(){let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/token/grant`,{method:"POST",headers:this.getApiRequestHeaders(),body:JSON.stringify({app_key:this.options.app_key,app_secret:this.options.app_secret})});if("errorMessage"in t)throw new Error(t.errorMessage);return t.id_token})}getCheckoutUrl(t){return o(this,null,function*(){let e=yield this.getAccessToken(),[n]=yield this.jsonFetch(`${this.getApiBaseUrl()}/tokenized/checkout/create`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-App-Key":this.getAppKey(),Authorization:`Bearer ${e}`},body:JSON.stringify(t)});if("errorMessage"in n)throw new Error(n.errorMessage);return n.bkashURL})}};var g=class extends c{constructor(t){super();this.apiKey=t}getApiBaseUrl(){return"https://api.lemonsqueezy.com/v1"}getApiRequestHeaders(){return{Accept:"application/vnd.api+json","Content-Type":"application/vnd.api+json",Authorization:`Bearer ${this.apiKey}`}}getCheckoutUrl(t){return o(this,null,function*(){let[e]=yield this.jsonFetch(`${this.getApiBaseUrl()}/checkouts`,{method:"POST",body:JSON.stringify({data:t}),headers:this.getApiRequestHeaders()});if("errors"in e)throw new Error(e.errors[0].detail);return e.data.attributes.url})}verifySignature(t){return o(this,null,function*(){try{let e=new TextEncoder,n=yield crypto.subtle.importKey("raw",e.encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=yield crypto.subtle.sign("HMAC",n,e.encode(t.body));if(Array.from(new Uint8Array(a)).map(p=>p.toString(16).padStart(2,"0")).join("")!==t.signature)throw new Error("Invalid signature");return{event:JSON.parse(t.body),type:t.x_event}}catch(e){return{error:e}}})}};import T from"dayjs";import L from"dayjs/plugin/timezone";import $ from"dayjs/plugin/utc";import A from"crypto";import q from"node-rsa";var C=class extends c{constructor(t){super();this.options=t;T.extend(L),T.extend($)}getApiBaseUrl(){return this.options.is_live?"https://api.mynagad.com/api/dfs":"http://sandbox.mynagad.com:10080/remote-payment-gateway-1.0/api/dfs"}getMerchantId(){return this.options.merchant_id}getMerchantNumber(){return this.options.merchant_number}getPrivateKey(){return this.options.private_key}getPublicKey(){return this.options.public_key}getTimeStamp(){return T().tz("Asia/Dhaka").format("YYYYMMDDHHmmss")}getCallbackUrl(){return this.options.callbackURL}getApiHeaders(){return{Accept:"application/json","Content-Type":"application/json","X-KM-Api-Version":this.options.apiVersion}}createHash(t){return A.createHash("sha1").update(t).digest("hex").toUpperCase()}encrypt(t){let e=`-----BEGIN PUBLIC KEY-----
2
2
  ${this.getPublicKey()}
3
- -----END PUBLIC KEY-----`;return I.publicEncrypt({key:t,padding:I.constants.RSA_PKCS1_PADDING},Buffer.from(JSON.stringify(e),"utf8")).toString("base64")}decrypt(e){let t=`-----BEGIN PRIVATE KEY-----
3
+ -----END PUBLIC KEY-----`;return A.publicEncrypt({key:e,padding:A.constants.RSA_PKCS1_PADDING},Buffer.from(JSON.stringify(t),"utf8")).toString("base64")}decrypt(t){let e=`-----BEGIN PRIVATE KEY-----
4
4
  ${this.getPrivateKey()}
5
- -----END PRIVATE KEY-----`,s=new K(t,"pkcs8",{encryptionScheme:"pkcs1"});s.setOptions({environment:"browser"});let n=s.decrypt(e).toString("utf8");return JSON.parse(n)}sign(e){let t=`-----BEGIN PRIVATE KEY-----
5
+ -----END PRIVATE KEY-----`,n=new q(e,"pkcs8",{encryptionScheme:"pkcs1"});n.setOptions({environment:"browser"});let a=n.decrypt(t).toString("utf8");return JSON.parse(a)}sign(t){let e=`-----BEGIN PRIVATE KEY-----
6
6
  ${this.getPrivateKey()}
7
- -----END PRIVATE KEY-----`,s=I.createSign("SHA256");return s.update(JSON.stringify(e)),s.end(),s.sign(t,"base64")}confirmPayment(e){return a(this,null,function*(){let t={currencyCode:"050",amount:e.amount,orderId:e.orderId,challenge:e.challenge,merchantId:this.getMerchantId()},s={signature:this.sign(t),paymentRefId:e.paymentReferenceId,sensitiveData:this.encrypt(t),merchantCallbackURL:this.getCallbackUrl(),additionalMerchantInfo:g({},e.productDetails)},[n]=yield this.axios(`${this.getApiBaseUrl()}/check-out/complete/${e.paymentReferenceId}`,{method:"POST",headers:S(g({},this.getApiHeaders()),{"X-KM-IP-V4":e.ip,"X-KM-Client-Type":e.clientType}),body:JSON.stringify(s)});return n})}getCheckoutUrl(e){return a(this,null,function*(){let t=this.getTimeStamp(),s=`${this.getApiBaseUrl()}/check-out/initialize/${this.getMerchantId()}/${e.orderId}`,n={datetime:t,orderId:e.orderId,merchantId:this.getMerchantId(),challenge:this.createHash(e.orderId)},h={dateTime:t,signature:this.sign(n),sensitiveData:this.encrypt(n),accountNumber:this.getMerchantNumber()},[c]=yield this.axios(s,{method:"POST",headers:S(g({},this.getApiHeaders()),{"X-KM-IP-V4":e.ip,"X-KM-Client-Type":e.clientType}),body:JSON.stringify(h)}),p=this.decrypt(c.sensitiveData);return(yield this.confirmPayment({ip:e.ip,challenge:p.challenge,amount:e.amount,orderId:e.orderId,clientType:e.clientType,paymentReferenceId:p.paymentReferenceId,productDetails:e.productDetails})).callBackUrl})}};var A=class extends o{constructor(e){super();this.options=e}getApiBaseUrl(){return this.options.sandbox?"https://api-m.sandbox.paypal.com":"https://api.paypal.com"}getClientId(){return this.options.clientId}getClientSecret(){return this.options.clientSecret}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/v2/checkout/orders`}getAccessToken(){return a(this,null,function*(){let e=`${this.getApiBaseUrl()}/v1/oauth2/token`,t=btoa(`${this.getClientId()}:${this.getClientSecret()}`),[s]=yield this.jsonFetch(e,{method:"POST",headers:{Authorization:`Basic ${t}`,"Content-Type":"application/x-www-form-urlencoded"},body:"grant_type=client_credentials"});return s.access_token})}getCheckoutUrl(e){return a(this,null,function*(){var h;let t=yield this.getAccessToken(),[s]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}}),n=(h=s.links.find(c=>c.rel==="approve"))==null?void 0:h.href;if(!n)throw new Error("Failed to get checkout url");return n})}};var k=class extends o{constructor(e){super();this.options=e}getApiBaseUrl(){return this.options.apiUrl}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/gwprocess/v4/api.php`}getApiValidationUrl(){return`${this.getApiBaseUrl()}/validator/api/validationserverAPI.php`}getApiRefundUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiRefundQueryUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryBySessionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryByTransactionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiHeaders(){return{"Content-Type":"application/x-www-form-urlencoded"}}urlFormEncode(e){return Object.entries(e).map(([t,s])=>`${encodeURIComponent(t)}=${encodeURIComponent(s)}`).join("&")}getCheckoutUrl(e){return a(this,null,function*(){let[t]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:this.urlFormEncode(e),headers:this.getApiHeaders()});if(t.status==="FAILED")throw new Error(t.failedreason);return t.redirectGatewayURL})}};import{Stripe as x}from"stripe";var f=class{constructor(r,e){this.apiKey=r;this.stripe=new x(r,e)}getCheckoutUrl(r){return a(this,null,function*(){let e=yield this.stripe.checkout.sessions.create(r);if(!e.url)throw new Error("Failed to get checkout url");return e.url})}verifySignature(r){return a(this,null,function*(){try{return{event:yield this.stripe.webhooks.constructEventAsync(r.body,r.signature,r.secret)}}catch(e){return{error:e}}})}};var Se={LemonSqueezy:y,Bkash:l,Paypal:A,SSLCommerz:k,Stripe:f,Nagad:v};export{Se as UnifyPayment};
7
+ -----END PRIVATE KEY-----`,n=A.createSign("SHA256");return n.update(JSON.stringify(t)),n.end(),n.sign(e,"base64")}confirmPayment(t){return o(this,null,function*(){let e={currencyCode:"050",amount:t.amount,orderId:t.orderId,challenge:t.challenge,merchantId:this.getMerchantId()},n={signature:this.sign(e),paymentRefId:t.paymentReferenceId,sensitiveData:this.encrypt(e),merchantCallbackURL:this.getCallbackUrl(),additionalMerchantInfo:h({},t.productDetails)},[a]=yield this.axios(`${this.getApiBaseUrl()}/check-out/complete/${t.paymentReferenceId}`,{method:"POST",headers:U(h({},this.getApiHeaders()),{"X-KM-IP-V4":t.ip,"X-KM-Client-Type":t.clientType}),body:JSON.stringify(n)});return a})}getCheckoutUrl(t){return o(this,null,function*(){let e=this.getTimeStamp(),n=`${this.getApiBaseUrl()}/check-out/initialize/${this.getMerchantId()}/${t.orderId}`,a={datetime:e,orderId:t.orderId,merchantId:this.getMerchantId(),challenge:this.createHash(t.orderId)},i={dateTime:e,signature:this.sign(a),sensitiveData:this.encrypt(a),accountNumber:this.getMerchantNumber()},[p]=yield this.axios(n,{method:"POST",headers:U(h({},this.getApiHeaders()),{"X-KM-IP-V4":t.ip,"X-KM-Client-Type":t.clientType}),body:JSON.stringify(i)}),u=this.decrypt(p.sensitiveData);return(yield this.confirmPayment({ip:t.ip,challenge:u.challenge,amount:t.amount,orderId:t.orderId,clientType:t.clientType,paymentReferenceId:u.paymentReferenceId,productDetails:t.productDetails})).callBackUrl})}};var k=class extends c{constructor(t){super();this.options=t}getApiBaseUrl(){return this.options.sandbox?"https://api-m.sandbox.paypal.com":"https://api.paypal.com"}getClientId(){return this.options.clientId}getClientSecret(){return this.options.clientSecret}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/v2/checkout/orders`}getAccessToken(){return o(this,null,function*(){let t=`${this.getApiBaseUrl()}/v1/oauth2/token`,e=btoa(`${this.getClientId()}:${this.getClientSecret()}`),[n]=yield this.jsonFetch(t,{method:"POST",headers:{Authorization:`Basic ${e}`,"Content-Type":"application/x-www-form-urlencoded"},body:"grant_type=client_credentials"});return n.access_token})}getCheckoutUrl(t){return o(this,null,function*(){var i;let e=yield this.getAccessToken(),[n]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}}),a=(i=n.links.find(p=>p.rel==="approve"))==null?void 0:i.href;if(!a)throw new Error("Failed to get checkout url");return a})}};var P=class extends c{constructor(r){var t;super(),this.accessToken=r.accessToken,this.sandbox=(t=r.sandbox)!=null?t:!1}getApiBaseUrl(){return this.sandbox?"https://sandbox-api.polar.sh/v1":"https://api.polar.sh/v1"}getApiRequestHeaders(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`}}getCheckoutUrl(r){return o(this,null,function*(){let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/checkouts/`,{method:"POST",body:JSON.stringify(r),headers:this.getApiRequestHeaders()});if(!t.url)throw new Error("Failed to create Polar checkout session");return t.url})}verifySignature(r){return o(this,null,function*(){try{let t=`${r.webhookId}.${r.timestamp}.${r.body}`,e=new TextEncoder,n=r.secret.startsWith("whsec_")?r.secret.slice(6):r.secret,a=Uint8Array.from(atob(n),w=>w.charCodeAt(0)),i=yield crypto.subtle.importKey("raw",a,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),p=yield crypto.subtle.sign("HMAC",i,e.encode(t)),u=btoa(String.fromCharCode(...new Uint8Array(p)));if(!r.signature.split(" ").some(w=>(w.startsWith("v1,")?w.slice(3):w)===u))throw new Error("Invalid webhook signature");let _=JSON.parse(r.body);return{type:_.type,event:_.data}}catch(t){return{error:t}}})}};var S=class extends c{constructor(r){super(),this.keyId=r.keyId,this.keySecret=r.keySecret}getApiBaseUrl(){return"https://api.razorpay.com/v1"}getApiRequestHeaders(){return{"Content-Type":"application/json",Authorization:`Basic ${btoa(`${this.keyId}:${this.keySecret}`)}`}}getCheckoutUrl(r){return o(this,null,function*(){let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/payment_links`,{method:"POST",body:JSON.stringify(r),headers:this.getApiRequestHeaders()});if(!t.short_url)throw new Error("Failed to create Razorpay payment link");return t.short_url})}verifySignature(r){return o(this,null,function*(){try{let t=new TextEncoder,e=yield crypto.subtle.importKey("raw",t.encode(r.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=yield crypto.subtle.sign("HMAC",e,t.encode(r.body));if(Array.from(new Uint8Array(n)).map(p=>p.toString(16).padStart(2,"0")).join("")!==r.signature)throw new Error("Invalid webhook signature");let i=JSON.parse(r.body);return{type:i.event,event:i.payload}}catch(t){return{error:t}}})}};import{Environment as x,Paddle as H}from"@paddle/paddle-node-sdk";var f=class{constructor(r){this.sdk=new H(r.apiKey,{environment:r.sandbox?x.sandbox:x.production})}createTransaction(r){return o(this,null,function*(){var n;let t=yield this.sdk.transactions.create(h(h({items:r.items.map(a=>({priceId:a.priceId,quantity:a.quantity}))},r.customerId&&{customerId:r.customerId}),r.customData&&{customData:r.customData})),e=(n=t.checkout)==null?void 0:n.url;if(!e)throw new Error("Failed to create Paddle checkout session");return{id:t.id,url:e}})}verifySignature(r){return o(this,null,function*(){try{let t=this.sdk.webhooks.unmarshal(r.body,r.secret,r.signature);if(!t)throw new Error("Invalid webhook signature");return{type:t.eventType,event:t}}catch(t){return{error:t}}})}};var I=class extends c{constructor(t){super();this.options=t}getApiBaseUrl(){return this.options.apiUrl}getApiCheckoutUrl(){return`${this.getApiBaseUrl()}/gwprocess/v4/api.php`}getApiValidationUrl(){return`${this.getApiBaseUrl()}/validator/api/validationserverAPI.php`}getApiRefundUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiRefundQueryUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryBySessionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiTransactionQueryByTransactionIdUrl(){return`${this.getApiBaseUrl()}/validator/api/merchantTransIDvalidationAPI.php`}getApiHeaders(){return{"Content-Type":"application/x-www-form-urlencoded"}}urlFormEncode(t){return Object.entries(t).map(([e,n])=>`${encodeURIComponent(e)}=${encodeURIComponent(n)}`).join("&")}getCheckoutUrl(t){return o(this,null,function*(){let[e]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:this.urlFormEncode(t),headers:this.getApiHeaders()});if(e.status==="FAILED")throw new Error(e.failedreason);return e.redirectGatewayURL})}};import{Stripe as F}from"stripe";var v=class{constructor(r,t){this.apiKey=r;this.stripe=new F(r,t)}getCheckoutUrl(r){return o(this,null,function*(){let t=yield this.stripe.checkout.sessions.create(r);if(!t.url)throw new Error("Failed to get checkout url");return t.url})}verifySignature(r){return o(this,null,function*(){try{return{event:yield this.stripe.webhooks.constructEventAsync(r.body,r.signature,r.secret)}}catch(t){return{error:t}}})}};var b=class extends c{constructor(r){super(),this.apiKey=r.apiKey}getApiBaseUrl(){return"https://api.commerce.coinbase.com"}getApiRequestHeaders(){return{"Content-Type":"application/json","X-CC-Api-Key":this.apiKey,"X-CC-Version":"2018-03-22"}}createCharge(r){return o(this,null,function*(){var e;let[t]=yield this.jsonFetch(`${this.getApiBaseUrl()}/charges`,{method:"POST",body:JSON.stringify(r),headers:this.getApiRequestHeaders()});if(!((e=t.data)!=null&&e.hosted_url))throw new Error("Failed to create Coinbase Commerce charge");return{id:t.data.id,code:t.data.code,url:t.data.hosted_url}})}verifySignature(r){return o(this,null,function*(){var t,e;try{let n=new TextEncoder,a=yield crypto.subtle.importKey("raw",n.encode(r.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=yield crypto.subtle.sign("HMAC",a,n.encode(r.body));if(Array.from(new Uint8Array(i)).map(m=>m.toString(16).padStart(2,"0")).join("")!==r.signature)throw new Error("Invalid webhook signature");let u=JSON.parse(r.body);return{type:(t=u.event)==null?void 0:t.type,event:(e=u.event)==null?void 0:e.data}}catch(n){return{error:n}}})}};import{Stripe as j}from"stripe";function W(s){let r=new v(s.apiKey,s.config),t=new j(s.apiKey,s.config);return{createCheckoutSession(n){return o(this,null,function*(){let a=h({mode:"payment",line_items:[{price_data:{currency:n.currency,unit_amount:n.amount,product_data:{name:n.productName||"Payment"}},quantity:1}],success_url:n.successUrl,cancel_url:n.cancelUrl,metadata:n.metadata},n.overrides),i=yield t.checkout.sessions.create(a);if(!i.url)throw new Error("Failed to create checkout session");return{url:i.url,sessionId:i.id,raw:i}})},verifyWebhook(n){return o(this,null,function*(){let a=yield r.verifySignature({body:n.body,signature:n.signature,secret:n.secret});if("error"in a)throw a.error;return{type:a.event.type,data:a.event.data.object,raw:a.event}})}}}function M(s){let r=new k({clientId:s.clientId,clientSecret:s.clientSecret,sandbox:s.sandbox});return{createCheckoutSession(e){return o(this,null,function*(){let n=(e.amount/100).toFixed(2),a=e.currency.toUpperCase();return{url:yield r.getCheckoutUrl({intent:"CAPTURE",purchase_units:[{items:[{name:e.description||"Payment",description:e.description||"Payment",quantity:1,unit_amount:{currency_code:a,value:n}}],amount:{currency_code:a,value:n,breakdown:{item_total:{currency_code:a,value:n}}}}],application_context:{return_url:e.successUrl,cancel_url:e.cancelUrl,shipping_preference:"NO_SHIPPING",user_action:"PAY_NOW",brand_name:e.brandName}})}})}}}function V(s){let r=new g(s.apiKey);return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({type:"checkouts",attributes:{custom_price:e.amount,product_options:{redirect_url:e.redirectUrl||e.successUrl}},relationships:{store:{data:{type:"stores",id:e.storeId}},variant:{data:{type:"variants",id:e.variantId}}}})}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret,x_event:""});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function J(s){let r=new l({apiUrl:s.apiUrl,username:s.username,password:s.password,app_key:s.appKey,app_secret:s.appSecret});return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({mode:"0011",payerReference:e.payerReference,callbackURL:e.successUrl,amount:String(e.amount),currency:"BDT",intent:"sale",merchantInvoiceNumber:e.merchantInvoiceNumber})}})}}}function Y(s){let r=new I({apiUrl:s.apiUrl,store_id:s.storeId,store_passwd:s.storePassword});return{createCheckoutSession(e){return o(this,null,function*(){let n=e.currency.toUpperCase();return{url:yield r.getCheckoutUrl({tran_id:e.transactionId,store_id:s.storeId,store_passwd:s.storePassword,total_amount:e.amount/100,currency:n,success_url:e.successUrl,cancel_url:e.cancelUrl,cus_name:e.customerName,cus_email:e.customerEmail,cus_add1:e.customerAddress,cus_city:e.customerCity,cus_state:e.customerState,cus_postcode:e.customerPostcode,cus_country:e.customerCountry,cus_phone:e.customerPhone,shipping_method:"NO",product_name:e.productName,product_category:e.productCategory,product_profile:e.productProfile||"general"})}})}}}function G(s){var t;let r=new C({merchant_id:s.merchantId,merchant_number:s.merchantNumber,private_key:s.privateKey,public_key:s.publicKey,callbackURL:s.callbackUrl,apiVersion:s.apiVersion,is_live:(t=s.isLive)!=null?t:!1});return{createCheckoutSession(n){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({orderId:n.orderId,amount:String(n.amount),ip:n.ip,clientType:n.clientType||"PC_WEB",productDetails:n.productDetails||{}})}})}}}function X(s){let r=new P({accessToken:s.accessToken,sandbox:s.sandbox});return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({products:[{product_id:e.productId,quantity:e.quantity}],success_url:e.successUrl,customer_email:e.customerEmail,customer_name:e.customerName,customer_external_id:e.customerExternalId,metadata:e.metadata,discount_id:e.discountId,allow_discount_codes:e.allowDiscountCodes})}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret,webhookId:e.webhookId||"",timestamp:e.timestamp||""});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function Q(s){let r=new S({keyId:s.keyId,keySecret:s.keySecret});return{createCheckoutSession(e){return o(this,null,function*(){return{url:yield r.getCheckoutUrl({amount:e.amount,currency:e.currency.toUpperCase(),description:e.description,customer:{name:e.customerName,email:e.customerEmail,contact:e.customerContact},notify:{sms:!1,email:!1},callback_url:e.successUrl,callback_method:"get",notes:e.notes})}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function Z(s){let r=new f({apiKey:s.apiKey,sandbox:s.sandbox});return{createCheckoutSession(e){return o(this,null,function*(){var a;let n=yield r.createTransaction({items:[{priceId:e.priceId,quantity:(a=e.quantity)!=null?a:1}],customerId:e.customerId,customData:e.customData});return{url:n.url,sessionId:n.id}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,secret:e.secret,signature:e.signature});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function ee(s){let r=new b({apiKey:s.apiKey});return{createCheckoutSession(e){return o(this,null,function*(){let n=(e.amount/100).toFixed(2),a=yield r.createCharge({name:e.name||"Payment",description:e.description||"Payment",pricing_type:"fixed_price",local_price:{amount:n,currency:e.currency.toUpperCase()},redirect_url:e.successUrl,cancel_url:e.cancelUrl,metadata:e.metadata});return{url:a.url,sessionId:a.code}})},verifyWebhook(e){return o(this,null,function*(){let n=yield r.verifySignature({body:e.body,signature:e.signature,secret:e.secret});if("error"in n)throw n.error;return{type:n.type,data:n.event,raw:n.event}})}}}function te(s){switch(s.provider){case"stripe":return W(s);case"paypal":return M(s);case"lemonsqueezy":return V(s);case"bkash":return J(s);case"sslcommerz":return Y(s);case"nagad":return G(s);case"polar":return X(s);case"razorpay":return Q(s);case"paddle":return Z(s);case"coinbase":return ee(s);default:throw new Error(`Unsupported payment provider: ${s.provider}`)}}var wt={LemonSqueezy:g,Bkash:l,Paypal:k,Polar:P,Razorpay:S,Paddle:f,SSLCommerz:I,Stripe:v,Nagad:C,Coinbase:b};export{wt as UnifyPayment,te as createPayment};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unify-payment/node",
3
- "version": "0.0.11",
3
+ "version": "1.0.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "module": "dist/index.mjs",