@tonder.io/ionic-lite-sdk 0.0.32-beta → 0.0.33-beta

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.
Files changed (34) hide show
  1. package/.gitlab-ci.yml +28 -28
  2. package/README.md +202 -193
  3. package/dist/classes/3dsHandler.d.ts +36 -0
  4. package/dist/classes/liteCheckout.d.ts +13 -4
  5. package/dist/index.js +1 -1
  6. package/dist/types/requests.d.ts +3 -0
  7. package/dist/types/responses.d.ts +1 -0
  8. package/jest.config.ts +14 -14
  9. package/package.json +38 -38
  10. package/rollup.config.js +16 -16
  11. package/src/classes/3dsHandler.ts +254 -0
  12. package/src/classes/errorResponse.ts +16 -16
  13. package/src/classes/liteCheckout.ts +535 -462
  14. package/src/helpers/utils.ts +12 -12
  15. package/src/index.ts +4 -4
  16. package/src/types/commons.ts +62 -62
  17. package/src/types/requests.ts +93 -89
  18. package/src/types/responses.ts +188 -187
  19. package/src/types/skyflow.ts +17 -17
  20. package/tests/classes/liteCheckout.test.ts +57 -57
  21. package/tests/methods/createOrder.test.ts +142 -142
  22. package/tests/methods/createPayment.test.ts +122 -122
  23. package/tests/methods/customerRegister.test.ts +119 -119
  24. package/tests/methods/getBusiness.test.ts +115 -115
  25. package/tests/methods/getCustomerCards.test.ts +117 -117
  26. package/tests/methods/getOpenpayDeviceSessionID.test.ts +94 -94
  27. package/tests/methods/getSkyflowToken.test.ts +154 -154
  28. package/tests/methods/getVaultToken.test.ts +106 -106
  29. package/tests/methods/registerCustomerCard.test.ts +117 -117
  30. package/tests/methods/startCheckoutRouter.test.ts +119 -119
  31. package/tests/methods/startCheckoutRouterFull.test.ts +138 -138
  32. package/tests/utils/defaultMock.ts +20 -20
  33. package/tests/utils/mockClasses.ts +651 -649
  34. package/tsconfig.json +18 -18
package/.gitlab-ci.yml CHANGED
@@ -1,29 +1,29 @@
1
- image: grupoapok/awscli:18
2
-
3
- stages:
4
- - test
5
- - deploy
6
-
7
- test:
8
- stage: test
9
- only:
10
- - development
11
- before_script:
12
- - npm install
13
- script:
14
- - npm run test
15
-
16
- deploy:
17
- stage: deploy
18
- only:
19
- - tags
20
- before_script:
21
- - |
22
- {
23
- echo "@tonder.io:registry=https://registry.npmjs.org/"
24
- echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}"
25
- } | tee -a .npmrc
26
- script:
27
- - npm install
28
- - npm run build
1
+ image: grupoapok/awscli:18
2
+
3
+ stages:
4
+ - test
5
+ - deploy
6
+
7
+ test:
8
+ stage: test
9
+ only:
10
+ - development
11
+ before_script:
12
+ - npm install
13
+ script:
14
+ - npm run test
15
+
16
+ deploy:
17
+ stage: deploy
18
+ only:
19
+ - tags
20
+ before_script:
21
+ - |
22
+ {
23
+ echo "@tonder.io:registry=https://registry.npmjs.org/"
24
+ echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}"
25
+ } | tee -a .npmrc
26
+ script:
27
+ - npm install
28
+ - npm run build
29
29
  - npm publish --access=public
