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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/.idea/aws.xml +17 -0
  2. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  3. package/.idea/vcs.xml +6 -0
  4. package/.idea/workspace.xml +72 -17
  5. package/dist/classes/BaseInlineCheckout.d.ts +48 -0
  6. package/dist/classes/liteCheckout.d.ts +61 -29
  7. package/dist/data/businessApi.d.ts +2 -0
  8. package/dist/data/cardApi.d.ts +4 -0
  9. package/dist/data/checkoutApi.d.ts +5 -0
  10. package/dist/data/customerApi.d.ts +2 -0
  11. package/dist/data/openPayApi.d.ts +1 -0
  12. package/dist/data/paymentMethodApi.d.ts +5 -0
  13. package/dist/data/skyflowApi.d.ts +1 -0
  14. package/dist/helpers/skyflow.d.ts +3 -0
  15. package/dist/helpers/utils.d.ts +8 -4
  16. package/dist/helpers/validations.d.ts +6 -0
  17. package/dist/index.js +1 -1
  18. package/dist/shared/catalog/paymentMethodsCatalog.d.ts +1 -0
  19. package/dist/shared/constants/messages.d.ts +11 -0
  20. package/dist/shared/constants/paymentMethodAPM.d.ts +62 -0
  21. package/dist/shared/constants/tonderUrl.d.ts +7 -0
  22. package/dist/types/card.d.ts +29 -0
  23. package/dist/types/checkout.d.ts +103 -0
  24. package/dist/types/commons.d.ts +32 -0
  25. package/dist/types/customer.d.ts +12 -0
  26. package/dist/types/paymentMethod.d.ts +22 -0
  27. package/dist/types/requests.d.ts +12 -3
  28. package/package.json +1 -1
  29. package/src/classes/BaseInlineCheckout.ts +318 -0
  30. package/src/classes/liteCheckout.ts +273 -280
  31. package/src/data/businessApi.ts +14 -0
  32. package/src/data/cardApi.ts +82 -0
  33. package/src/data/checkoutApi.ts +71 -0
  34. package/src/data/customerApi.ts +31 -0
  35. package/src/data/openPayApi.ts +7 -0
  36. package/src/data/paymentMethodApi.ts +34 -0
  37. package/src/data/skyflowApi.ts +16 -0
  38. package/src/helpers/skyflow.ts +85 -0
  39. package/src/helpers/utils.ts +31 -243
  40. package/src/helpers/validations.ts +55 -0
  41. package/src/shared/catalog/paymentMethodsCatalog.ts +248 -0
  42. package/src/shared/constants/messages.ts +11 -0
  43. package/src/shared/constants/paymentMethodAPM.ts +63 -0
  44. package/src/shared/constants/tonderUrl.ts +8 -0
  45. package/src/types/card.ts +34 -0
  46. package/src/types/checkout.ts +118 -0
  47. package/src/types/commons.ts +37 -0
  48. package/src/types/customer.ts +12 -0
  49. package/src/types/index.d.ts +10 -0
  50. package/src/types/liteInlineCheckout.d.ts +191 -0
  51. package/src/types/paymentMethod.ts +24 -0
  52. package/src/types/requests.ts +12 -3
  53. package/src/types/validations.d.ts +11 -0
  54. package/tests/classes/liteCheckout.test.ts +3 -3
  55. package/tests/methods/getBusiness.test.ts +2 -2
  56. package/tests/methods/getCustomerCards.test.ts +4 -8
  57. package/tests/utils/defaultMock.ts +3 -2
  58. package/tests/utils/mockClasses.ts +7 -4
  59. package/tests/methods/getOpenpayDeviceSessionID.test.ts +0 -95
  60. package/tests/methods/getSkyflowToken.test.ts +0 -155
  61. package/tests/methods/getVaultToken.test.ts +0 -107
@@ -1,17 +1,47 @@
1
- import {injectMercadoPagoSecurity} from "../helpers/mercadopago";
1
+ import {fetchBusiness} from "../data/businessApi";
2
2
 
3
3
  declare const MP_DEVICE_SESSION_ID: string | undefined;
