@unify-payment/node 0.0.3 → 0.0.5

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.ts CHANGED
@@ -1,4 +1,345 @@
1
- export * from "./lib/common";
2
- export * from "./lib/lemonsqueezy";
3
- export * from "./lib/stripe";
4
- export * from "./types/lemonsqueezy";
1
+ import Stripe$1, { Stripe as Stripe$2 } from 'stripe';
2
+
3
+ interface IBkashCheckoutOptions {
4
+ code: "0011";
5
+ payerReference: string;
6
+ callbackURL: string;
7
+ amount: string;
8
+ currency: "BDT";
9
+ intent: "sale";
10
+ merchantInvoiceNumber: string;
11
+ merchantAssociationInfo?: string;
12
+ }
13
+ interface IBkashPayloadProps {
14
+ apiUrl: string;
15
+ username: string;
16
+ password: string;
17
+ app_key: string;
18
+ app_secret: string;
19
+ }
20
+
21
+ type TFetchOptions = {
22
+ method?: string;
23
+ headers?: HeadersInit;
24
+ body?: BodyInit;
25
+ };
26
+ declare class UnifyFetch {
27
+ jsonFetch<T>(url: string, options?: TFetchOptions): Promise<[T, Response]>;
28
+ axios<T>(url: string, options?: TFetchOptions): Promise<void>;
29
+ }
30
+
31
+ declare class Bkash extends UnifyFetch {
32
+ private options;
33
+ constructor(options: IBkashPayloadProps);
34
+ private getAppKey;
35
+ private getApiBaseUrl;
36
+ private getApiRequestHeaders;
37
+ getAccessToken(): Promise<string>;
38
+ getCheckoutUrl(options: IBkashCheckoutOptions): Promise<string>;
39
+ }
40
+
41
+ type TLemonSqueezyWebhookEvents = "order_created" | "order_refunded" | "subscription_created" | "subscription_updated" | "subscription_cancelled" | "subscription_resumed" | "subscription_expired" | "subscription_paused" | "subscription_unpaused" | "subscription_payment_success" | "subscription_payment_failed" | "subscription_payment_recovered" | "subscription_payment_refunded" | "license_key_created" | "license_key_updated";
42
+ type TWebhookEventResponse = {
43
+ error: Error;
44
+ } | {
45
+ event: ILemonSqueezyWebhookEeventResponse;
46
+ type: TLemonSqueezyWebhookEvents;
47
+ };
48
+ interface ILemonSqueezyWebhookEeventResponse {
49
+ meta: {
50
+ event_name: string;
51
+ custom_data: {
52
+ customer_id: number;
53
+ };
54
+ };
55
+ data: {
56
+ type: "orders" | "subscriptions";
57
+ id: string;
58
+ attributes: {
59
+ store_id: number;
60
+ customer_id: number;
61
+ identifier: string;
62
+ order_number: number;
63
+ user_name: string;
64
+ user_email: string;
65
+ currency: string;
66
+ currency_rate: string;
67
+ subtotal: number;
68
+ discount_total: number;
69
+ tax: number;
70
+ total: number;
71
+ subtotal_usd: number;
72
+ discount_total_usd: number;
73
+ tax_usd: number;
74
+ total_usd: number;
75
+ tax_name: string;
76
+ tax_rate: string;
77
+ status: string;
78
+ status_formatted: string;
79
+ refunded: boolean;
80
+ refunded_at: any;
81
+ subtotal_formatted: string;
82
+ discount_total_formatted: string;
83
+ tax_formatted: string;
84
+ total_formatted: string;
85
+ first_order_item: {
86
+ id: number;
87
+ order_id: number;
88
+ product_id: number;
89
+ variant_id: number;
90
+ product_name: string;
91
+ variant_name: string;
92
+ price: number;
93
+ created_at: string;
94
+ updated_at: string;
95
+ deleted_at: any;
96
+ test_mode: boolean;
97
+ };
98
+ urls: {
99
+ receipt: string;
100
+ };
101
+ created_at: string;
102
+ updated_at: string;
103
+ };
104
+ relationships: {
105
+ store: {
106
+ links: {
107
+ related: string;
108
+ self: string;
109
+ };
110
+ };
111
+ customer: {
112
+ links: {
113
+ related: string;
114
+ self: string;
115
+ };
116
+ };
117
+ "order-items": {
118
+ links: {
119
+ related: string;
120
+ self: string;
121
+ };
122
+ };
123
+ subscriptions: {
124
+ links: {
125
+ related: string;
126
+ self: string;
127
+ };
128
+ };
129
+ "license-keys": {
130
+ links: {
131
+ related: string;
132
+ self: string;
133
+ };
134
+ };
135
+ "discount-redemptions": {
136
+ links: {
137
+ related: string;
138
+ self: string;
139
+ };
140
+ };
141
+ };
142
+ links: {
143
+ self: string;
144
+ };
145
+ };
146
+ }
147
+ interface ILemonSqueezyCheckoutOptions {
148
+ type: "checkouts";
149
+ attributes?: {
150
+ custom_price?: number;
151
+ product_options?: {
152
+ redirect_url?: string;
153
+ enabled_variants?: number[];
154
+ };
155
+ checkout_options?: {
156
+ button_color: string;
157
+ };
158
+ checkout_data?: {
159
+ discount_code?: string;
160
+ custom?: {
161
+ user_id: number;
162
+ };
163
+ };
164
+ expires_at?: string;
165
+ preview?: boolean;
166
+ };
167
+ relationships: {
168
+ store: {
169
+ data: {
170
+ type: string;
171
+ id: string;
172
+ };
173
+ };
174
+ variant: {
175
+ data: {
176
+ type: string;
177
+ id: string;
178
+ };
179
+ };
180
+ };
181
+ }
182
+
183
+ declare class LemonSqueezy extends UnifyFetch {
184
+ private apiKey;
185
+ constructor(apiKey: string);
186
+ private getApiBaseUrl;
187
+ private getApiRequestHeaders;
188
+ getCheckoutUrl(options: ILemonSqueezyCheckoutOptions): Promise<string>;
189
+ verifySignature(payload: {
190
+ signature: string;
191
+ secret: string;
192
+ body: string;
193
+ x_event: string;
194
+ }): Promise<TWebhookEventResponse>;
195
+ }
196
+
197
+ interface IPaypalOptions {
198
+ clientId: string;
199
+ clientSecret: string;
200
+ sandbox?: boolean;
201
+ }
202
+ interface IPaypalPayload {
203
+ intent: "CAPTURE";
204
+ purchase_units: {
205
+ items: {
206
+ name: string;
207
+ description: string;
208
+ quantity: number;
209
+ unit_amount: {
210
+ currency_code: "USD" | "EUR";
211
+ value: string;
212
+ };
213
+ }[];
214
+ amount: {
215
+ currency_code: "USD" | "EUR";
216
+ value: string;
217
+ breakdown: {
218
+ item_total: {
219
+ currency_code: "USD" | "EUR";
220
+ value: string;
221
+ };
222
+ };
223
+ };
224
+ }[];
225
+ application_context: {
226
+ return_url: string;
227
+ cancel_url: string;
228
+ shipping_preference?: "NO_SHIPPING";
229
+ user_action?: "PAY_NOW";
230
+ brand_name?: string;
231
+ };
232
+ }
233
+
234
+ declare class Paypal extends UnifyFetch {
235
+ private options;
236
+ constructor(options: IPaypalOptions);
237
+ private getApiBaseUrl;
238
+ private getClientId;
239
+ private getClientSecret;
240
+ private getApiCheckoutUrl;
241
+ getAccessToken(): Promise<string>;
242
+ getCheckoutUrl(payload: IPaypalPayload): Promise<string>;
243
+ }
244
+
245
+ type ISSLCommerzCreateCheckoutPayload = {
246
+ tran_id: string;
247
+ store_id: string;
248
+ store_passwd: string;
249
+ total_amount: number;
250
+ currency: "USD" | "EUR";
251
+ success_url?: string;
252
+ cancel_url?: string;
253
+ cus_name: string;
254
+ cus_email: string;
255
+ cus_add1: string;
256
+ cus_add2?: string;
257
+ cus_city: string;
258
+ cus_state: string;
259
+ cus_postcode: string;
260
+ cus_country: string;
261
+ cus_phone: string;
262
+ cus_fax?: string;
263
+ shipping_method: "NO";
264
+ product_name: string;
265
+ product_category: string;
266
+ product_profile: "general" | "physical-goods" | "non-physical-goods" | "airline-tickets" | "travel-vertical" | "telecom-vertical";
267
+ } | {
268
+ tran_id: string;
269
+ store_id: string;
270
+ store_passwd: string;
271
+ total_amount: number;
272
+ currency: "USD" | "EUR";
273
+ success_url?: string;
274
+ cancel_url?: string;
275
+ cus_name: string;
276
+ cus_email: string;
277
+ cus_add1: string;
278
+ cus_add2?: string;
279
+ cus_city: string;
280
+ cus_state: string;
281
+ cus_postcode: string;
282
+ cus_country: string;
283
+ cus_phone: string;
284
+ cus_fax?: string;
285
+ shipping_method: "YES";
286
+ ship_name: string;
287
+ ship_add1: string;
288
+ ship_add2?: string;
289
+ ship_city: string;
290
+ ship_state: string;
291
+ ship_postcode: string;
292
+ ship_country: string;
293
+ product_name: string;
294
+ product_category: string;
295
+ product_profile: "general" | "physical-goods" | "non-physical-goods" | "airline-tickets" | "travel-vertical" | "telecom-vertical";
296
+ };
297
+ type ISSLCommerzOptions = {
298
+ apiUrl: string;
299
+ store_id: string;
300
+ store_url?: string;
301
+ store_passwd: string;
302
+ };
303
+
304
+ declare class SSLCommerz extends UnifyFetch {
305
+ private options;
306
+ constructor(options: ISSLCommerzOptions);
307
+ private getApiBaseUrl;
308
+ private getApiCheckoutUrl;
309
+ private getApiValidationUrl;
310
+ private getApiRefundUrl;
311
+ private getApiRefundQueryUrl;
312
+ private getApiTransactionQueryBySessionIdUrl;
313
+ private getApiTransactionQueryByTransactionIdUrl;
314
+ private getApiHeaders;
315
+ private urlFormEncode;
316
+ getCheckoutUrl(payload: ISSLCommerzCreateCheckoutPayload): Promise<string>;
317
+ }
318
+
319
+ type TStripeWebhookEventResponse = {
320
+ error: Error;
321
+ } | {
322
+ event: Stripe$1.Event;
323
+ };
324
+
325
+ declare class Stripe {
326
+ private apiKey;
327
+ private stripe;
328
+ constructor(apiKey: string, config?: Stripe$2.StripeConfig);
329
+ getCheckoutUrl(params: Stripe$2.Checkout.SessionCreateParams): Promise<string>;
330
+ verifySignature(payload: {
331
+ signature: string;
332
+ secret: string;
333
+ body: string;
334
+ }): Promise<TStripeWebhookEventResponse>;
335
+ }
336
+
337
+ declare const UnifyPayment: {
338
+ LemonSqueezy: typeof LemonSqueezy;
339
+ Bkash: typeof Bkash;
340
+ Paypal: typeof Paypal;
341
+ SSLCommerz: typeof SSLCommerz;
342
+ Stripe: typeof Stripe;
343
+ };
344
+
345
+ export { UnifyPayment };
package/dist/index.js CHANGED
@@ -1,20 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./lib/common"), exports);
18
- __exportStar(require("./lib/lemonsqueezy"), exports);
19
- __exportStar(require("./lib/stripe"), exports);
20
- __exportStar(require("./types/lemonsqueezy"), exports);
1
+ "use strict";var A=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var f=(i,r)=>{for(var e in r)A(i,e,{get:r[e],enumerable:!0})},w=(i,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of S(r))!C.call(i,s)&&s!==e&&A(i,s,{get:()=>r[s],enumerable:!(t=I(r,s))||t.enumerable});return i};var U=i=>w(A({},"__esModule",{value:!0}),i);var o=(i,r,e)=>new Promise((t,s)=>{var c=p=>{try{a(e.next(p))}catch(k){s(k)}},u=p=>{try{a(e.throw(p))}catch(k){s(k)}},a=p=>p.done?t(p.value):Promise.resolve(p.value).then(c,u);a((e=e.apply(i,r)).next())});var P={};f(P,{UnifyPayment:()=>T});module.exports=U(P);var n=class{jsonFetch(r,e){return o(this,null,function*(){let t=yield fetch(r,e);return[yield t.json(),t]})}axios(r,e){return o(this,null,function*(){})}};var l=class extends n{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 o(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 o(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 d=class extends n{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 o(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 o(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"]),c=yield crypto.subtle.sign("HMAC",s,t.encode(e.body));if(Array.from(new Uint8Array(c)).map(a=>a.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}}})}};var g=class extends n{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 o(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 o(this,null,function*(){var u;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}`}}),c=(u=s.links.find(a=>a.rel==="approve"))==null?void 0:u.href;if(!c)throw new Error("Failed to get checkout url");return c})}};var y=class extends n{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 o(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})}};var v=require("stripe");var m=class{constructor(r,e){this.apiKey=r;this.stripe=new v.Stripe(r,e)}getCheckoutUrl(r){return o(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 o(this,null,function*(){try{return{event:yield this.stripe.webhooks.constructEventAsync(r.body,r.signature,r.secret)}}catch(e){return{error:e}}})}};var T={LemonSqueezy:d,Bkash:l,Paypal:g,SSLCommerz:y,Stripe:m};0&&(module.exports={UnifyPayment});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ var r=(n,s,e)=>new Promise((t,o)=>{var c=p=>{try{a(e.next(p))}catch(A){o(A)}},l=p=>{try{a(e.throw(p))}catch(A){o(A)}},a=p=>p.done?t(p.value):Promise.resolve(p.value).then(c,l);a((e=e.apply(n,s)).next())});var i=class{jsonFetch(s,e){return r(this,null,function*(){let t=yield fetch(s,e);return[yield t.json(),t]})}axios(s,e){return r(this,null,function*(){})}};var d=class extends i{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 r(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 r(this,null,function*(){let t=yield this.getAccessToken(),[o]=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 o)throw new Error(o.errorMessage);return o.bkashURL})}};var g=class extends i{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 r(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 r(this,null,function*(){try{let t=new TextEncoder,o=yield crypto.subtle.importKey("raw",t.encode(e.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),c=yield crypto.subtle.sign("HMAC",o,t.encode(e.body));if(Array.from(new Uint8Array(c)).map(a=>a.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}}})}};var y=class extends i{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 r(this,null,function*(){let e=`${this.getApiBaseUrl()}/v1/oauth2/token`,t=btoa(`${this.getClientId()}:${this.getClientSecret()}`),[o]=yield this.jsonFetch(e,{method:"POST",headers:{Authorization:`Basic ${t}`,"Content-Type":"application/x-www-form-urlencoded"},body:"grant_type=client_credentials"});return o.access_token})}getCheckoutUrl(e){return r(this,null,function*(){var l;let t=yield this.getAccessToken(),[o]=yield this.jsonFetch(this.getApiCheckoutUrl(),{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}}),c=(l=o.links.find(a=>a.rel==="approve"))==null?void 0:l.href;if(!c)throw new Error("Failed to get checkout url");return c})}};var m=class extends i{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,o])=>`${encodeURIComponent(t)}=${encodeURIComponent(o)}`).join("&")}getCheckoutUrl(e){return r(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 v}from"stripe";var k=class{constructor(s,e){this.apiKey=s;this.stripe=new v(s,e)}getCheckoutUrl(s){return r(this,null,function*(){let e=yield this.stripe.checkout.sessions.create(s);if(!e.url)throw new Error("Failed to get checkout url");return e.url})}verifySignature(s){return r(this,null,function*(){try{return{event:yield this.stripe.webhooks.constructEventAsync(s.body,s.signature,s.secret)}}catch(e){return{error:e}}})}};var Q={LemonSqueezy:g,Bkash:d,Paypal:y,SSLCommerz:m,Stripe:k};export{Q as UnifyPayment};
package/package.json CHANGED
@@ -1,17 +1,34 @@
1
1
  {
2
2
  "name": "@unify-payment/node",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
- "files": [
7
- "dist"
6
+ "module": "dist/index.mjs",
7
+ "keywords": [
8
+ "starter",
9
+ "kit",
10
+ "starterkit",
11
+ "easy",
12
+ "express",
13
+ "sailsjs",
14
+ "bower",
15
+ "frontend",
16
+ "backend",
17
+ "fullstack",
18
+ "starter-kit"
8
19
  ],
20
+ "homepage": "https://github.com/shakibhasan09/unify-payment",
21
+ "repository": {
22
+ "url": "https://github.com/shakibhasan09/unify-payment"
23
+ },
24
+ "license": "ISC",
9
25
  "scripts": {
10
- "build": "npx tsc -b",
11
- "dev": "npx tsc -b -w"
26
+ "build": "tsup",
27
+ "dev": "tsup --watch"
12
28
  },
13
29
  "devDependencies": {
14
30
  "@tsconfig/recommended": "^1.0.7",
31
+ "tsup": "^8.2.4",
15
32
  "typescript": "^5.4.5"
16
33
  },
17
34
  "dependencies": {
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { Bkash } from "./lib/bkash";
2
+ import { LemonSqueezy } from "./lib/lemonsqueezy";
3
+ import { Paypal } from "./lib/paypal";
4
+ import { SSLCommerz } from "./lib/sslcommerz";
5
+ import { Stripe } from "./lib/stripe";
6
+
7
+ const UnifyPayment = {
8
+ LemonSqueezy,
9
+ Bkash,
10
+ Paypal,
11
+ SSLCommerz,
12
+ Stripe,
13
+ };
14
+
15
+ export { UnifyPayment };
@@ -0,0 +1,73 @@
1
+ import {
2
+ IBkashAccessTokenResponse,
3
+ IBkashCheckoutOptions,
4
+ IBkashCheckoutResponse,
5
+ IBkashErrorResponse,
6
+ IBkashPayloadProps,
7
+ } from "../types/bkash";
8
+ import { UnifyFetch } from "../utils/fetch";
9
+
10
+ export class Bkash extends UnifyFetch {
11
+ constructor(private options: IBkashPayloadProps) {
12
+ super();
13
+ }
14
+
15
+ private getAppKey() {
16
+ return this.options.app_key;
17
+ }
18
+
19
+ private getApiBaseUrl() {
20
+ return this.options.apiUrl;
21
+ }
22
+
23
+ private getApiRequestHeaders() {
24
+ return {
25
+ "Content-Type": "application/json",
26
+ Accept: "application/json",
27
+ username: this.options.username,
28
+ password: this.options.password,
29
+ };
30
+ }
31
+
32
+ async getAccessToken() {
33
+ const [res] = await this.jsonFetch<
34
+ IBkashAccessTokenResponse | IBkashErrorResponse
35
+ >(`${this.getApiBaseUrl()}/tokenized/checkout/token/grant`, {
36
+ method: "POST",
37
+ headers: this.getApiRequestHeaders(),
38
+ body: JSON.stringify({
39
+ app_key: this.options.app_key,
40
+ app_secret: this.options.app_secret,
41
+ }),
42
+ });
43
+
44
+ if ("errorMessage" in res) {
45
+ throw new Error(res.errorMessage);
46
+ }
47
+
48
+ return res.id_token;
49
+ }
50
+
51
+ async getCheckoutUrl(options: IBkashCheckoutOptions) {
52
+ const accessToken = await this.getAccessToken();
53
+
54
+ const [res] = await this.jsonFetch<
55
+ IBkashCheckoutResponse | IBkashErrorResponse
56
+ >(`${this.getApiBaseUrl()}/tokenized/checkout/create`, {
57
+ method: "POST",
58
+ headers: {
59
+ Accept: "application/json",
60
+ "Content-Type": "application/json",
61
+ "X-App-Key": this.getAppKey(),
62
+ Authorization: `Bearer ${accessToken}`,
63
+ },
64
+ body: JSON.stringify(options),
65
+ });
66
+
67
+ if ("errorMessage" in res) {
68
+ throw new Error(res.errorMessage);
69
+ }
70
+
71
+ return res.bkashURL;
72
+ }
73
+ }
@@ -0,0 +1,83 @@
1
+ import {
2
+ ILemonSqueezyCheckoutOptions,
3
+ TGetCheckoutUrl,
4
+ TWebhookEventResponse,
5
+ } from "../types/lemonsqueezy";
6
+ import { UnifyFetch } from "../utils/fetch";
7
+
8
+ export class LemonSqueezy extends UnifyFetch {
9
+ constructor(private apiKey: string) {
10
+ super();
11
+ }
12
+
13
+ private getApiBaseUrl() {
14
+ return "https://api.lemonsqueezy.com/v1";
15
+ }
16
+
17
+ private getApiRequestHeaders() {
18
+ return {
19
+ Accept: "application/vnd.api+json",
20
+ "Content-Type": "application/vnd.api+json",
21
+ Authorization: `Bearer ${this.apiKey}`,
22
+ };
23
+ }
24
+
25
+ async getCheckoutUrl(options: ILemonSqueezyCheckoutOptions) {
26
+ const [res] = await this.jsonFetch<TGetCheckoutUrl>(
27
+ `${this.getApiBaseUrl()}/checkouts`,
28
+ {
29
+ method: "POST",
30
+ body: JSON.stringify({ data: options }),
31
+ headers: this.getApiRequestHeaders(),
32
+ }
33
+ );
34
+
35
+ if ("errors" in res) {
36
+ throw new Error(res.errors[0].detail);
37
+ }
38
+
39
+ return res.data.attributes.url;
40
+ }
41
+
42
+ async verifySignature(payload: {
43
+ signature: string;
44
+ secret: string;
45
+ body: string;
46
+ x_event: string;
47
+ }): Promise<TWebhookEventResponse> {
48
+ try {
49
+ const encoder = new TextEncoder();
50
+
51
+ const key = await crypto.subtle.importKey(
52
+ "raw",
53
+ encoder.encode(payload.secret),
54
+ { name: "HMAC", hash: "SHA-256" },
55
+ false,
56
+ ["sign"]
57
+ );
58
+
59
+ const hmac = await crypto.subtle.sign(
60
+ "HMAC",
61
+ key,
62
+ encoder.encode(payload.body)
63
+ );
64
+
65
+ const digest = Array.from(new Uint8Array(hmac))
66
+ .map((b) => b.toString(16).padStart(2, "0"))
67
+ .join("");
68
+
69
+ if (digest !== payload.signature) {
70
+ throw new Error("Invalid signature");
71
+ }
72
+
73
+ return {
74
+ event: JSON.parse(payload.body),
75
+ type: payload.x_event as any,
76
+ };
77
+ } catch (err) {
78
+ return {
79
+ error: err as Error,
80
+ };
81
+ }
82
+ }
83
+ }
@@ -0,0 +1,73 @@
1
+ import {
2
+ IPaypalAuthResponse,
3
+ IPaypalOptions,
4
+ IPayPalOrderResponse,
5
+ IPaypalPayload,
6
+ } from "../types/paypal";
7
+ import { UnifyFetch } from "../utils/fetch";
8
+
9
+ export class Paypal extends UnifyFetch {
10
+ constructor(private options: IPaypalOptions) {
11
+ super();
12
+ }
13
+
14
+ private getApiBaseUrl() {
15
+ if (this.options.sandbox) {
16
+ return "https://api-m.sandbox.paypal.com";
17
+ }
18
+ return "https://api.paypal.com";
19
+ }
20
+
21
+ private getClientId() {
22
+ return this.options.clientId;
23
+ }
24
+
25
+ private getClientSecret() {
26
+ return this.options.clientSecret;
27
+ }
28
+
29
+ private getApiCheckoutUrl() {
30
+ return `${this.getApiBaseUrl()}/v2/checkout/orders`;
31
+ }
32
+
33
+ async getAccessToken() {
34
+ const url = `${this.getApiBaseUrl()}/v1/oauth2/token`;
35
+
36
+ const auth = btoa(`${this.getClientId()}:${this.getClientSecret()}`);
37
+
38
+ const [response] = await this.jsonFetch<IPaypalAuthResponse>(url, {
39
+ method: "POST",
40
+ headers: {
41
+ Authorization: `Basic ${auth}`,
42
+ "Content-Type": "application/x-www-form-urlencoded",
43
+ },
44
+ body: "grant_type=client_credentials",
45
+ });
46
+
47
+ return response.access_token;
48
+ }
49
+
50
+ async getCheckoutUrl(payload: IPaypalPayload) {
51
+ const accessToken = await this.getAccessToken();
52
+
53
+ const [res] = await this.jsonFetch<IPayPalOrderResponse>(
54
+ this.getApiCheckoutUrl(),
55
+ {
56
+ method: "POST",
57
+ body: JSON.stringify(payload),
58
+ headers: {
59
+ "Content-Type": "application/json",
60
+ Authorization: `Bearer ${accessToken}`,
61
+ },
62
+ }
63
+ );
64
+
65
+ const url = res.links.find((link) => link.rel === "approve")?.href;
66
+
67
+ if (!url) {
68
+ throw new Error("Failed to get checkout url");
69
+ }
70
+
71
+ return url;
72
+ }
73
+ }