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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +60 -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 +27 -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 +5 -3
  28. package/package.json +1 -1
  29. package/src/classes/BaseInlineCheckout.ts +318 -0
  30. package/src/classes/liteCheckout.ts +254 -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 +32 -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 +183 -0
  51. package/src/types/paymentMethod.ts +24 -0
  52. package/src/types/requests.ts +5 -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 +4 -0
  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,39 @@
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 { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
7
+ import {
8
+ CustomerRegisterResponse,
9
+ CreateOrderResponse,
10
+ CreatePaymentResponse,
11
+ StartCheckoutResponse,
12
+ IErrorResponse,
13
+ RegisterCustomerCardResponse,
14
+ GetBusinessResponse
15
+ } from "../types/responses";
11
16
  import { ErrorResponse } from "./errorResponse";
12
- import { buildErrorResponse, buildErrorResponseFromCatch, getBrowserInfo, getPaymentMethodDetails, getBusinessId } from "../helpers/utils";
13
- import { ThreeDSHandler } from "./3dsHandler";
17
+ import {
18
+ buildErrorResponse,
19
+ buildErrorResponseFromCatch,
20
+ getBrowserInfo,
21
+ getBusinessId,
22
+ formatPublicErrorResponse, getCardType
23
+ } from "../helpers/utils";
14
24
  import { getCustomerAPMs } from "../data/api";
25
+ import {BaseInlineCheckout} from "./BaseInlineCheckout";
26
+ import {fetchCustomerCards, removeCustomerCard, saveCustomerCard} from "../data/cardApi";
27
+ import {MESSAGES} from "../shared/constants/messages";
28
+ import {ICustomerCardsResponse, ISaveCardRequest, ISaveCardResponse} from "../types/card";
29
+ import {getSkyflowTokens} from "../helpers/skyflow";
30
+ import {fetchCustomerAPMs} from "../data/paymentMethodApi";
31
+ import {IPaymentMethod} from "../types/paymentMethod";
32
+ import {ICardFields} from "../types/checkout";
33
+ import {ILiteInlineCheckout} from "../types/liteInlineCheckout";
34
+ import {startCheckoutRouter} from "../data/checkoutApi";
35
+ import {getOpenpayDeviceSessionID} from "../data/openPayApi";
36
+ import {getPaymentMethodDetails} from "../shared/catalog/paymentMethodsCatalog";
15
37
 
16
38
  declare global {
17
39
  interface Window {
@@ -19,151 +41,193 @@ declare global {
19
41
  }
20
42
  }
21
43
 
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;
44
+ export interface LiteCheckoutConstructor extends IInlineCheckoutBaseOptions {}
45
+
46
+ export class LiteCheckout extends BaseInlineCheckout implements ILiteInlineCheckout {
33
47
  activeAPMs: APM[] = []
34
- merchantData?: Business | ErrorResponse;
48
+ #customerData?: Record<string, any>;
35
49
 
36
50
  constructor({
37
- signal,
38
- baseUrlTonder,
39
- apiKeyTonder,
51
+ apiKey,
52
+ mode,
53
+ returnUrl,
54
+ callBack,
40
55
  }: 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()
56
+ super({mode, apiKey, returnUrl, callBack});
49
57
  }
50
58
 
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
- }
59
+ async injectCheckout() {
60
+ await this._initializeCheckout();
57
61
  }
58
62
 
59
- async getOpenpayDeviceSessionID(
60
- merchant_id: string,
61
- public_key: string,
62
- is_sandbox: boolean
63
- ): Promise<string | ErrorResponse> {
63
+ async getCustomerCards(): Promise<ICustomerCardsResponse> {
64
64
  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);
65
+ await this._fetchMerchantData()
66
+ const { auth_token } = await this._getCustomer();
67
+ const response = await fetchCustomerCards(
68
+ this.baseUrl,
69
+ auth_token,
70
+ this.merchantData!.business.pk,
71
+ );
72
+
73
+ return {
74
+ ...response,
75
+ cards: response.cards.map((ic) => ({
76
+ ...ic,
77
+ icon: getCardType(ic.fields.card_scheme),
78
+ })),
79
+ };
80
+ } catch (error) {
81
+ throw formatPublicErrorResponse(
82
+ {
83
+ message: MESSAGES.getCardsError,
84
+ },
85
+ error,
86
+ );
74
87
  }
75
88
  }
76
- async #fetchMerchantData() {
89
+
90
+ async saveCustomerCard(card: ISaveCardRequest): Promise<ISaveCardResponse> {
77
91
  try {
78
- if (!this.merchantData){
79
- this.merchantData = await this.getBusiness();
80
- }
81
- return this.merchantData
82
- }catch(e){
83
- return this.merchantData
92
+ await this._fetchMerchantData()
93
+ const { auth_token } = await this._getCustomer();
94
+ const { vault_id, vault_url, business } = this.merchantData!;
95
+
96
+ const skyflowTokens = await getSkyflowTokens({
97
+ vault_id: vault_id,
98
+ vault_url: vault_url,
99
+ data: card,
100
+ baseUrl: this.baseUrl,
101
+ apiKey: this.apiKeyTonder,
102
+ });
103
+
104
+ return await saveCustomerCard(
105
+ this.baseUrl,
106
+ auth_token,
107
+ business?.pk,
108
+ skyflowTokens,
109
+ );
110
+ } catch (error) {
111
+ throw formatPublicErrorResponse(
112
+ {
113
+ message: MESSAGES.saveCardError,
114
+ },
115
+ error,
116
+ );
84
117
  }
85
118
  }
86
119
 
87
- async getBusiness(): Promise<GetBusinessResponse | ErrorResponse> {
120
+
121
+ async removeCustomerCard(skyflowId: string): Promise<string> {
88
122
  try {
89
- const getBusiness = await fetch(
90
- `${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,
91
- {
92
- headers: {
93
- Authorization: `Token ${this.apiKeyTonder}`,
123
+ await this._fetchMerchantData()
124
+ const { auth_token } = await this._getCustomer();
125
+ const { business } = this.merchantData!;
126
+
127
+ return await removeCustomerCard(
128
+ this.baseUrl,
129
+ auth_token,
130
+ skyflowId,
131
+ business?.pk,
132
+ );
133
+ } catch (error) {
134
+ throw formatPublicErrorResponse(
135
+ {
136
+ message: MESSAGES.removeCardError,
94
137
  },
95
- signal: this.signal,
96
- }
138
+ error,
97
139
  );
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
140
  }
105
141
  }
106
142
 
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)
112
- }
113
143
 
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
144
+ async getCustomerPaymentMethods(): Promise<IPaymentMethod[]> {
145
+ try {
146
+ const response = await fetchCustomerAPMs(this.baseUrl, this.apiKeyTonder);
147
+
148
+ const apms_results =
149
+ response && "results" in response && response["results"].length > 0
150
+ ? response["results"]
151
+ : [];
152
+
153
+ return apms_results
154
+ .filter((apmItem) => apmItem.category.toLowerCase() !== "cards")
155
+ .map((apmItem) => {
156
+ const apm = {
157
+ id: apmItem.pk,
158
+ payment_method: apmItem.payment_method,
159
+ priority: apmItem.priority,
160
+ category: apmItem.category,
161
+ ...getPaymentMethodDetails(apmItem.payment_method),
162
+ };
163
+ return apm;
164
+ })
165
+ .sort((a, b) => a.priority - b.priority);
166
+ } catch (error) {
167
+ throw formatPublicErrorResponse(
168
+ {
169
+ message: MESSAGES.getPaymentMethodsError,
170
+ },
171
+ error,
172
+ );
118
173
  }
174
+ }
119
175
 
120
- if (["Success", "Authorized"].includes(response?.transaction_status)) {
121
- return response;
176
+ async getBusiness(): Promise<GetBusinessResponse> {
177
+ try {
178
+ return await fetchBusiness(this.baseUrl, this.apiKeyTonder, this.abortController.signal)
179
+ } catch (e) {
180
+ throw formatPublicErrorResponse({
181
+ message: MESSAGES.getBusinessError
182
+ },e);
122
183
  }
184
+ }
123
185
 
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
- }
186
+ _setCartTotal(total: string) {
187
+ this.cartTotal = total;
138
188
  }
139
189
 
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()
190
+ async _checkout({ card, payment_method, isSandbox }: {card?: ICardFields | string; payment_method?: string; isSandbox?: boolean;}) {
191
+ await this._fetchMerchantData()
192
+ const customer = await this._getCustomer(
193
+ this.abortController.signal,
194
+ );
195
+ const { vault_id, vault_url } = this.merchantData!;
196
+ let skyflowTokens;
197
+ if (!payment_method || payment_method !== "" || payment_method === null) {
198
+ if (typeof card === "string") {
199
+ skyflowTokens = {
200
+ skyflow_id: card,
201
+ };
158
202
  } else {
159
- return response;
203
+ skyflowTokens = await getSkyflowTokens({
204
+ vault_id: vault_id,
205
+ vault_url: vault_url,
206
+ data: {...card, card_number: card!.card_number.replace(/\s+/g, '')},
207
+ baseUrl: this.baseUrl,
208
+ apiKey: this.apiKeyTonder,
209
+ });
160
210
  }
161
211
  }
212
+
213
+ return await this._handleCheckout({
214
+ card: skyflowTokens,
215
+ payment_method,
216
+ customer,
217
+ isSandbox
218
+ });
162
219
  }
163
-
220
+
221
+
222
+ // TODO: DEPRECATED
223
+ /**
224
+ * @deprecated This method is deprecated and will be removed in a future release.
225
+ * It is no longer necessary to use this method as customer registration is now automatically handled
226
+ * during the payment process or when using card management methods.
227
+ */
164
228
  async customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse> {
165
229
  try {
166
- const url = `${this.baseUrlTonder}/api/v1/customer/`;
230
+ const url = `${this.baseUrl}/api/v1/customer/`;
167
231
  const data = { email: email };
168
232
  const response = await fetch(url, {
169
233
  method: "POST",
@@ -171,7 +235,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
171
235
  "Content-Type": "application/json",
172
236
  Authorization: `Token ${this.apiKeyTonder}`,
173
237
  },
174
- signal: this.signal,
238
+ signal: this.abortController.signal,
175
239
  body: JSON.stringify(data),
176
240
  });
177
241
 
@@ -182,9 +246,16 @@ export class LiteCheckout implements LiteCheckoutConstructor {
182
246
  }
183
247
  }
184
248
 
249
+
250
+ // TODO: DEPRECATED
251
+ /**
252
+ * @deprecated This method is deprecated and will be removed in a future release.
253
+ * It is no longer necessary to use this method as order creation is now automatically
254
+ * handled when making a payment through the `payment` function.
255
+ */
185
256
  async createOrder(orderItems: CreateOrderRequest): Promise<CreateOrderResponse | ErrorResponse> {
186
257
  try {
187
- const url = `${this.baseUrlTonder}/api/v1/orders/`;
258
+ const url = `${this.baseUrl}/api/v1/orders/`;
188
259
  const data = orderItems;
189
260
  const response = await fetch(url, {
190
261
  method: "POST",
@@ -201,9 +272,15 @@ export class LiteCheckout implements LiteCheckoutConstructor {
201
272
  }
202
273
  }
203
274
 
275
+ // TODO: DEPRECATED
276
+ /**
277
+ * @deprecated This method is deprecated and will be removed in a future release.
278
+ * It is no longer necessary to use this method as payment creation is now automatically
279
+ * handled when making a payment through the `payment` function.
280
+ */
204
281
  async createPayment(paymentItems: CreatePaymentRequest): Promise<CreatePaymentResponse | ErrorResponse> {
205
282
  try {
206
- const url = `${this.baseUrlTonder}/api/v1/business/${paymentItems.business_pk}/payments/`;
283
+ const url = `${this.baseUrl}/api/v1/business/${paymentItems.business_pk}/payments/`;
207
284
  const data = paymentItems;
208
285
  const response = await fetch(url, {
209
286
  method: "POST",
@@ -219,32 +296,30 @@ export class LiteCheckout implements LiteCheckoutConstructor {
219
296
  throw buildErrorResponseFromCatch(e);
220
297
  }
221
298
  }
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
299
 
300
+ // TODO: DEPRECATED
301
+ /**
302
+ * @deprecated This method is deprecated and will be removed in a future release.
303
+ * Use the {@link payment} method
304
+ */
241
305
  async startCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
242
- const checkoutResult = await this.handleCheckoutRouter(routerData);
306
+ const checkoutResult = await startCheckoutRouter(this.baseUrl, this.apiKeyTonder, routerData);
243
307
  const payload = await this.init3DSRedirect(checkoutResult)
244
308
  if(payload)
245
309
  return checkoutResult;
246
310
  }
247
311
 
312
+ // TODO: DEPRECATED
313
+ async init3DSRedirect(checkoutResult: ErrorResponse | StartCheckoutResponse){
314
+ this.process3ds.setPayload(checkoutResult)
315
+ return await this._handle3dsRedirect(checkoutResult)
316
+ }
317
+
318
+ // TODO: DEPRECATED
319
+ /**
320
+ * @deprecated This method is deprecated and will be removed in a future release.
321
+ * Use the {@link payment} method
322
+ */
248
323
  async startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
249
324
 
250
325
  try {
@@ -261,7 +336,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
261
336
  payment_method
262
337
  } = routerFullData;
263
338
 
264
- const merchantResult = await this.getBusiness();
339
+ const merchantResult = await this._fetchMerchantData();
265
340
 
266
341
  const customerResult : CustomerRegisterResponse | ErrorResponse = await this.customerRegister(customer.email);
267
342
 
@@ -303,7 +378,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
303
378
  const { openpay_keys, business } = merchantResult
304
379
 
305
380
  if (openpay_keys.merchant_id && openpay_keys.public_key) {
306
- deviceSessionIdTonder = await this.getOpenpayDeviceSessionID(
381
+ deviceSessionIdTonder = await getOpenpayDeviceSessionID(
307
382
  openpay_keys.merchant_id,
308
383
  openpay_keys.public_key,
309
384
  isSandbox
@@ -339,7 +414,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
339
414
  ...(typeof MP_DEVICE_SESSION_ID !== "undefined" ? {mp_device_session_id: MP_DEVICE_SESSION_ID}:{})
340
415
  };
341
416
 
342
- const checkoutResult = await this.handleCheckoutRouter(routerItems);
417
+ const checkoutResult = await startCheckoutRouter(this.baseUrl, this.apiKeyTonder, routerItems);
343
418
  const payload = await this.init3DSRedirect(checkoutResult)
344
419
  if(payload)
345
420
  return checkoutResult;
@@ -371,100 +446,21 @@ export class LiteCheckout implements LiteCheckoutConstructor {
371
446
  }
372
447
  }
373
448
 
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
-
449
+ // TODO: DEPRECATED
450
+ /**
451
+ * @deprecated This method is deprecated and will be removed in a future release.
452
+ * Use the {@link saveCustomerCard} method
453
+ */
457
454
  async registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse> {
458
455
  try {
459
- await this.#fetchMerchantData()
456
+ await this._fetchMerchantData()
460
457
 
461
- const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/`, {
458
+ const response = await fetch(`${this.baseUrl}/api/v1/business/${getBusinessId(this.merchantData)}/cards/`, {
462
459
  method: 'POST',
463
460
  headers: {
464
461
  'Authorization': `Token ${customerToken}`,
465
462
  'Content-Type': 'application/json'
466
463
  },
467
- signal: this.signal,
468
464
  body: JSON.stringify({...data})
469
465
  });
470
466
 
@@ -475,36 +471,21 @@ export class LiteCheckout implements LiteCheckoutConstructor {
475
471
  }
476
472
  }
477
473
 
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
-
474
+ // TODO: DEPRECATED
475
+ /**
476
+ * @deprecated This method is deprecated and will be removed in a future release.
477
+ * Use the {@link removeCustomerCard} method
478
+ */
498
479
  async deleteCustomerCard(customerToken: string, skyflowId: string = ""): Promise<Boolean | ErrorResponse> {
499
480
  try {
500
- await this.#fetchMerchantData()
501
- const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/${skyflowId}`, {
481
+ await this._fetchMerchantData()
482
+ const response = await fetch(`${this.baseUrl}/api/v1/business/${getBusinessId(this.merchantData)}/cards/${skyflowId}`, {
502
483
  method: 'DELETE',
503
484
  headers: {
504
485
  'Authorization': `Token ${customerToken}`,
505
486
  'Content-Type': 'application/json'
506
487
  },
507
- signal: this.signal,
488
+ signal: this.abortController.signal,
508
489
  });
509
490
 
510
491
  if (response.ok) return true;
@@ -514,36 +495,28 @@ export class LiteCheckout implements LiteCheckoutConstructor {
514
495
  }
515
496
  }
516
497
 
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
-
498
+ // TODO: DEPRECATED
499
+ /**
500
+ * @deprecated This method is deprecated and will be removed in a future release.
501
+ * Use the {@link getCustomerPaymentMethods} method
502
+ */
530
503
  async getActiveAPMs(): Promise<APM[]> {
531
504
  try {
532
- const apms_response = await getCustomerAPMs(this.baseUrlTonder, this.apiKeyTonder);
505
+ const apms_response = await getCustomerAPMs(this.baseUrl, this.apiKeyTonder);
533
506
  const apms_results = apms_response && apms_response['results'] && apms_response['results'].length > 0 ? apms_response['results'] : []
534
507
  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);
508
+ .filter((apmItem: TonderAPM) =>
509
+ apmItem.category.toLowerCase() !== 'cards')
510
+ .map((apmItem: TonderAPM) => {
511
+ const apm: APM = {
512
+ id: apmItem.pk,
513
+ payment_method: apmItem.payment_method,
514
+ priority: apmItem.priority,
515
+ category: apmItem.category,
516
+ ...getPaymentMethodDetails(apmItem.payment_method,)
517
+ }
518
+ return apm;
519
+ }).sort((a: APM, b: APM) => a.priority - b.priority);
547
520
 
548
521
  return this.activeAPMs
549
522
  } catch (e) {
@@ -551,4 +524,5 @@ export class LiteCheckout implements LiteCheckoutConstructor {
551
524
  return [];
552
525
  }
553
526
  }
527
+
554
528
  }