4
4
 
5
- import Skyflow from "skyflow-js";
6
- import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
7
- import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
8
- import { APM, Business, TonderAPM } from "../types/commons";
9
- import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
10
- import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetVaultTokenResponse, IErrorResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
5
+ import {APM, Business, IInlineCheckoutBaseOptions, TonderAPM} from "../types/commons";
6
+ import {
7
+ CreateOrderRequest,
8
+ CreatePaymentRequest,
9
+ RegisterCustomerCardRequest,
10
+ StartCheckoutRequest,
11
+ StartCheckoutFullRequest,
12
+ StartCheckoutIdRequest,
13
+ TokensRequest
14
+ } from "../types/requests";
15
+ import {
16
+ CustomerRegisterResponse,
17
+ CreateOrderResponse,
18
+ CreatePaymentResponse,
19
+ StartCheckoutResponse,
20
+ IErrorResponse,
21
+ RegisterCustomerCardResponse,
22
+ GetBusinessResponse
23
+ } from "../types/responses";
11
24
  import { ErrorResponse } from "./errorResponse";
12
- import { buildErrorResponse, buildErrorResponseFromCatch, getBrowserInfo, getPaymentMethodDetails, getBusinessId } from "../helpers/utils";
13
- import { ThreeDSHandler } from "./3dsHandler";
25
+ import {
26
+ buildErrorResponse,
27
+ buildErrorResponseFromCatch,
28
+ getBrowserInfo,
29
+ getBusinessId,
30
+ formatPublicErrorResponse, getCardType
31
+ } from "../helpers/utils";
14
32
  import { getCustomerAPMs } from "../data/api";
33
+ import {BaseInlineCheckout} from "./BaseInlineCheckout";
34
+ import {fetchCustomerCards, removeCustomerCard, saveCustomerCard} from "../data/cardApi";
35
+ import {MESSAGES} from "../shared/constants/messages";
36
+ import {ICustomerCardsResponse, ISaveCardRequest, ISaveCardResponse} from "../types/card";
37
+ import {getSkyflowTokens} from "../helpers/skyflow";
38
+ import {fetchCustomerAPMs} from "../data/paymentMethodApi";
39
+ import {IPaymentMethod} from "../types/paymentMethod";
40
+ import {ICardFields} from "../types/checkout";
41
+ import {ILiteInlineCheckout} from "../types/liteInlineCheckout";
42
+ import {startCheckoutRouter} from "../data/checkoutApi";
43
+ import {getOpenpayDeviceSessionID} from "../data/openPayApi";
44
+ import {getPaymentMethodDetails} from "../shared/catalog/paymentMethodsCatalog";
15
45
 
