@tonder.io/ionic-lite-sdk 0.0.42-beta.1 → 0.0.42-beta.3

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 (55) hide show
  1. package/.gitlab-ci.yml +28 -28
  2. package/README.md +532 -532
  3. package/dist/classes/BaseInlineCheckout.d.ts +1 -1
  4. package/dist/classes/liteCheckout.d.ts +1 -1
  5. package/dist/data/cardApi.d.ts +3 -3
  6. package/dist/index.js +1 -1
  7. package/dist/types/liteInlineCheckout.d.ts +1 -1
  8. package/jest.config.ts +14 -14
  9. package/package.json +41 -41
  10. package/rollup.config.js +16 -16
  11. package/src/classes/3dsHandler.ts +347 -347
  12. package/src/classes/BaseInlineCheckout.ts +424 -424
  13. package/src/classes/errorResponse.ts +16 -16
  14. package/src/classes/liteCheckout.ts +589 -591
  15. package/src/data/api.ts +20 -20
  16. package/src/data/businessApi.ts +18 -18
  17. package/src/data/cardApi.ts +91 -87
  18. package/src/data/checkoutApi.ts +84 -84
  19. package/src/data/customerApi.ts +31 -31
  20. package/src/data/openPayApi.ts +12 -12
  21. package/src/data/paymentMethodApi.ts +37 -37
  22. package/src/data/skyflowApi.ts +20 -20
  23. package/src/helpers/constants.ts +63 -63
  24. package/src/helpers/mercadopago.ts +15 -15
  25. package/src/helpers/skyflow.ts +91 -91
  26. package/src/helpers/utils.ts +120 -120
  27. package/src/helpers/validations.ts +55 -55
  28. package/src/index.ts +12 -12
  29. package/src/shared/catalog/paymentMethodsCatalog.ts +247 -247
  30. package/src/shared/constants/messages.ts +10 -10
  31. package/src/shared/constants/paymentMethodAPM.ts +63 -63
  32. package/src/shared/constants/tonderUrl.ts +8 -8
  33. package/src/types/card.ts +35 -35
  34. package/src/types/checkout.ts +123 -123
  35. package/src/types/commons.ts +143 -143
  36. package/src/types/customer.ts +22 -22
  37. package/src/types/liteInlineCheckout.ts +216 -216
  38. package/src/types/paymentMethod.ts +23 -23
  39. package/src/types/requests.ts +114 -114
  40. package/src/types/responses.ts +192 -192
  41. package/src/types/skyflow.ts +17 -17
  42. package/src/types/transaction.ts +101 -101
  43. package/src/types/validations.d.ts +11 -11
  44. package/tests/classes/liteCheckout.test.ts +57 -57
  45. package/tests/methods/createOrder.test.ts +141 -141
  46. package/tests/methods/createPayment.test.ts +121 -121
  47. package/tests/methods/customerRegister.test.ts +118 -118
  48. package/tests/methods/getBusiness.test.ts +114 -114
  49. package/tests/methods/getCustomerCards.test.ts +112 -112
  50. package/tests/methods/registerCustomerCard.test.ts +117 -117
  51. package/tests/methods/startCheckoutRouter.test.ts +119 -119
  52. package/tests/methods/startCheckoutRouterFull.test.ts +138 -138
  53. package/tests/utils/defaultMock.ts +21 -21
  54. package/tests/utils/mockClasses.ts +659 -659
  55. package/tsconfig.json +18 -18