package/README.md CHANGED
@@ -1,193 +1,202 @@
1
- # Tonder SDK
2
-
3
- Tonder SDK Lite to integrate REST service
4
-
5
- ## Installation
6
-
7
- You can install using NPM
8
- ```bash
9
- npm i @tonder.io/ionic-lite-sdk
10
- ```
11
-
12
- Add dependencies to the root of the app (index.html)
13
- ```html
14
- <script src=https://openpay.s3.amazonaws.com/openpay.v1.min.js></script>
15
- <script src=https://openpay.s3.amazonaws.com/openpay-data.v1.min.js></script>
16
- ```
17
-
18
- ## Usage
19
- ## Import LiteCheckout class
20
- ```javascript
21
- import { LiteCheckout } from "@tonder.io/ionic-lite-sdk"
22
- ```
23
- ## Create instance
24
-
25
- ```javascript
26
- const liteCheckout = new LiteCheckout({
27
- signal,
28
- baseUrlTonder,
29
- apiKeyTonder
30
- })
31
- ```
32
-
33
- | Property | Type | Description |
34
- |:---------------:|:-------------:|:-----------------------------------------------------------------------:|
35
- | signal | AborSignal | Signal from AbortController instance if it need cancel request |
36
- | baseUrlTonder | string | Live server: http://stage.tonder.io |
37
- | | | Mock Server: https://stoplight.io/mocks/tonder/tonder-api-v1-2/3152148 |
38
- | apiKeyTonder | string | You can take this from you Tonder Dashboard |
39
- | | | |
40
-
41
- # Class methods
42
-
43
- # Checkout router
44
-
45
- ```typescript
46
-
47
- const returnUrl = "http://localhost:8100/payment/success";
48
-
49
- let checkoutData = {
50
- customer: {
51
- name: "Jhon",
52
- lastname: "Doe",
53
- email: "john.c.calhoun@examplepetstore.com",
54
- phone: "+58452258525"
55
- },
56
- order: {
57
- items: [
58
- {
59
- description: "Test product description",
60
- quantity: 1,
61
- price_unit: 25,
62
- discount: 1,
63
- taxes: 12,
64
- product_reference: 89456123,
65
- name: "Test product",
66
- amount_total: 25
67
- }
68
- ]
69
- },
70
- return_url: returnUrl,
71
- total: 25,
72
- isSandbox: true,
73
- metadata: {},
74
- currency: "MXN",
75
- skyflowTokens: {
76
- cardholder_name: "",
77
- card_number: "",
78
- expiration_year: "",
79
- expiration_month: "",
80
- cvv: "",
81
- skyflow_id: ""
82
- }
83
- }
84
-
85
- ```
86
-
87
- <font size="4">It is required get the skyflow tokens to add it to the checkout router method, the values of the variable skyflowFields come from your html form</font>
88
-
89
- ```typescript
90
-
91
- const merchantData: any = await liteCheckout.getBusiness();
92
-
93
- const { vault_id, vault_url } = merchantData;
94
-
95
- const skyflowFields = {
96
- card_number: this.paymentForm.value.cardNumber,
97
- cvv: this.paymentForm.value.cvv,
98
- expiration_month: this.paymentForm.value.month,
99
- expiration_year: this.paymentForm.value.expirationYear,
100
- cardholder_name: this.paymentForm.value.name
101
- }
102
-
103
- const skyflowTokens = await liteCheckout.getSkyflowTokens({
104
- vault_id: vault_id,
105
- vault_url: vault_url,
106
- data: skyflowFields
107
- })
108
-
109
- checkoutData.skyflowTokens = skyflowTokens;
110
-
111
- const jsonResponseRouter: any = await liteCheckout.startCheckoutRouterFull(
112
- checkoutData
113
- );
114
-
115
- ```
116
-
117
- <font size="4">Take actions on base to the checkout router response</font>
118
-
119
- # Customer Cards(Register)
120
-
121
- ## Register customer card
122
-
123
- ```typescript
124
-
125
- customer_auth_token: string;
126
-
127
- data: {
128
- skyflow_id: string;
129
- };
130
-
131
- const jsonResponseOrder = await liteCheckout.registerCustomerCard(
132
- customer_auth_token,
133
- data
134
- );
135
- ```
136
-
137
- ## Return register customer card
138
- ```typescript
139
- {
140
- skyflow_id: string;
141
- user_id: number;
142
- }
143
- ```
144
-
145
- # Customer Cards(Get)
146
-
147
- ## Get customer cards
148
-
149
- ```typescript
150
-
151
- customer_auth_token: string;
152
-
153
- query: string = "?ordering=<string>&search=<string>";
154
-
155
- const jsonResponseOrder = await liteCheckout.getCustomerCards(
156
- customer_auth_token,
157
- query
158
- );
159
- ```
160
-
161
- ## Return get customer cards
162
- ```typescript
163
- {
164
- user_id: number,
165
- cards: [
166
- {
167
- fields: {
168
- card_number: string,
169
- cardholder_name: string,
170
- cvv: string,
171
- expiration_month: string,
172
- expiration_year: string,
173
- skyflow_id: string
174
- }
175
- }
176
- ]
177
- }
178
- ```
179
-
180
- ## Delete customer card
181
-
182
- ```typescript
183
-
184
- const deleted: boolean = await liteCheckout.deleteCustomerCard(
185
- customer_auth_token,
186
- skyflow_id
187
- );
188
-
189
- ```
190
-
191
- ## License
192
-
193
- [MIT](https://choosealicense.com/licenses/mit/)
1
+ # Tonder SDK
2
+
3
+ Tonder SDK Lite to integrate REST service
4
+
5
+ ## Installation
6
+
7
+ You can install using NPM
8
+ ```bash
9
+ npm i @tonder.io/ionic-lite-sdk
10
+ ```
11
+
12
+ Add dependencies to the root of the app (index.html)
13
+ ```html
14
+ <script src=https://openpay.s3.amazonaws.com/openpay.v1.min.js></script>
15
+ <script src=https://openpay.s3.amazonaws.com/openpay-data.v1.min.js></script>
16
+ ```
17
+
18
+ ## Usage
19
+ ## Import LiteCheckout class
20
+ ```javascript
21
+ import { LiteCheckout } from "@tonder.io/ionic-lite-sdk"
22
+ ```
23
+ ## Create instance
24
+
25
+ ```javascript
26
+ const liteCheckout = new LiteCheckout({
27
+ signal,
28
+ baseUrlTonder,
29
+ apiKeyTonder
30
+ })
31
+
32
+ // To verify a 3ds transaction you can use the following method
33
+ // It should be called after the injectCheckout method
34
+ // The response status will be one of the following
35
+ // ['Declined', 'Cancelled', 'Failed', 'Success', 'Pending', 'Authorized']
36
+
37
+ inlineCheckout.verify3dsTransaction().then(response => {
38
+ console.log('Verify 3ds response', response)
39
+ })
40
+ ```
41
+
42
+ | Property | Type | Description |
43
+ |:---------------:|:-------------:|:-----------------------------------------------------------------------:|
44
+ | signal | AborSignal | Signal from AbortController instance if it need cancel request |
45
+ | baseUrlTonder | string | Live server: http://stage.tonder.io |
46
+ | | | Mock Server: https://stoplight.io/mocks/tonder/tonder-api-v1-2/3152148 |
47
+ | apiKeyTonder | string | You can take this from you Tonder Dashboard |
48
+ | | | |
49
+
50
+ # Class methods
51
+
52
+ # Checkout router
53
+
54
+ ```typescript
55
+
56
+ const returnUrl = "http://localhost:8100/payment/success";
57
+
58
+ let checkoutData = {
59
+ customer: {
60
+ name: "Jhon",
61
+ lastname: "Doe",
62
+ email: "john.c.calhoun@examplepetstore.com",
63
+ phone: "+58452258525"
64
+ },
65
+ order: {
66
+ items: [
67
+ {
68
+ description: "Test product description",
69
+ quantity: 1,
70
+ price_unit: 25,
71
+ discount: 1,
72
+ taxes: 12,
73
+ product_reference: 89456123,
74
+ name: "Test product",
75
+ amount_total: 25
76
+ }
77
+ ]
78
+ },
79
+ return_url: returnUrl,
80
+ total: 25,
81
+ isSandbox: true,
82
+ metadata: {},
83
+ currency: "MXN",
84
+ skyflowTokens: {
85
+ cardholder_name: "",
86
+ card_number: "",
87
+ expiration_year: "",
88
+ expiration_month: "",
89
+ cvv: "",
90
+ skyflow_id: ""
91
+ }
92
+ }
93
+
94
+ ```
95
+
96
+ <font size="4">It is required get the skyflow tokens to add it to the checkout router method, the values of the variable skyflowFields come from your html form</font>
97
+
98
+ ```typescript
99
+
100
+ const merchantData: any = await liteCheckout.getBusiness();
101
+
102
+ const { vault_id, vault_url } = merchantData;
103
+
104
+ const skyflowFields = {
105
+ card_number: this.paymentForm.value.cardNumber,
106
+ cvv: this.paymentForm.value.cvv,
107
+ expiration_month: this.paymentForm.value.month,
108
+ expiration_year: this.paymentForm.value.expirationYear,
109
+ cardholder_name: this.paymentForm.value.name
110
+ }
111
+
112
+ const skyflowTokens = await liteCheckout.getSkyflowTokens({
113
+ vault_id: vault_id,
114
+ vault_url: vault_url,
115
+ data: skyflowFields
116
+ })
117
+
118
+ checkoutData.skyflowTokens = skyflowTokens;
119
+
120
+ const jsonResponseRouter: any = await liteCheckout.startCheckoutRouterFull(
121
+ checkoutData
122
+ );
123
+
124
+ ```
125
+
126
+ <font size="4">Take actions on base to the checkout router response</font>
127
+
128
+ # Customer Cards(Register)
129
+
130
+ ## Register customer card
131
+
132
+ ```typescript
133
+
134
+ customer_auth_token: string;
135
+
136
+ data: {
137
+ skyflow_id: string;
138
+ };
139
+
140
+ const jsonResponseOrder = await liteCheckout.registerCustomerCard(
141
+ customer_auth_token,
142
+ data
143
+ );
144
+ ```
145
+
146
+ ## Return register customer card
147
+ ```typescript
148
+ {
149
+ skyflow_id: string;
150
+ user_id: number;
151
+ }
152
+ ```
153
+
154
+ # Customer Cards(Get)
155
+
156
+ ## Get customer cards
157
+
158
+ ```typescript
159
+
160
+ customer_auth_token: string;
161
+
162
+ query: string = "?ordering=<string>&search=<string>";
163
+
164
+ const jsonResponseOrder = await liteCheckout.getCustomerCards(
165
+ customer_auth_token,
166
+ query
167
+ );
168
+ ```
169
+
170
+ ## Return get customer cards
171
+ ```typescript
172
+ {
173
+ user_id: number,
174
+ cards: [
175
+ {
176
+ fields: {
177
+ card_number: string,
178
+ cardholder_name: string,
179
+ cvv: string,
180
+ expiration_month: string,
181
+ expiration_year: string,
182
+ skyflow_id: string
183
+ }
184
+ }
185
+ ]
186
+ }
187
+ ```
188
+
189
+ ## Delete customer card
190
+
191
+ ```typescript
192
+
193
+ const deleted: boolean = await liteCheckout.deleteCustomerCard(
194
+ customer_auth_token,
195
+ skyflow_id
196
+ );
197
+
198
+ ```
199
+
200
+ ## License
201
+
202
+ [MIT](https://choosealicense.com/licenses/mit/)
@@ -0,0 +1,36 @@
1
+ type ThreeDSHandlerContructor = {
2
+ payload?: any;
3
+ apiKey?: string;
4
+ baseUrl?: string;
5
+ successUrl?: Location | string;
6
+ };
7
+ export declare class ThreeDSHandler {
8
+ baseUrl?: string;
9
+ apiKey?: string;
10
+ payload?: any;
11
+ successUrl?: Location | string;
12
+ localStorageKey: string;
13
+ constructor({ payload, apiKey, baseUrl, successUrl }: ThreeDSHandlerContructor);
14
+ setStorageItem(data: any): void;
15
+ getStorageItem(): string | null;
16
+ removeStorageItem(): void;
17
+ saveVerifyTransactionUrl(): void;
18
+ saveUrlWithExpiration(url: string): void;
19
+ saveCheckoutId(checkoutId: any): void;
20
+ removeCheckoutId(): void;
21
+ getCurrentCheckoutId(): any;
22
+ getUrlWithExpiration(): any;
23
+ removeVerifyTransactionUrl(): void;
24
+ getVerifyTransactionUrl(): string | null;
25
+ loadIframe(): Promise<unknown> | undefined;
26
+ getRedirectUrl(): any;
27
+ redirectToChallenge(): void;
28
+ getURLParameters(): any;
29
+ handleSuccessTransaction(response: any): any;
30
+ handleDeclinedTransaction(response: any): any;
31
+ handle3dsChallenge(response_json: any): Promise<void>;
32
+ handleTransactionResponse(response: any): Promise<any>;
33
+ verifyTransactionStatus(): Promise<any>;
34
+ setPayload: (payload: any) => void;
35
+ }
36
+ export {};
@@ -1,7 +1,8 @@
1
1
  import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
2
- import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest } from "../types/requests";
2
+ import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
3
3
  import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
4
4
  import { ErrorResponse } from "./errorResponse";
5
+ import { ThreeDSHandler } from "./3dsHandler";
5
6
  declare global {
6
7
  interface Window {
7
8
  OpenPay: any;
@@ -11,19 +12,27 @@ export type LiteCheckoutConstructor = {
11
12
  signal: AbortSignal;
12
13
  baseUrlTonder: string;
13
14
  apiKeyTonder: string;
15
+ successUrl?: string;
14
16
  };
15
17
  export declare class LiteCheckout implements LiteCheckoutConstructor {
16
18
  signal: AbortSignal;
17
19
  baseUrlTonder: string;
18
20
  apiKeyTonder: string;
19
- constructor({ signal, baseUrlTonder, apiKeyTonder, }: LiteCheckoutConstructor);
21
+ process3ds: ThreeDSHandler;
22
+ successUrl?: string;
23
+ constructor({ signal, baseUrlTonder, apiKeyTonder, successUrl, }: LiteCheckoutConstructor);
20
24
  getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
21
25
  getBusiness(): Promise<GetBusinessResponse | ErrorResponse>;
26
+ verify3dsTransaction(): Promise<any>;
27
+ resumeCheckout(response: any): Promise<any>;
28
+ handle3dsRedirect(response: ErrorResponse | StartCheckoutResponse | false | undefined): Promise<false | StartCheckoutResponse | ErrorResponse | undefined>;
22
29
  customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse>;
23
30
  createOrder(orderItems: CreateOrderRequest): Promise<CreateOrderResponse | ErrorResponse>;
24
31
  createPayment(paymentItems: CreatePaymentRequest): Promise<CreatePaymentResponse | ErrorResponse>;
25
- startCheckoutRouter(routerData: StartCheckoutRequest): Promise<StartCheckoutResponse | ErrorResponse>;
26
- startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse>;
32
+ handleCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest): Promise<StartCheckoutResponse>;
33
+ startCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined>;
34
+ startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined>;
35
+ init3DSRedirect(checkoutResult: ErrorResponse | StartCheckoutResponse): Promise<false | StartCheckoutResponse | ErrorResponse | undefined>;
27
36
  getSkyflowTokens({ vault_id, vault_url, data, }: TokensRequest): Promise<any | ErrorResponse>;
28
37
  getVaultToken(): Promise<string>;
29
38
  getFieldsPromise(data: any, collectContainer: CollectContainer): Promise<Promise<boolean>[]>;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import e from"skyflow-js";function t(e,t,i,r){return new(i||(i=Promise))((function(o,n){function s(e){try{a(r.next(e))}catch(e){n(e)}}function d(e){try{a(r.throw(e))}catch(e){n(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,d)}a((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class i{constructor({code:e,body:t,name:i,message:r,stack:o}){this.code=e,this.body=t,this.name=i,this.message=r,this.stack=o}}class r{constructor({signal:e,baseUrlTonder:t,apiKeyTonder:i}){this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=i}getOpenpayDeviceSessionID(e,i,r){return t(this,void 0,void 0,(function*(){try{let t=yield window.OpenPay;return t.setId(e),t.setApiKey(i),t.setSandboxMode(r),yield t.deviceData.setup({signal:this.signal})}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,{headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(e.ok)return yield e.json();throw yield this.buildErrorResponse(e)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/customer/`,i={email:e},r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal,body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/orders/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/business/${e.business_pk}/payments/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/checkout-router/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:n,return_url:s,isSandbox:d,metadata:a,currency:l}=e,h=yield this.getBusiness(),c=yield this.customerRegister(o.email);if(c&&"auth_token"in c&&h&&"reference"in h){const e={business:this.apiKeyTonder,client:c.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},u=yield this.createOrder(e),y=(new Date).toISOString();if("id"in u&&"id"in c&&"business"in h){const e={business_pk:h.business.pk,amount:r,date:y,order_id:u.id,client_id:c.id},t=yield this.createPayment(e);let i;const{openpay_keys:p,business:m}=h;p.merchant_id&&p.public_key&&(i=yield this.getOpenpayDeviceSessionID(p.merchant_id,p.public_key,d));const v={card:n,name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:i||null,token_id:"",order_id:"id"in u&&u.id,business_id:m.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:a,browser_info:{javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent},currency:l};return yield this.startCheckoutRouter(v)}throw new i({code:"500",body:u,name:"Keys error",message:"Order response errors"})}throw new i({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"})}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getSkyflowTokens({vault_id:i,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){const n=e.init({vaultID:i,vaultURL:r,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield this.getVaultToken()})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),s=yield this.getFieldsPromise(o,n);if((yield Promise.all(s)).some((e=>!e)))throw this.buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield n.collect();if(e)return e.records[0].fields;throw this.buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getVaultToken(){var e;return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(t.ok)return null===(e=yield t.json())||void 0===e?void 0:e.token;throw new Error(`HTTPCODE: ${t.status}`)}catch(e){throw new Error(`Failed to retrieve bearer token; ${"string"==typeof e?e:e.message}`)}}))}getFieldsPromise(e,i){return t(this,void 0,void 0,(function*(){const t=yield this.getFields(e,i);return t?t.map((t=>new Promise((i=>{var r;const o=document.createElement("div");o.hidden=!0,o.id=`id-${t.key}`,null===(r=document.querySelector("body"))||void 0===r||r.appendChild(o),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const r=e[t.key];return t.element.update({value:r}),i(t.element.isMounted())}}),120)}),120)})))):[]}))}registerCustomerCard(e,i){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal,body:JSON.stringify(i)});if(t.ok)return yield t.json();throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getCustomerCards(e,i=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/${i}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return yield t.json();throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}deleteCustomerCard(e,i=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/${i}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return!0;throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}buildErrorResponseFromCatch(e){return new i({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack})}buildErrorResponse(e,r=void 0){return t(this,void 0,void 0,(function*(){let t,o,n="Error";e&&"json"in e&&(t=yield null==e?void 0:e.json()),e&&"status"in e&&(o=e.status.toString()),e&&"text"in e&&(n=yield e.text());return new i({code:o,body:t,name:o,message:n,stack:r})}))}getFields(i,r){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(i).map((i=>t(this,void 0,void 0,(function*(){return{element:yield r.create({table:"cards",column:i,type:e.ElementType.INPUT_FIELD}),key:i}})))))}))}}export{r as LiteCheckout};
1
+ import e from"skyflow-js";function t(e,t,i,r){return new(i||(i=Promise))((function(o,n){function s(e){try{d(r.next(e))}catch(e){n(e)}}function a(e){try{d(r.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}d((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class i{constructor({code:e,body:t,name:i,message:r,stack:o}){this.code=e,this.body=t,this.name=i,this.message=r,this.stack=o}}class r{constructor({payload:e=null,apiKey:t,baseUrl:i,successUrl:r}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=i,this.apiKey=t,this.payload=e,this.successUrl=r}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,i,r,o,n;const s=null===(i=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===i?void 0:i.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(n=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===n?void 0:n.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}saveCheckoutId(e){localStorage.setItem("checkout_id",JSON.stringify(e))}removeCheckoutId(){localStorage.removeItem("checkout_id")}getCurrentCheckoutId(){const e=localStorage.getItem("checkout_id");return e?JSON.parse(e):null}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,i;if(null===(i=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===i?void 0:i.iframe)return new Promise(((e,t)=>{var i,r,o;const n=null===(o=null===(r=null===(i=this.payload)||void 0===i?void 0:i.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe;if(n){this.saveVerifyTransactionUrl();const i=document.createElement("div");i.innerHTML=n,document.body.appendChild(i);const r=document.createElement("script");r.textContent='document.getElementById("tdsMmethodForm").submit();',i.appendChild(r);const o=document.getElementById("tdsMmethodTgtFrame");o?o.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,i;return null===(i=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===i?void 0:i.url}redirectToChallenge(){const e=this.getRedirectUrl();e?(this.saveVerifyTransactionUrl(),window.location=e):console.log("No redirection found")}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[i,r]of t)e[i]=r;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const i=document.createElement("input");i.type="hidden",i.name=e.creq,i.value=e.creq,t.appendChild(i);const r=document.createElement("input");r.type="hidden",r.name=e.term_url,r.value=e.TermUrl,t.appendChild(r),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}class o{constructor({signal:e,baseUrlTonder:t,apiKeyTonder:i,successUrl:o}){this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=i,this.successUrl=o,this.process3ds=new r({apiKey:this.apiKeyTonder,baseUrl:this.baseUrlTonder,successUrl:o})}getOpenpayDeviceSessionID(e,i,r){return t(this,void 0,void 0,(function*(){try{let t=yield window.OpenPay;return t.setId(e),t.setApiKey(i),t.setSandboxMode(r),yield t.deviceData.setup({signal:this.signal})}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,{headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(e.ok)return yield e.json();throw yield this.buildErrorResponse(e)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield this.resumeCheckout(e);return this.process3ds.setPayload(t),t&&"is_route_finished"in t&&"provider"in t&&"tonder"===t.provider?t:this.handle3dsRedirect(t)}))}resumeCheckout(e){return t(this,void 0,void 0,(function*(){if(["Failed","Declined","Cancelled"].includes(null==e?void 0:e.status)){const e={checkout_id:this.process3ds.getCurrentCheckoutId()};return yield this.handleCheckoutRouter(e)}return e}))}handle3dsRedirect(e){var i,r;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(r=null===(i=null==e?void 0:e.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===r?void 0:r.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/customer/`,i={email:e},r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal,body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/orders/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/business/${e.business_pk}/payments/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}handleCheckoutRouter(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/checkout-router/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield this.handleCheckoutRouter(e);if(yield this.init3DSRedirect(t))return t}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:n,return_url:s,isSandbox:a,metadata:d,currency:l}=e,c=yield this.getBusiness(),u=yield this.customerRegister(o.email);if(!(u&&"auth_token"in u&&c&&"reference"in c))throw new i({code:"500",body:c,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:u.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:c.reference,is_oneclick:!0,items:t.items},h=yield this.createOrder(e),y=(new Date).toISOString();if(!("id"in h&&"id"in u&&"business"in c))throw new i({code:"500",body:h,name:"Keys error",message:"Order response errors"});{const e={business_pk:c.business.pk,amount:r,date:y,order_id:h.id,client_id:u.id},t=yield this.createPayment(e);let i;const{openpay_keys:p,business:v}=c;p.merchant_id&&p.public_key&&(i=yield this.getOpenpayDeviceSessionID(p.merchant_id,p.public_key,a));const m={card:n,name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:i||null,token_id:"",order_id:"id"in h&&h.id,business_id:v.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:{javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent},currency:l},f=yield this.handleCheckoutRouter(m);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),this.process3ds.saveCheckoutId(e&&"checkout_id"in e?e.checkout_id:""),yield this.handle3dsRedirect(e)}))}getSkyflowTokens({vault_id:i,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){const n=e.init({vaultID:i,vaultURL:r,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield this.getVaultToken()})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),s=yield this.getFieldsPromise(o,n);if((yield Promise.all(s)).some((e=>!e)))throw this.buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield n.collect();if(e)return e.records[0].fields;throw this.buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getVaultToken(){var e;return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(t.ok)return null===(e=yield t.json())||void 0===e?void 0:e.token;throw new Error(`HTTPCODE: ${t.status}`)}catch(e){throw new Error(`Failed to retrieve bearer token; ${"string"==typeof e?e:e.message}`)}}))}getFieldsPromise(e,i){return t(this,void 0,void 0,(function*(){const t=yield this.getFields(e,i);return t?t.map((t=>new Promise((i=>{var r;const o=document.createElement("div");o.hidden=!0,o.id=`id-${t.key}`,null===(r=document.querySelector("body"))||void 0===r||r.appendChild(o),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const r=e[t.key];return t.element.update({value:r}),i(t.element.isMounted())}}),120)}),120)})))):[]}))}registerCustomerCard(e,i){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal,body:JSON.stringify(i)});if(t.ok)return yield t.json();throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getCustomerCards(e,i=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/${i}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return yield t.json();throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}deleteCustomerCard(e,i=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/${i}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return!0;throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}buildErrorResponseFromCatch(e){return new i({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack})}buildErrorResponse(e,r=void 0){return t(this,void 0,void 0,(function*(){let t,o,n="Error";e&&"json"in e&&(t=yield null==e?void 0:e.json()),e&&"status"in e&&(o=e.status.toString()),e&&"text"in e&&(n=yield e.text());return new i({code:o,body:t,name:o,message:n,stack:r})}))}getFields(i,r){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(i).map((i=>t(this,void 0,void 0,(function*(){return{element:yield r.create({table:"cards",column:i,type:e.ElementType.INPUT_FIELD}),key:i}})))))}))}}export{o as LiteCheckout};
@@ -42,6 +42,9 @@ export type StartCheckoutRequest = {
42
42
  metadata: any;
43
43
  currency: string;
44
44
  };