16
46
  declare global {
17
47
  interface Window {
@@ -19,151 +49,204 @@ declare global {
19
49
  }
20
50
  }
21
51
 
22
- export type LiteCheckoutConstructor = {
23
- signal: AbortSignal;
24
- baseUrlTonder: string;
25
- apiKeyTonder: string;
26
- };
27
-
28
- export class LiteCheckout implements LiteCheckoutConstructor {
29
- signal: AbortSignal;
30
- baseUrlTonder: string;
31
- apiKeyTonder: string;
32
- process3ds: ThreeDSHandler;
52
+ export interface LiteCheckoutConstructor extends IInlineCheckoutBaseOptions {}
53
+
54
+ export class LiteCheckout extends BaseInlineCheckout implements ILiteInlineCheckout {
33
55
  activeAPMs: APM[] = []
34
- merchantData?: Business | ErrorResponse;
56
+ #customerData?: Record<string, any>;
35
57
 
36
58
  constructor({
37
- signal,
38
- baseUrlTonder,
39
- apiKeyTonder,
59
+ apiKey,
60
+ mode,
61
+ returnUrl,
62
+ callBack,
40
63
  }: LiteCheckoutConstructor) {
41
- this.baseUrlTonder = baseUrlTonder;
42
- this.signal = signal;
43
- this.apiKeyTonder = apiKeyTonder;
44
- this.process3ds = new ThreeDSHandler({
45
- apiKey: this.apiKeyTonder,
46
- baseUrl: this.baseUrlTonder,
47
- })
48
- this.#init()
64
+ super({mode, apiKey, returnUrl, callBack});
49
65
  }
50
66
 
51
- async #init(){
52
- this.getActiveAPMs()
53
- const { mercado_pago } = await this.#fetchMerchantData() as Business
54
- if (!!mercado_pago && mercado_pago.active){
55
- injectMercadoPagoSecurity()
56
- }
67
+ async injectCheckout() {
68
+ await this._initializeCheckout();
57
69
  }
58
70
 
59
- async getOpenpayDeviceSessionID(
60
- merchant_id: string,
61
- public_key: string,
62
- is_sandbox: boolean
63
- ): Promise<string | ErrorResponse> {
71
+ async getCustomerCards(): Promise<ICustomerCardsResponse> {
64
72
  try {
65
- let openpay = await window.OpenPay;
66
- openpay.setId(merchant_id);
67
- openpay.setApiKey(public_key);
68
- openpay.setSandboxMode(is_sandbox);
69
- return await openpay.deviceData.setup({
70
- signal: this.signal,
71
- }) as string;
72
- } catch (e) {
73
- throw buildErrorResponseFromCatch(e);
73
+ await this._fetchMerchantData()
74
+ const { auth_token } = await this._getCustomer();
75
+ const response = await fetchCustomerCards(
76
+ this.baseUrl,
77
+ auth_token,
78
+ this.merchantData!.business.pk,
79
+ );
80
+
81
+ return {
82
+ ...response,
83
+ cards: response.cards.map((ic) => ({
84
+ ...ic,
85
+ icon: getCardType(ic.fields.card_scheme),
86
+ })),
87
+ };
88
+ } catch (error) {
89
+ throw formatPublicErrorResponse(
90
+ {
91
+ message: MESSAGES.getCardsError,
92
+ },
93
+ error,
94
+ );
74
95
  }
75
96
  }
76
- async #fetchMerchantData() {
97
+
98
+ async saveCustomerCard(card: ISaveCardRequest): Promise<ISaveCardResponse> {
77
99
  try {
78
- if (!this.merchantData){
79
- this.merchantData = await this.getBusiness();
80
- }
81
- return this.merchantData
82
- }catch(e){
83
- return this.merchantData
100
+ await this._fetchMerchantData()
101
+ const { auth_token } = await this._getCustomer();
102
+ const { vault_id, vault_url, business } = this.merchantData!;
103
+
104
+ const skyflowTokens = await getSkyflowTokens({
105
+ vault_id: vault_id,
106
+ vault_url: vault_url,
107
+ data: card,
108
+ baseUrl: this.baseUrl,
109
+ apiKey: this.apiKeyTonder,
110
+ });
111
+
112
+ return await saveCustomerCard(
113
+ this.baseUrl,
114
+ auth_token,
115
+ business?.pk,
116
+ skyflowTokens,
117
+ );
118
+ } catch (error) {
119
+ throw formatPublicErrorResponse(
120
+ {
121
+ message: MESSAGES.saveCardError,
122
+ },
123
+ error,
124
+ );
84
125
  }
85
126
  }
86
127
 
87
- async getBusiness(): Promise<GetBusinessResponse | ErrorResponse> {
128
+
129
+ async removeCustomerCard(skyflowId: string): Promise<string> {
88
130
  try {
89
- const getBusiness = await fetch(
90
- `${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,
91
- {
92
- headers: {
93
- Authorization: `Token ${this.apiKeyTonder}`,
131
+ await this._fetchMerchantData()
132
+ const { auth_token } = await this._getCustomer();
133
+ const { business } = this.merchantData!;
134
+
135
+ return await removeCustomerCard(
136
+ this.baseUrl,
137
+ auth_token,
138
+ skyflowId,
139
+ business?.pk,
140
+ );
141
+ } catch (error) {
142
+ throw formatPublicErrorResponse(
143
+ {
144
+ message: MESSAGES.removeCardError,
94
145
  },
95
- signal: this.signal,
96
- }
146
+ error,
97
147
  );
98
-
99
- if (getBusiness.ok) return (await getBusiness.json()) as Business;
100
-
101
- throw await buildErrorResponse(getBusiness);
102
- } catch (e) {
103
- throw buildErrorResponseFromCatch(e);
104
148
  }
105
149
  }
106
150
 
107
- async verify3dsTransaction () {
108
- const result3ds = await this.process3ds.verifyTransactionStatus()
109
- const resultCheckout = await this.resumeCheckout(result3ds)
110
- this.process3ds.setPayload(resultCheckout)
111
- return this.handle3dsRedirect(resultCheckout)
151
+ async getCustomerPaymentMethods(): Promise<IPaymentMethod[]> {
152
+ try {
153
+ const response = await fetchCustomerAPMs(this.baseUrl, this.apiKeyTonder);
154
+
155
+ const apms_results =
156
+ response && "results" in response && response["results"].length > 0
157
+ ? response["results"]
158
+ : [];
159
+
160
+ return apms_results
161
+ .filter((apmItem) => apmItem.category.toLowerCase() !== "cards")
162
+ .map((apmItem) => {
163
+ const apm = {
164
+ id: apmItem.pk,
165
+ payment_method: apmItem.payment_method,
166
+ priority: apmItem.priority,
167
+ category: apmItem.category,
168
+ ...getPaymentMethodDetails(apmItem.payment_method),
169
+ };
170
+ return apm;
171
+ })
172
+ .sort((a, b) => a.priority - b.priority);
173
+ } catch (error) {
174
+ throw formatPublicErrorResponse(
175
+ {
176
+ message: MESSAGES.getPaymentMethodsError,
177
+ },
178
+ error,
179
+ );
180
+ }
112
181
  }
113
182
 
114
- async resumeCheckout(response: any) {
115
- // Stop the routing process if the transaction is either hard declined or successful
116
- if (response?.decline?.error_type === "Hard") {
117
- return response
183
+ async getBusiness(): Promise<GetBusinessResponse> {
184
+ try {
185
+ return await fetchBusiness(this.baseUrl, this.apiKeyTonder, this.abortController.signal)
186
+ } catch (e) {
187
+ throw formatPublicErrorResponse({
188
+ message: MESSAGES.getBusinessError
189
+ },e);
118
190
  }
191
+ }
119
192
 
120
- if (["Success", "Authorized"].includes(response?.transaction_status)) {
121
- return response;
122
- }
123
193
 
124
- if (response) {
125
- const routerItems = {
126
- checkout_id: response?.checkout?.id,
127
- };
128
- try {
129
- const routerResponse = await this.handleCheckoutRouter(
130
- routerItems
131
- );
132
- return routerResponse
133
- }catch (error){
134
- // throw error
135
- }
136
- return response
137
- }
194
+ // TODO: DEPRECATED
195
+ async getSkyflowTokens({vault_id, vault_url, data}: TokensRequest): Promise<any | ErrorResponse> {
196
+ return await getSkyflowTokens({
197
+ vault_id: vault_id,
198
+ vault_url: vault_url,
199
+ data,
200
+ baseUrl: this.baseUrl,
201
+ apiKey: this.apiKeyTonder,
202
+ })
138
203
  }
139
204
 
140
- async handle3dsRedirect(response: ErrorResponse | StartCheckoutResponse | false | undefined) {
141
- const iframe = response && 'next_action' in response ? response?.next_action?.iframe_resources?.iframe:null
142
- if (iframe) {
143
- this.process3ds.loadIframe()!.then(() => {
144
- //TODO: Check if this will be necessary on the frontend side
145
- // after some the tests in production, since the 3DS process
146
- // doesn't works properly on the sandbox environment
147
- // setTimeout(() => {
148
- // process3ds.verifyTransactionStatus();
149
- // }, 10000);
150
- this.process3ds.verifyTransactionStatus();
151
- }).catch((error: any) => {
152
- console.log('Error loading iframe:', error)
153
- })
154
- } else {
155
- const redirectUrl = this.process3ds.getRedirectUrl()
156
- if (redirectUrl) {
157
- this.process3ds.redirectToChallenge()
205
+ _setCartTotal(total: string) {
206
+ this.cartTotal = total;
207
+ }
208
+
209
+ async _checkout({ card, payment_method, isSandbox }: {card?: ICardFields | string; payment_method?: string; isSandbox?: boolean;}) {
210
+ await this._fetchMerchantData()
211
+ const customer = await this._getCustomer(
212
+ this.abortController.signal,
213
+ );
214
+ const { vault_id, vault_url } = this.merchantData!;
215
+ let skyflowTokens;
216
+ if (!payment_method || payment_method !== "" || payment_method === null) {
217
+ if (typeof card === "string") {
218
+ skyflowTokens = {
219
+ skyflow_id: card,
220
+ };
158
221
  } else {
159
- return response;
222
+ skyflowTokens = await getSkyflowTokens({
223
+ vault_id: vault_id,
224
+ vault_url: vault_url,
225
+ data: {...card, card_number: card!.card_number.replace(/\s+/g, '')},
226
+ baseUrl: this.baseUrl,
227
+ apiKey: this.apiKeyTonder,
228
+ });
160
229
  }
161
230
  }
231
+
232
+ return await this._handleCheckout({
233
+ card: skyflowTokens,
234
+ payment_method,
235
+ customer,
236
+ isSandbox
237
+ });
162
238
  }
163
-
239
+
240
+
241
+ // TODO: DEPRECATED
242
+ /**
243
+ * @deprecated This method is deprecated and will be removed in a future release.
244
+ * It is no longer necessary to use this method as customer registration is now automatically handled
245
+ * during the payment process or when using card management methods.
246
+ */
164
247
  async customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse> {
165
248
  try {
166
- const url = `${this.baseUrlTonder}/api/v1/customer/`;
249
+ const url = `${this.baseUrl}/api/v1/customer/`;
167
250
  const data = { email: email };
168
251
  const response = await fetch(url, {
169
252
  method: "POST",
@@ -171,7 +254,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
171
254
  "Content-Type": "application/json",
172
255
  Authorization: `Token ${this.apiKeyTonder}`,
173
256
  },
174
- signal: this.signal,
257
+ signal: this.abortController.signal,
175
258
  body: JSON.stringify(data),
176
259
  });
177
260
 
@@ -182,9 +265,16 @@ export class LiteCheckout implements LiteCheckoutConstructor {
182
265
  }
183
266
  }
184
267
 
268
+
269
+ // TODO: DEPRECATED
270
+ /**
271
+ * @deprecated This method is deprecated and will be removed in a future release.
272
+ * It is no longer necessary to use this method as order creation is now automatically
273
+ * handled when making a payment through the `payment` function.
274
+ */
185
275
  async createOrder(orderItems: CreateOrderRequest): Promise<CreateOrderResponse | ErrorResponse> {
186
276
  try {
187
- const url = `${this.baseUrlTonder}/api/v1/orders/`;
277
+ const url = `${this.baseUrl}/api/v1/orders/`;
188
278
  const data = orderItems;
189
279
  const response = await fetch(url, {
190
280
  method: "POST",
@@ -201,9 +291,15 @@ export class LiteCheckout implements LiteCheckoutConstructor {
201
291
  }
202
292
  }
203
293
 
294
+ // TODO: DEPRECATED
295
+ /**
296
+ * @deprecated This method is deprecated and will be removed in a future release.
297
+ * It is no longer necessary to use this method as payment creation is now automatically
298
+ * handled when making a payment through the `payment` function.
299
+ */
204
300
  async createPayment(paymentItems: CreatePaymentRequest): Promise<CreatePaymentResponse | ErrorResponse> {
205
301
  try {
206
- const url = `${this.baseUrlTonder}/api/v1/business/${paymentItems.business_pk}/payments/`;
302
+ const url = `${this.baseUrl}/api/v1/business/${paymentItems.business_pk}/payments/`;
207
303
  const data = paymentItems;
208
304
  const response = await fetch(url, {
209
305
  method: "POST",
@@ -219,32 +315,30 @@ export class LiteCheckout implements LiteCheckoutConstructor {
219
315
  throw buildErrorResponseFromCatch(e);
220
316
  }
221
317
  }
222
- async handleCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest){
223
- try {
224
- const url = `${this.baseUrlTonder}/api/v1/checkout-router/`;
225
- const data = routerData;
226
- const response = await fetch(url, {
227
- method: "POST",
228
- headers: {
229
- "Content-Type": "application/json",
230
- Authorization: `Token ${this.apiKeyTonder}`,
231
- },
232
- body: JSON.stringify({...data, ...(typeof MP_DEVICE_SESSION_ID !== "undefined" ? {mp_device_session_id: MP_DEVICE_SESSION_ID}:{})}),
233
- });
234
- if (response.ok) return await response.json() as StartCheckoutResponse;
235
- throw await buildErrorResponse(response);
236
- } catch (e) {
237
- throw buildErrorResponseFromCatch(e);
238
- }
239
- }
240
318
 
319
+ // TODO: DEPRECATED
320
+ /**
321
+ * @deprecated This method is deprecated and will be removed in a future release.
322
+ * Use the {@link payment} method
323
+ */
241
324
  async startCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
242
- const checkoutResult = await this.handleCheckoutRouter(routerData);
325
+ const checkoutResult = await startCheckoutRouter(this.baseUrl, this.apiKeyTonder, routerData);
243
326
  const payload = await this.init3DSRedirect(checkoutResult)
244
327
  if(payload)
245
328
  return checkoutResult;
246
329
  }
247
330
 
331
+ // TODO: DEPRECATED
332
+ async init3DSRedirect(checkoutResult: ErrorResponse | StartCheckoutResponse){
333
+ this.process3ds.setPayload(checkoutResult)
334
+ return await this._handle3dsRedirect(checkoutResult)
335
+ }
336
+
337
+ // TODO: DEPRECATED
338
+ /**
339
+ * @deprecated This method is deprecated and will be removed in a future release.
340
+ * Use the {@link payment} method
341
+ */
248
342
  async startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
249
343
 
250
344
  try {
@@ -261,7 +355,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
261
355
  payment_method
262
356
  } = routerFullData;
263
357
 
264
- const merchantResult = await this.getBusiness();
358
+ const merchantResult = await this._fetchMerchantData();
265
359
 
266
360
  const customerResult : CustomerRegisterResponse | ErrorResponse = await this.customerRegister(customer.email);
267
361
 
@@ -303,7 +397,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
303
397
  const { openpay_keys, business } = merchantResult
304
398
 
305
399
  if (openpay_keys.merchant_id && openpay_keys.public_key) {
306
- deviceSessionIdTonder = await this.getOpenpayDeviceSessionID(
400
+ deviceSessionIdTonder = await getOpenpayDeviceSessionID(
307
401
  openpay_keys.merchant_id,
308
402
  openpay_keys.public_key,
309
403
  isSandbox
@@ -339,7 +433,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
339
433
  ...(typeof MP_DEVICE_SESSION_ID !== "undefined" ? {mp_device_session_id: MP_DEVICE_SESSION_ID}:{})
340
434
  };
341
435
 
342
- const checkoutResult = await this.handleCheckoutRouter(routerItems);
436
+ const checkoutResult = await startCheckoutRouter(this.baseUrl, this.apiKeyTonder, routerItems);
343
437
  const payload = await this.init3DSRedirect(checkoutResult)
344
438
  if(payload)
345
439
  return checkoutResult;
@@ -371,100 +465,21 @@ export class LiteCheckout implements LiteCheckoutConstructor {
371
465
  }
372
466
  }
373
467
 
374
- async init3DSRedirect(checkoutResult: ErrorResponse | StartCheckoutResponse){
375
- this.process3ds.setPayload(checkoutResult)
376
- return await this.handle3dsRedirect(checkoutResult)
377
- }
378
-
379
- async getSkyflowTokens({
380
- vault_id,
381
- vault_url,
382
- data,
383
- }: TokensRequest): Promise<any | ErrorResponse> {
384
- const skyflow = Skyflow.init({
385
- vaultID: vault_id,
386
- vaultURL: vault_url,
387
- getBearerToken: async () => await this.getVaultToken(),
388
- options: {
389
- logLevel: Skyflow.LogLevel.ERROR,
390
- env: Skyflow.Env.DEV,
391
- },
392
- });
393
-
394
- const collectContainer: CollectContainer = skyflow.container(
395
- Skyflow.ContainerType.COLLECT
396
- ) as CollectContainer;
397
-
398
- const fieldPromises = await this.getFieldsPromise(data, collectContainer);
399
-
400
- const result = await Promise.all(fieldPromises);
401
-
402
- const mountFail = result.some((item: boolean) => !item);
403
-
404
- if (mountFail) {
405
- throw buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));
406
- } else {
407
- try {
408
- const collectResponseSkyflowTonder = await collectContainer.collect() as any;
409
- if (collectResponseSkyflowTonder) return collectResponseSkyflowTonder["records"][0]["fields"];
410
- throw buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))
411
- } catch (error) {
412
- throw buildErrorResponseFromCatch(error);
413
- }
414
- }
415
- }
416
-
417
- async getVaultToken(): Promise<string> {
418
- try {
419
- const response = await fetch(`${this.baseUrlTonder}/api/v1/vault-token/`, {
420
- method: "GET",
421
- headers: {
422
- Authorization: `Token ${this.apiKeyTonder}`,
423
- },
424
- signal: this.signal,
425
- });
426
- if (response.ok) return (await response.json() as GetVaultTokenResponse)?.token;
427
- throw new Error(`HTTPCODE: ${response.status}`)
428
- } catch (e) {
429
- throw new Error(`Failed to retrieve bearer token; ${typeof e == "string" ? e : (e as Error).message}`)
430
- }
431
- }
432
-
433
- async getFieldsPromise(data: any, collectContainer: CollectContainer): Promise<Promise<boolean>[]> {
434
- const fields = await this.getFields(data, collectContainer);
435
- if (!fields) return [];
436
-
437
- return fields.map((field: { element: CollectElement, key: string }) => {
438
- return new Promise((resolve) => {
439
- const div = document.createElement("div");
440
- div.hidden = true;
441
- div.id = `id-${field.key}`;
442
- document.querySelector(`body`)?.appendChild(div);
443
- setTimeout(() => {
444
- field.element.mount(`#id-${field.key}`);
445
- setInterval(() => {
446
- if (field.element.isMounted()) {
447
- const value = data[field.key];
448
- field.element.update({ value: value });
449
- return resolve(field.element.isMounted());
450
- }
451
- }, 120);
452
- }, 120);
453
- });
454
- })
455
- }
456
-
468
+ // TODO: DEPRECATED
469
+ /**
470
+ * @deprecated This method is deprecated and will be removed in a future release.
471
+ * Use the {@link saveCustomerCard} method
472
+ */
457
473
  async registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse> {
458
474
  try {
459
- await this.#fetchMerchantData()
475
+ await this._fetchMerchantData()
460
476
 
461
- const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/`, {
477
+ const response = await fetch(`${this.baseUrl}/api/v1/business/${getBusinessId(this.merchantData)}/cards/`, {
462
478
  method: 'POST',
463
479
  headers: {
464
480
  'Authorization': `Token ${customerToken}`,
465
481
  'Content-Type': 'application/json'
466
482
  },
467
- signal: this.signal,
468
483
  body: JSON.stringify({...data})
469
484
  });
470
485
 
@@ -475,36 +490,21 @@ export class LiteCheckout implements LiteCheckoutConstructor {
475
490
  }
476
491
  }
477
492
 
478
- async getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse> {
479
- try {
480
- await this.#fetchMerchantData()
481
-
482
- const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards`, {
483
- method: 'GET',
484
- headers: {
485
- 'Authorization': `Token ${customerToken}`,
486
- 'Content-Type': 'application/json'
487
- },
488
- signal: this.signal,
489
- });
490
-
491
- if (response.ok) return await response.json() as GetCustomerCardsResponse;
492
- throw await buildErrorResponse(response);
493
- } catch (error) {
494
- throw buildErrorResponseFromCatch(error);
495
- }
496
- }
497
-
493
+ // TODO: DEPRECATED
494
+ /**
495
+ * @deprecated This method is deprecated and will be removed in a future release.
496
+ * Use the {@link removeCustomerCard} method
497
+ */
498
498
  async deleteCustomerCard(customerToken: string, skyflowId: string = ""): Promise<Boolean | ErrorResponse> {
499
499
  try {
500
- await this.#fetchMerchantData()
501
- const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/${skyflowId}`, {
500
+ await this._fetchMerchantData()
501
+ const response = await fetch(`${this.baseUrl}/api/v1/business/${getBusinessId(this.merchantData)}/cards/${skyflowId}`, {
502
502
  method: 'DELETE',
503
503
  headers: {
504
504
  'Authorization': `Token ${customerToken}`,
505
505
  'Content-Type': 'application/json'
506
506
  },
507
- signal: this.signal,
507
+ signal: this.abortController.signal,
508
508
  });
509
509
 
510
510
  if (response.ok) return true;
@@ -514,36 +514,28 @@ export class LiteCheckout implements LiteCheckoutConstructor {
514
514
  }
515
515
  }
516
516
 
517
- private async getFields(data: any, collectContainer: CollectContainer): Promise<{ element: CollectElement, key: string }[]> {
518
- return await Promise.all(
519
- Object.keys(data).map(async (key) => {
520
- const cardHolderNameElement = await collectContainer.create({
521
- table: "cards",
522
- column: key,
523
- type: Skyflow.ElementType.INPUT_FIELD,
524
- });
525
- return { element: cardHolderNameElement, key: key };
526
- })
527
- )
528
- }
529
-
517
+ // TODO: DEPRECATED
518
+ /**
519
+ * @deprecated This method is deprecated and will be removed in a future release.
520
+ * Use the {@link getCustomerPaymentMethods} method
521
+ */
530
522
  async getActiveAPMs(): Promise<APM[]> {
531
523
  try {
532
- const apms_response = await getCustomerAPMs(this.baseUrlTonder, this.apiKeyTonder);
524
+ const apms_response = await getCustomerAPMs(this.baseUrl, this.apiKeyTonder);
533
525
  const apms_results = apms_response && apms_response['results'] && apms_response['results'].length > 0 ? apms_response['results'] : []
534
526
  this.activeAPMs = apms_results
535
- .filter((apmItem: TonderAPM) =>
536
- apmItem.category.toLowerCase() !== 'cards')
537
- .map((apmItem: TonderAPM) => {
538
- const apm: APM = {
539
- id: apmItem.pk,
540
- payment_method: apmItem.payment_method,
541
- priority: apmItem.priority,
542
- category: apmItem.category,
543
- ...getPaymentMethodDetails(apmItem.payment_method,)
544
- }
545
- return apm;
546
- }).sort((a: APM, b: APM) => a.priority - b.priority);
527
+ .filter((apmItem: TonderAPM) =>
528
+ apmItem.category.toLowerCase() !== 'cards')
529
+ .map((apmItem: TonderAPM) => {
530
+ const apm: APM = {
531
+ id: apmItem.pk,
532
+ payment_method: apmItem.payment_method,
533
+ priority: apmItem.priority,
534
+ category: apmItem.category,
535
+ ...getPaymentMethodDetails(apmItem.payment_method,)
536
+ }
537
+ return apm;
538
+ }).sort((a: APM, b: APM) => a.priority - b.priority);
547
539
 
548
540
  return this.activeAPMs
549
541
  } catch (e) {
@@ -551,4 +543,5 @@ export class LiteCheckout implements LiteCheckoutConstructor {
551
543
  return [];
552
544
  }
553
545
  }
546
+
554
547
  }