@@ -1,424 +1,424 @@
1
- import { ThreeDSHandler } from "./3dsHandler";
2
- import { ErrorResponse } from "./errorResponse";
3
- import { fetchBusiness } from "../data/businessApi";
4
- import { injectMercadoPagoSecurity } from "../helpers/mercadopago";
5
- import { TONDER_URL_BY_MODE } from "../shared/constants/tonderUrl";
6
- import {
7
- createOrder,
8
- createPayment,
9
- startCheckoutRouter,
10
- } from "../data/checkoutApi";
11
- import { getOpenpayDeviceSessionID } from "../data/openPayApi";
12
- import { getBrowserInfo } from "../helpers/utils";
13
- import { registerOrFetchCustomer } from "../data/customerApi";
14
- import { get } from "lodash";
15
- import {
16
- fetchCustomerCards,
17
- removeCustomerCard,
18
- saveCustomerCard,
19
- } from "../data/cardApi";
20
- import { fetchCustomerPaymentMethods } from "../data/paymentMethodApi";
21
- import {Business, IConfigureCheckout, IInlineCheckoutBaseOptions, CustomizationOptions} from "../types/commons";
22
- import {ICustomer} from "../types/customer";
23
- import {ICardFields, IItem, IProcessPaymentRequest, IStartCheckoutResponse} from "../types/checkout";
24
- import {ICustomerCardsResponse, ISaveCardResponse, ISaveCardSkyflowRequest} from "../types/card";
25
- import {IPaymentMethodResponse} from "../types/paymentMethod";
26
- import {ITransaction} from "../types/transaction";
27
- export class BaseInlineCheckout {
28
- baseUrl = "";
29
- cartTotal: string | number = "0";
30
- process3ds: ThreeDSHandler;
31
- mode?: "production" | "sandbox" | "stage" | "development" | undefined;
32
- apiKeyTonder: string;
33
- returnUrl?: string;
34
- tdsIframeId?: string;
35
- tonderPayButtonId?: string;
36
- callBack?: ((response: IStartCheckoutResponse | Record<string, any>) => void) | undefined;
37
- merchantData?: Business;
38
- abortController: AbortController;
39
- secureToken: string = "";
40
- customer?: ICustomer | { email: string };
41
- customization: CustomizationOptions = {
42
- saveCards: {
43
- showSaveCardOption: true,
44
- showSaved: true,
45
- autoSave: false
46
- },
47
- redirectOnComplete: true
48
- }
49
-
50
- cartItems?: IItem[];
51
- metadata = {};
52
- card? = {};
53
- currency?: string = "";
54
-
55
- #customerData?: Record<string, any>;
56
-
57
- constructor({
58
- mode = "stage",
59
- customization,
60
- apiKey,
61
- apiKeyTonder,
62
- returnUrl,
63
- tdsIframeId,
64
- callBack = () => {},
65
- baseUrlTonder,
66
- tonderPayButtonId
67
- }: IInlineCheckoutBaseOptions) {
68
- this.apiKeyTonder = apiKeyTonder || apiKey || "";
69
- this.returnUrl = returnUrl;
70
- this.callBack = callBack;
71
- this.mode = mode;
72
- this.customer = {} as ICustomer
73
- this.baseUrl = baseUrlTonder || TONDER_URL_BY_MODE[this.mode] || TONDER_URL_BY_MODE["stage"];
74
- this.abortController = new AbortController();
75
- this.process3ds = new ThreeDSHandler({
76
- apiKey: apiKey,
77
- baseUrl: this.baseUrl,
78
- customization: customization,
79
- tdsIframeId: tdsIframeId,
80
- tonderPayButtonId: tonderPayButtonId,
81
- callBack: callBack
82
- });
83
- this.tdsIframeId = tdsIframeId;
84
- this.customization = {
85
- ...this.customization,
86
- ...(customization || {}),
87
- saveCards: {
88
- ...this.customization.saveCards,
89
- ...(customization?.saveCards || {})
90
- }
91
- }
92
- }
93
-
94
- configureCheckout(data: IConfigureCheckout) {
95
- if ("customer" in data) this.#handleCustomer(data["customer"]);
96
- if ("secureToken" in data) this.#setSecureToken(data["secureToken"]);
97
- }
98
-
99
- async verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void> {
100
- const result3ds = await this.process3ds.verifyTransactionStatus();
101
- const resultCheckout = await this.#resumeCheckout(result3ds);
102
- this.process3ds.setPayload(resultCheckout);
103
- return this._handle3dsRedirect(resultCheckout);
104
- }
105
-
106
- payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse> {
107
- return new Promise(async (resolve, reject) => {
108
- try {
109
- this.#handleCustomer(data.customer);
110
- this._setCartTotal(data.cart?.total);
111
- this.#setCartItems(data.cart?.items);
112
- this.#handleMetadata(data);
113
- this.#handleCurrency(data);
114
- this.#handleCard(data);
115
- const response = await this._checkout(data);
116
- this.process3ds.setPayload(response);
117
- const payload = await this._handle3dsRedirect(response);
118
- if (payload) {
119
- try {
120
- const selector: any = document.querySelector(`#${this.tonderPayButtonId}`);
121
- if(selector) {
122
- selector.disabled = false;
123
- }
124
- } catch {}
125
- if (this.callBack) this.callBack!(response);
126
- resolve(response);
127
- }
128
- } catch (error) {
129
- reject(error);
130
- }
131
- });
132
- }
133
-
134
- async _initializeCheckout() {
135
- const business_response = await this._fetchMerchantData();
136
-
137
- if (
138
- !!business_response &&
139
- !!business_response.mercado_pago &&
140
- business_response.mercado_pago.active
141
- ) {
142
- injectMercadoPagoSecurity();
143
- }
144
- }
145
-
146
- async _checkout(data: any): Promise<any> {
147
- throw new Error(
148
- "The #checkout method should be implement in child classes.",
149
- );
150
- }
151
-
152
- _setCartTotal(total: string | number) {
153
- throw new Error(
154
- "The #setCartTotal method should be implement in child classes.",
155
- );
156
- }
157
-
158
- async _getCustomer(signal: AbortSignal | null = null) {
159
- if (!!this.#customerData) return this.#customerData!;
160
-
161
- this.#customerData = await registerOrFetchCustomer(
162
- this.baseUrl,
163
- this.apiKeyTonder,
164
- this.customer!,
165
- signal,
166
- );
167
- return this.#customerData!;
168
- }
169
-
170
- async _handleCheckout({
171
- card,
172
- payment_method,
173
- customer,
174
- isSandbox,
175
- // TODO: DEPRECATED
176
- returnUrl: returnUrlData
177
- }: {
178
- card?: string;
179
- payment_method?: string;
180
- customer: Record<string, any>;
181
- isSandbox?: boolean;
182
- returnUrl?: string;
183
- }) {
184
- const { openpay_keys, reference, business } = this.merchantData!;
185
- const total = Number(this.cartTotal);
186
- try {
187
- let deviceSessionIdTonder;
188
- if (
189
- !deviceSessionIdTonder &&
190
- openpay_keys.merchant_id &&
191
- openpay_keys.public_key
192
- ) {
193
- deviceSessionIdTonder = await getOpenpayDeviceSessionID(
194
- openpay_keys.merchant_id,
195
- openpay_keys.public_key,
196
- isSandbox,
197
- this.abortController.signal,
198
- );
199
- }
200
-
201
- const { id, auth_token } = customer;
202
-
203
- const orderItems = {
204
- business: this.apiKeyTonder,
205
- client: auth_token,
206
- billing_address_id: null,
207
- shipping_address_id: null,
208
- amount: total,
209
- status: "A",
210
- reference: reference,
211
- is_oneclick: true,
212
- items: this.cartItems!,
213
- };
214
- const jsonResponseOrder = await createOrder(
215
- this.baseUrl,
216
- this.apiKeyTonder,
217
- orderItems,
218
- );
219
-
220
- // Create payment
221
- const now = new Date();
222
- const dateString = now.toISOString();
223
-
224
- const paymentItems = {
225
- business_pk: business.pk,
226
- client_id: id,
227
- amount: total,
228
- date: dateString,
229
- order_id: jsonResponseOrder.id,
230
- };
231
- const jsonResponsePayment = await createPayment(
232
- this.baseUrl,
233
- this.apiKeyTonder,
234
- paymentItems,
235
- );
236
-
237
- // Checkout router
238
- const routerItems = {
239
- name: get(this.customer, "firstName", get(this.customer, "name", "")),
240
- last_name: get(
241
- this.customer,
242
- "lastName",
243
- get(this.customer, "lastname", ""),
244
- ),
245
- email_client: get(this.customer, "email", ""),
246
- phone_number: get(this.customer, "phone", ""),
247
- return_url: returnUrlData || this.returnUrl,
248
- id_product: "no_id",
249
- quantity_product: 1,
250
- id_ship: "0",
251
- instance_id_ship: "0",
252
- amount: total,
253
- title_ship: "shipping",
254
- description: "transaction",
255
- device_session_id: deviceSessionIdTonder ? deviceSessionIdTonder : null,
256
- token_id: "",
257
- order_id: jsonResponseOrder.id,
258
- business_id: business.pk,
259
- payment_id: jsonResponsePayment.pk,
260
- source: "sdk",
261
- metadata: this.metadata,
262
- browser_info: getBrowserInfo(),
263
- currency: this.currency!,
264
- ...(!!payment_method ? { payment_method } : { card }),
265
- };
266
-
267
- const jsonResponseRouter = await startCheckoutRouter(
268
- this.baseUrl,
269
- this.apiKeyTonder,
270
- routerItems,
271
- );
272
-
273
- if (jsonResponseRouter) {
274
- return jsonResponseRouter;
275
- } else {
276
- return false;
277
- }
278
- } catch (error) {
279
- console.log(error);
280
- throw error;
281
- }
282
- }
283
-
284
- async _fetchMerchantData() {
285
- try {
286
- if (!this.merchantData) {
287
- this.merchantData = await fetchBusiness(
288
- this.baseUrl,
289
- this.apiKeyTonder,
290
- this.abortController.signal,
291
- );
292
- }
293
- return this.merchantData;
294
- } catch (e) {
295
- return this.merchantData;
296
- }
297
- }
298
-
299
- async _getCustomerCards(
300
- authToken: string,
301
- businessId: string | number,
302
- ): Promise<ICustomerCardsResponse> {
303
- return await fetchCustomerCards(this.baseUrl, authToken, businessId);
304
- }
305
-
306
- async _saveCustomerCard(
307
- authToken: string,
308
- secureToken: string,
309
- businessId: string | number,
310
- skyflowTokens: ISaveCardSkyflowRequest,
311
- ): Promise<ISaveCardResponse> {
312
- return await saveCustomerCard(
313
- this.baseUrl,
314
- this.secureToken,
315
- authToken,
316
- businessId,
317
- skyflowTokens,
318
- );
319
- }
320
-
321
- async _removeCustomerCard(
322
- authToken: string,
323
- businessId: string | number,
324
- skyflowId: string,
325
- ): Promise<string> {
326
- return await removeCustomerCard(
327
- this.baseUrl,
328
- authToken,
329
- skyflowId,
330
- businessId,
331
- );
332
- }
333
- async _fetchCustomerPaymentMethods(): Promise<IPaymentMethodResponse> {
334
- return await fetchCustomerPaymentMethods(this.baseUrl, this.apiKeyTonder);
335
- }
336
-
337
- #handleCustomer(customer: ICustomer | { email: string }) {
338
- if (!customer) return;
339
-
340
- this.customer = customer;
341
- }
342
-
343
- #setSecureToken(token: string) {
344
- this.secureToken = token;
345
- }
346
-
347
- #setCartItems(items: IItem[]) {
348
- this.cartItems = items;
349
- }
350
-
351
- #handleMetadata(data: { metadata?: any }) {
352
- this.metadata = data?.metadata;
353
- }
354
-
355
- #handleCurrency(data: { currency?: string }) {
356
- this.currency = data?.currency;
357
- }
358
-
359
- #handleCard(data: { card?: ICardFields | string }) {
360
- this.card = data?.card;
361
- }
362
-
363
- // TODO: Make private after remove deprecated functions of liteCheckout
364
- async _handle3dsRedirect(
365
- response: ITransaction | IStartCheckoutResponse | void,
366
- ) {
367
- const iframe =
368
- response && "next_action" in response
369
- ? response?.next_action?.iframe_resources?.iframe
370
- : null;
371
-
372
- if (iframe) {
373
- this.process3ds
374
- .loadIframe()!
375
- .then(() => {
376
- //TODO: Check if this will be necessary on the frontend side
377
- // after some the tests in production, since the 3DS process
378
- // doesn't works properly on the sandbox environment
379
- // setTimeout(() => {
380
- // process3ds.verifyTransactionStatus();
381
- // }, 10000);
382
- this.process3ds.verifyTransactionStatus();
383
- })
384
- .catch((error) => {
385
- console.log("Error loading iframe:", error);
386
- });
387
- } else {
388
- const redirectUrl = this.process3ds.getRedirectUrl();
389
- if (redirectUrl) {
390
- this.process3ds.redirectToChallenge();
391
- } else {
392
- return response;
393
- }
394
- }
395
- }
396
-
397
- async #resumeCheckout(response: any) {
398
- // Stop the routing process if the transaction is either hard declined or successful
399
- if (response?.decline?.error_type === "Hard") {
400
- return response;
401
- }
402
-
403
- if (["Success", "Authorized"].includes(response?.transaction_status)) {
404
- return response;
405
- }
406
-
407
- if (response) {
408
- const routerItems = {
409
- checkout_id: response.checkout?.id,
410
- };
411
-
412
- try {
413
- return await startCheckoutRouter(
414
- this.baseUrl,
415
- this.apiKeyTonder,
416
- routerItems,
417
- );
418
- } catch (error) {
419
- // throw error
420
- }
421
- return response;
422
- }
423
- }
424
- }
1
+ import { ThreeDSHandler } from "./3dsHandler";
2
+ import { ErrorResponse } from "./errorResponse";
3
+ import { fetchBusiness } from "../data/businessApi";
4
+ import { injectMercadoPagoSecurity } from "../helpers/mercadopago";
5
+ import { TONDER_URL_BY_MODE } from "../shared/constants/tonderUrl";
6
+ import {
7
+ createOrder,
8
+ createPayment,
9
+ startCheckoutRouter,
10
+ } from "../data/checkoutApi";
11
+ import { getOpenpayDeviceSessionID } from "../data/openPayApi";
12
+ import { getBrowserInfo } from "../helpers/utils";
13
+ import { registerOrFetchCustomer } from "../data/customerApi";
14
+ import { get } from "lodash";
15
+ import {
16
+ fetchCustomerCards,
17
+ removeCustomerCard,
18
+ saveCustomerCard,
19
+ } from "../data/cardApi";
20
+ import { fetchCustomerPaymentMethods } from "../data/paymentMethodApi";
21
+ import {Business, IConfigureCheckout, IInlineCheckoutBaseOptions, CustomizationOptions} from "../types/commons";
22
+ import {ICustomer} from "../types/customer";
23
+ import {ICardFields, IItem, IProcessPaymentRequest, IStartCheckoutResponse} from "../types/checkout";
24
+ import {ICustomerCardsResponse, ISaveCardResponse, ISaveCardSkyflowRequest} from "../types/card";
25
+ import {IPaymentMethodResponse} from "../types/paymentMethod";
26
+ import {ITransaction} from "../types/transaction";
27
+ export class BaseInlineCheckout {
28
+ baseUrl = "";
29
+ cartTotal: string | number = "0";
30
+ process3ds: ThreeDSHandler;
31
+ mode?: "production" | "sandbox" | "stage" | "development" | undefined;
32
+ apiKeyTonder: string;
33
+ returnUrl?: string;
34
+ tdsIframeId?: string;
35
+ tonderPayButtonId?: string;
36
+ callBack?: ((response: IStartCheckoutResponse | Record<string, any>) => void) | undefined;
37
+ merchantData?: Business;
38
+ abortController: AbortController;
39
+ secureToken: string = "";
40
+ customer?: ICustomer | { email: string };
41
+ customization: CustomizationOptions = {
42
+ saveCards: {
43
+ showSaveCardOption: true,
44
+ showSaved: true,
45
+ autoSave: false
46
+ },
47
+ redirectOnComplete: true
48
+ }
49
+
50
+ cartItems?: IItem[];
51
+ metadata = {};
52
+ card? = {};
53
+ currency?: string = "";
54
+
55
+ #customerData?: Record<string, any>;
56
+
57
+ constructor({
58
+ mode = "stage",
59
+ customization,
60
+ apiKey,
61
+ apiKeyTonder,
62
+ returnUrl,
63
+ tdsIframeId,
64
+ callBack = () => {},
65
+ baseUrlTonder,
66
+ tonderPayButtonId
67
+ }: IInlineCheckoutBaseOptions) {
68
+ this.apiKeyTonder = apiKeyTonder || apiKey || "";
69
+ this.returnUrl = returnUrl;
70
+ this.callBack = callBack;
71
+ this.mode = mode;
72
+ this.customer = {} as ICustomer
73
+ this.baseUrl = baseUrlTonder || TONDER_URL_BY_MODE[this.mode] || TONDER_URL_BY_MODE["stage"];
74
+ this.abortController = new AbortController();
75
+ this.process3ds = new ThreeDSHandler({
76
+ apiKey: apiKey,
77
+ baseUrl: this.baseUrl,
78
+ customization: customization,
79
+ tdsIframeId: tdsIframeId,
80
+ tonderPayButtonId: tonderPayButtonId,
81
+ callBack: callBack
82
+ });
83
+ this.tdsIframeId = tdsIframeId;
84
+ this.customization = {
85
+ ...this.customization,
86
+ ...(customization || {}),
87
+ saveCards: {
88
+ ...this.customization.saveCards,
89
+ ...(customization?.saveCards || {})
90
+ }
91
+ }
92
+ }
93
+
94
+ configureCheckout(data: IConfigureCheckout) {
95
+ if ("customer" in data) this.#handleCustomer(data["customer"]);
96
+ if ("secureToken" in data) this.#setSecureToken(data["secureToken"]);
97
+ }
98
+
99
+ async verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void> {
100
+ const result3ds = await this.process3ds.verifyTransactionStatus();
101
+ const resultCheckout = await this.#resumeCheckout(result3ds);
102
+ this.process3ds.setPayload(resultCheckout);
103
+ return this._handle3dsRedirect(resultCheckout);
104
+ }
105
+
106
+ payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse> {
107
+ return new Promise(async (resolve, reject) => {
108
+ try {
109
+ this.#handleCustomer(data.customer);
110
+ this._setCartTotal(data.cart?.total);
111
+ this.#setCartItems(data.cart?.items);
112
+ this.#handleMetadata(data);
113
+ this.#handleCurrency(data);
114
+ this.#handleCard(data);
115
+ const response = await this._checkout(data);
116
+ this.process3ds.setPayload(response);
117
+ const payload = await this._handle3dsRedirect(response);
118
+ if (payload) {
119
+ try {
120
+ const selector: any = document.querySelector(`#${this.tonderPayButtonId}`);
121
+ if(selector) {
122
+ selector.disabled = false;
123
+ }
124
+ } catch {}
125
+ if (this.callBack) this.callBack!(response);
126
+ resolve(response);
127
+ }
128
+ } catch (error) {
129
+ reject(error);
130
+ }
131
+ });
132
+ }
133
+
134
+ async _initializeCheckout() {
135
+ const business_response = await this._fetchMerchantData();
136
+
137
+ if (
138
+ !!business_response &&
139
+ !!business_response.mercado_pago &&
140
+ business_response.mercado_pago.active
141
+ ) {
142
+ injectMercadoPagoSecurity();
143
+ }
144
+ }
145
+
146
+ async _checkout(data: any): Promise<any> {
147
+ throw new Error(
148
+ "The #checkout method should be implement in child classes.",
149
+ );
150
+ }
151
+
152
+ _setCartTotal(total: string | number) {
153
+ throw new Error(
154
+ "The #setCartTotal method should be implement in child classes.",
155
+ );
156
+ }
157
+
158
+ async _getCustomer(signal: AbortSignal | null = null) {
159
+ if (!!this.#customerData) return this.#customerData!;
160
+
161
+ this.#customerData = await registerOrFetchCustomer(
162
+ this.baseUrl,
163
+ this.apiKeyTonder,
164
+ this.customer!,
165
+ signal,
166
+ );
167
+ return this.#customerData!;
168
+ }
169
+
170
+ async _handleCheckout({
171
+ card,
172
+ payment_method,
173
+ customer,
174
+ isSandbox,
175
+ // TODO: DEPRECATED
176
+ returnUrl: returnUrlData
177
+ }: {
178
+ card?: string;
179
+ payment_method?: string;
180
+ customer: Record<string, any>;
181
+ isSandbox?: boolean;
182
+ returnUrl?: string;
183
+ }) {
184
+ const { openpay_keys, reference, business } = this.merchantData!;
185
+ const total = Number(this.cartTotal);
186
+ try {
187
+ let deviceSessionIdTonder;
188
+ if (
189
+ !deviceSessionIdTonder &&
190
+ openpay_keys.merchant_id &&
191
+ openpay_keys.public_key
192
+ ) {
193
+ deviceSessionIdTonder = await getOpenpayDeviceSessionID(
194
+ openpay_keys.merchant_id,
195
+ openpay_keys.public_key,
196
+ isSandbox,
197
+ this.abortController.signal,
198
+ );
199
+ }
200
+
201
+ const { id, auth_token } = customer;
202
+
203
+ const orderItems = {
204
+ business: this.apiKeyTonder,
205
+ client: auth_token,
206
+ billing_address_id: null,
207
+ shipping_address_id: null,
208
+ amount: total,
209
+ status: "A",
210
+ reference: reference,
211
+ is_oneclick: true,
212
+ items: this.cartItems!,
213
+ };
214
+ const jsonResponseOrder = await createOrder(
215
+ this.baseUrl,
216
+ this.apiKeyTonder,
217
+ orderItems,
218
+ );
219
+
220
+ // Create payment
221
+ const now = new Date();
222
+ const dateString = now.toISOString();
223
+
224
+ const paymentItems = {
225
+ business_pk: business.pk,
226
+ client_id: id,
227
+ amount: total,
228
+ date: dateString,
229
+ order_id: jsonResponseOrder.id,
230
+ };
231
+ const jsonResponsePayment = await createPayment(
232
+ this.baseUrl,
233
+ this.apiKeyTonder,
234
+ paymentItems,
235
+ );
236
+
237
+ // Checkout router
238
+ const routerItems = {
239
+ name: get(this.customer, "firstName", get(this.customer, "name", "")),
240
+ last_name: get(
241
+ this.customer,
242
+ "lastName",
243
+ get(this.customer, "lastname", ""),
244
+ ),
245
+ email_client: get(this.customer, "email", ""),
246
+ phone_number: get(this.customer, "phone", ""),
247
+ return_url: returnUrlData || this.returnUrl,
248
+ id_product: "no_id",
249
+ quantity_product: 1,
250
+ id_ship: "0",
251
+ instance_id_ship: "0",
252
+ amount: total,
253
+ title_ship: "shipping",
254
+ description: "transaction",
255
+ device_session_id: deviceSessionIdTonder ? deviceSessionIdTonder : null,
256
+ token_id: "",
257
+ order_id: jsonResponseOrder.id,
258
+ business_id: business.pk,
259
+ payment_id: jsonResponsePayment.pk,
260
+ source: "sdk",
261
+ metadata: this.metadata,
262
+ browser_info: getBrowserInfo(),
263
+ currency: this.currency!,
264
+ ...(!!payment_method ? { payment_method } : { card }),
265
+ };
266
+
267
+ const jsonResponseRouter = await startCheckoutRouter(
268
+ this.baseUrl,
269
+ this.apiKeyTonder,
270
+ routerItems,
271
+ );
272
+
273
+ if (jsonResponseRouter) {
274
+ return jsonResponseRouter;
275
+ } else {
276
+ return false;
277
+ }
278
+ } catch (error) {
279
+ console.log(error);
280
+ throw error;
281
+ }
282
+ }
283
+
284
+ async _fetchMerchantData() {
285
+ try {
286
+ if (!this.merchantData) {
287
+ this.merchantData = await fetchBusiness(
288
+ this.baseUrl,
289
+ this.apiKeyTonder,
290
+ this.abortController.signal,
291
+ );
292
+ }
293
+ return this.merchantData;
294
+ } catch (e) {
295
+ return this.merchantData;
296
+ }
297
+ }
298
+
299
+ async _getCustomerCards(
300
+ authToken: string,
301
+ businessId: string | number,
302
+ ): Promise<ICustomerCardsResponse> {
303
+ return await fetchCustomerCards(this.baseUrl, authToken, this.secureToken, businessId);
304
+ }
305
+
306
+ async _saveCustomerCard(
307
+ authToken: string,
308
+ businessId: string | number,
309
+ skyflowTokens: ISaveCardSkyflowRequest,
310
+ ): Promise<ISaveCardResponse> {
311
+ return await saveCustomerCard(
312
+ this.baseUrl,
313
+ authToken,
314
+ this.secureToken,
315
+ businessId,
316
+ skyflowTokens,
317
+ );
318
+ }
319
+
320
+ async _removeCustomerCard(
321
+ authToken: string,
322
+ businessId: string | number,
323
+ skyflowId: string,
324
+ ): Promise<string> {
325
+ return await removeCustomerCard(
326
+ this.baseUrl,
327
+ authToken,
328
+ this.secureToken,
329
+ skyflowId,
330
+ businessId,
331
+ );
332
+ }
333
+ async _fetchCustomerPaymentMethods(): Promise<IPaymentMethodResponse> {
334
+ return await fetchCustomerPaymentMethods(this.baseUrl, this.apiKeyTonder);
335
+ }
336
+
337
+ #handleCustomer(customer: ICustomer | { email: string }) {
338
+ if (!customer) return;
339
+
340
+ this.customer = customer;
341
+ }
342
+
343
+ #setSecureToken(token: string) {
344
+ this.secureToken = token;
345
+ }
346
+
347
+ #setCartItems(items: IItem[]) {
348
+ this.cartItems = items;
349
+ }
350
+
351
+ #handleMetadata(data: { metadata?: any }) {
352
+ this.metadata = data?.metadata;
353
+ }
354
+
355
+ #handleCurrency(data: { currency?: string }) {
356
+ this.currency = data?.currency;
357
+ }
358
+
359
+ #handleCard(data: { card?: ICardFields | string }) {
360
+ this.card = data?.card;
361
+ }
362
+
363
+ // TODO: Make private after remove deprecated functions of liteCheckout
364
+ async _handle3dsRedirect(
365
+ response: ITransaction | IStartCheckoutResponse | void,
366
+ ) {
367
+ const iframe =
368
+ response && "next_action" in response
369
+ ? response?.next_action?.iframe_resources?.iframe
370
+ : null;
371
+
372
+ if (iframe) {
373
+ this.process3ds
374
+ .loadIframe()!
375
+ .then(() => {
376
+ //TODO: Check if this will be necessary on the frontend side
377
+ // after some the tests in production, since the 3DS process
378
+ // doesn't works properly on the sandbox environment
379
+ // setTimeout(() => {
380
+ // process3ds.verifyTransactionStatus();
381
+ // }, 10000);
382
+ this.process3ds.verifyTransactionStatus();
383
+ })
384
+ .catch((error) => {
385
+ console.log("Error loading iframe:", error);
386
+ });
387
+ } else {
388
+ const redirectUrl = this.process3ds.getRedirectUrl();
389
+ if (redirectUrl) {
390
+ this.process3ds.redirectToChallenge();
391
+ } else {
392
+ return response;
393
+ }
394
+ }
395
+ }
396
+
397
+ async #resumeCheckout(response: any) {
398
+ // Stop the routing process if the transaction is either hard declined or successful
399
+ if (response?.decline?.error_type === "Hard") {
400
+ return response;
401
+ }
402
+
403
+ if (["Success", "Authorized"].includes(response?.transaction_status)) {
404
+ return response;
405
+ }
406
+
407
+ if (response) {
408
+ const routerItems = {
409
+ checkout_id: response.checkout?.id,
410
+ };
411
+
412
+ try {
413
+ return await startCheckoutRouter(
414
+ this.baseUrl,
415
+ this.apiKeyTonder,
416
+ routerItems,
417
+ );
418
+ } catch (error) {
419
+ // throw error
420
+ }
421
+ return response;
422
+ }
423
+ }
424
+ }