45
+ export type StartCheckoutIdRequest = {
46
+ checkout_id: any;
47
+ };
45
48
  export interface VaultRequest extends SkyflowRecord {
46
49
  records: SkyflowRecord[];
47
50
  continueOnError?: boolean;
@@ -133,6 +133,7 @@ export type StartCheckoutResponse = {
133
133
  method: string;
134
134
  object: string;
135
135
  };
136
+ is_route_finished: Boolean;
136
137
  transaction_status: string;
137
138
  transaction_id: number;
138
139
  payment_id: number;
package/jest.config.ts CHANGED
@@ -1,15 +1,15 @@
1
- import type { JestConfigWithTsJest } from 'ts-jest'
2
-
3
- const jestConfig: JestConfigWithTsJest = {
4
- testEnvironment: "jsdom",
5
- preset: 'ts-jest',
6
- transform: {
7
- '^.+\\.tsx?$': [
8
- 'ts-jest',
9
- {
10
- },
11
- ],
12
- },
13
- }
14
-
1
+ import type { JestConfigWithTsJest } from 'ts-jest'
2
+
3
+ const jestConfig: JestConfigWithTsJest = {
4
+ testEnvironment: "jsdom",
5
+ preset: 'ts-jest',
6
+ transform: {
7
+ '^.+\\.tsx?$': [
8
+ 'ts-jest',
9
+ {
10
+ },
11
+ ],
12
+ },
13
+ }
14
+
15
15
  export default jestConfig