@tonder.io/ionic-lite-sdk 0.0.32-beta → 0.0.34-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 (40) hide show
  1. package/.gitlab-ci.yml +28 -28
  2. package/README.md +202 -193
  3. package/dist/classes/3dsHandler.d.ts +33 -0
  4. package/dist/classes/liteCheckout.d.ts +16 -6
  5. package/dist/data/api.d.ts +1 -0
  6. package/dist/helpers/constants.d.ts +62 -0
  7. package/dist/helpers/utils.d.ts +8 -0
  8. package/dist/index.js +1 -1
  9. package/dist/types/commons.d.ts +16 -0
  10. package/dist/types/requests.d.ts +14 -2
  11. package/dist/types/responses.d.ts +1 -0
  12. package/jest.config.ts +14 -14
  13. package/package.json +38 -38
  14. package/rollup.config.js +16 -16
  15. package/src/classes/3dsHandler.ts +241 -0
  16. package/src/classes/errorResponse.ts +16 -16
  17. package/src/classes/liteCheckout.ts +521 -462
  18. package/src/data/api.ts +21 -0
  19. package/src/helpers/constants.ts +64 -0
  20. package/src/helpers/utils.ts +315 -12
  21. package/src/index.ts +4 -4
  22. package/src/types/commons.ts +80 -62
  23. package/src/types/requests.ts +105 -89
  24. package/src/types/responses.ts +188 -187
  25. package/src/types/skyflow.ts +17 -17
  26. package/tests/classes/liteCheckout.test.ts +57 -57
  27. package/tests/methods/createOrder.test.ts +142 -142
  28. package/tests/methods/createPayment.test.ts +122 -122
  29. package/tests/methods/customerRegister.test.ts +119 -119
  30. package/tests/methods/getBusiness.test.ts +115 -115
  31. package/tests/methods/getCustomerCards.test.ts +117 -117
  32. package/tests/methods/getOpenpayDeviceSessionID.test.ts +94 -94
  33. package/tests/methods/getSkyflowToken.test.ts +154 -154
  34. package/tests/methods/getVaultToken.test.ts +106 -106
  35. package/tests/methods/registerCustomerCard.test.ts +117 -117
  36. package/tests/methods/startCheckoutRouter.test.ts +119 -119
  37. package/tests/methods/startCheckoutRouterFull.test.ts +138 -138
  38. package/tests/utils/defaultMock.ts +20 -20
  39. package/tests/utils/mockClasses.ts +652 -649
  40. package/tsconfig.json +18 -18
@@ -1,462 +1,521 @@
1
- import Skyflow from "skyflow-js";
2
- import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
3
- import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
4
- import { Business } from "../types/commons";
5
- import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest } from "../types/requests";
6
- import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetVaultTokenResponse, IErrorResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
7
- import { ErrorResponse } from "./errorResponse";
8
- import { getBrowserInfo } from "../helpers/utils";
9
-
10
- declare global {
11
- interface Window {
12
- OpenPay: any;
13
- }
14
- }
15
-
16
- export type LiteCheckoutConstructor = {
17
- signal: AbortSignal;
18
- baseUrlTonder: string;
19
- apiKeyTonder: string;
20
- };
21
-
22
- export class LiteCheckout implements LiteCheckoutConstructor {
23
- signal: AbortSignal;
24
- baseUrlTonder: string;
25
- apiKeyTonder: string;
26
-
27
- constructor({
28
- signal,
29
- baseUrlTonder,
30
- apiKeyTonder,
31
- }: LiteCheckoutConstructor) {
32
- this.baseUrlTonder = baseUrlTonder;
33
- this.signal = signal;
34
- this.apiKeyTonder = apiKeyTonder;
35
- }
36
-
37
- async getOpenpayDeviceSessionID(
38
- merchant_id: string,
39
- public_key: string,
40
- is_sandbox: boolean
41
- ): Promise<string | ErrorResponse> {
42
- try {
43
- let openpay = await window.OpenPay;
44
- openpay.setId(merchant_id);
45
- openpay.setApiKey(public_key);
46
- openpay.setSandboxMode(is_sandbox);
47
- return await openpay.deviceData.setup({
48
- signal: this.signal,
49
- }) as string;
50
- } catch (e) {
51
- throw this.buildErrorResponseFromCatch(e);
52
- }
53
- }
54
-
55
- async getBusiness(): Promise<GetBusinessResponse | ErrorResponse> {
56
- try {
57
- const getBusiness = await fetch(
58
- `${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,
59
- {
60
- headers: {
61
- Authorization: `Token ${this.apiKeyTonder}`,
62
- },
63
- signal: this.signal,
64
- }
65
- );
66
-
67
- if (getBusiness.ok) return (await getBusiness.json()) as Business;
68
-
69
- throw await this.buildErrorResponse(getBusiness);
70
- } catch (e) {
71
- throw this.buildErrorResponseFromCatch(e);
72
- }
73
- }
74
-
75
- async customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse> {
76
- try {
77
- const url = `${this.baseUrlTonder}/api/v1/customer/`;
78
- const data = { email: email };
79
- const response = await fetch(url, {
80
- method: "POST",
81
- headers: {
82
- "Content-Type": "application/json",
83
- Authorization: `Token ${this.apiKeyTonder}`,
84
- },
85
- signal: this.signal,
86
- body: JSON.stringify(data),
87
- });
88
-
89
- if (response.ok) return await response.json() as CustomerRegisterResponse;
90
- throw await this.buildErrorResponse(response);
91
- } catch (e) {
92
- throw this.buildErrorResponseFromCatch(e);
93
- }
94
- }
95
-
96
- async createOrder(orderItems: CreateOrderRequest): Promise<CreateOrderResponse | ErrorResponse> {
97
- try {
98
- const url = `${this.baseUrlTonder}/api/v1/orders/`;
99
- const data = orderItems;
100
- const response = await fetch(url, {
101
- method: "POST",
102
- headers: {
103
- "Content-Type": "application/json",
104
- Authorization: `Token ${this.apiKeyTonder}`,
105
- },
106
- body: JSON.stringify(data),
107
- });
108
- if (response.ok) return await response.json() as CreateOrderResponse;
109
- throw await this.buildErrorResponse(response);
110
- } catch (e) {
111
- throw this.buildErrorResponseFromCatch(e);
112
- }
113
- }
114
-
115
- async createPayment(paymentItems: CreatePaymentRequest): Promise<CreatePaymentResponse | ErrorResponse> {
116
- try {
117
- const url = `${this.baseUrlTonder}/api/v1/business/${paymentItems.business_pk}/payments/`;
118
- const data = paymentItems;
119
- const response = await fetch(url, {
120
- method: "POST",
121
- headers: {
122
- "Content-Type": "application/json",
123
- Authorization: `Token ${this.apiKeyTonder}`,
124
- },
125
- body: JSON.stringify(data),
126
- });
127
- if (response.ok) return await response.json() as CreatePaymentResponse;
128
- throw await this.buildErrorResponse(response);
129
- } catch (e) {
130
- throw this.buildErrorResponseFromCatch(e);
131
- }
132
- }
133
-
134
- async startCheckoutRouter(routerData: StartCheckoutRequest): Promise<StartCheckoutResponse | ErrorResponse> {
135
- try {
136
- const url = `${this.baseUrlTonder}/api/v1/checkout-router/`;
137
- const data = routerData;
138
- const response = await fetch(url, {
139
- method: "POST",
140
- headers: {
141
- "Content-Type": "application/json",
142
- Authorization: `Token ${this.apiKeyTonder}`,
143
- },
144
- body: JSON.stringify(data),
145
- });
146
- if (response.ok) return await response.json() as StartCheckoutResponse;
147
- throw await this.buildErrorResponse(response);
148
- } catch (e) {
149
- throw this.buildErrorResponseFromCatch(e);
150
- }
151
- }
152
-
153
- async startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse> {
154
-
155
- try {
156
-
157
- const {
158
- order,
159
- total,
160
- customer,
161
- skyflowTokens,
162
- return_url,
163
- isSandbox,
164
- metadata,
165
- currency
166
- } = routerFullData;
167
-
168
- const merchantResult = await this.getBusiness();
169
-
170
- const customerResult : CustomerRegisterResponse | ErrorResponse = await this.customerRegister(customer.email);
171
-
172
- if(customerResult && "auth_token" in customerResult && merchantResult && "reference" in merchantResult) {
173
-
174
- const orderData: CreateOrderRequest = {
175
- business: this.apiKeyTonder,
176
- client: customerResult.auth_token,
177
- billing_address_id: null,
178
- shipping_address_id: null,
179
- amount: total,
180
- reference: merchantResult.reference,
181
- is_oneclick: true,
182
- items: order.items,
183
- };
184
-
185
- const orderResult = await this.createOrder(orderData);
186
-
187
- const now = new Date();
188
-
189
- const dateString = now.toISOString();
190
-
191
- if("id" in orderResult && "id" in customerResult && "business" in merchantResult) {
192
-
193
- const paymentItems: CreatePaymentRequest = {
194
- business_pk: merchantResult.business.pk,
195
- amount: total,
196
- date: dateString,
197
- order_id: orderResult.id,
198
- client_id: customerResult.id
199
- };
200
-
201
- const paymentResult = await this.createPayment(
202
- paymentItems
203
- );
204
-
205
- let deviceSessionIdTonder: any;
206
-
207
- const { openpay_keys, business } = merchantResult
208
-
209
- if (openpay_keys.merchant_id && openpay_keys.public_key) {
210
- deviceSessionIdTonder = await this.getOpenpayDeviceSessionID(
211
- openpay_keys.merchant_id,
212
- openpay_keys.public_key,
213
- isSandbox
214
- );
215
- }
216
-
217
- const routerItems: StartCheckoutRequest = {
218
- card: skyflowTokens,
219
- name: customer.name,
220
- last_name: customer.lastname,
221
- email_client: customer.email,
222
- phone_number: customer.phone,
223
- return_url: return_url,
224
- id_product: "no_id",
225
- quantity_product: 1,
226
- id_ship: "0",
227
- instance_id_ship: "0",
228
- amount: total,
229
- title_ship: "shipping",
230
- description: "transaction",
231
- device_session_id: deviceSessionIdTonder ? deviceSessionIdTonder : null,
232
- token_id: "",
233
- order_id: ("id" in orderResult) && orderResult.id,
234
- business_id: business.pk,
235
- payment_id: ("pk" in paymentResult) && paymentResult.pk,
236
- source: 'sdk',
237
- metadata: metadata,
238
- browser_info: getBrowserInfo(),
239
- currency: currency
240
- };
241
-
242
- const checkoutResult = await this.startCheckoutRouter(routerItems);
243
-
244
- return checkoutResult;
245
-
246
- } else {
247
-
248
- throw new ErrorResponse({
249
- code: "500",
250
- body: orderResult as any,
251
- name: "Keys error",
252
- message: "Order response errors"
253
- } as IErrorResponse)
254
-
255
- }
256
-
257
- } else {
258
-
259
- throw new ErrorResponse({
260
- code: "500",
261
- body: merchantResult as any,
262
- name: "Keys error",
263
- message: "Merchant or customer reposne errors"
264
- } as IErrorResponse)
265
-
266
- }
267
- } catch (e) {
268
-
269
- throw this.buildErrorResponseFromCatch(e);
270
-
271
- }
272
- }
273
-
274
- async getSkyflowTokens({
275
- vault_id,
276
- vault_url,
277
- data,
278
- }: TokensRequest): Promise<any | ErrorResponse> {
279
- const skyflow = Skyflow.init({
280
- vaultID: vault_id,
281
- vaultURL: vault_url,
282
- getBearerToken: async () => await this.getVaultToken(),
283
- options: {
284
- logLevel: Skyflow.LogLevel.ERROR,
285
- env: Skyflow.Env.DEV,
286
- },
287
- });
288
-
289
- const collectContainer: CollectContainer = skyflow.container(
290
- Skyflow.ContainerType.COLLECT
291
- ) as CollectContainer;
292
-
293
- const fieldPromises = await this.getFieldsPromise(data, collectContainer);
294
-
295
- const result = await Promise.all(fieldPromises);
296
-
297
- const mountFail = result.some((item: boolean) => !item);
298
-
299
- if (mountFail) {
300
- throw this.buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));
301
- } else {
302
- try {
303
- const collectResponseSkyflowTonder = await collectContainer.collect() as any;
304
- if (collectResponseSkyflowTonder) return collectResponseSkyflowTonder["records"][0]["fields"];
305
- throw this.buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))
306
- } catch (error) {
307
- throw this.buildErrorResponseFromCatch(error);
308
- }
309
- }
310
- }
311
-
312
- async getVaultToken(): Promise<string> {
313
- try {
314
- const response = await fetch(`${this.baseUrlTonder}/api/v1/vault-token/`, {
315
- method: "GET",
316
- headers: {
317
- Authorization: `Token ${this.apiKeyTonder}`,
318
- },
319
- signal: this.signal,
320
- });
321
- if (response.ok) return (await response.json() as GetVaultTokenResponse)?.token;
322
- throw new Error(`HTTPCODE: ${response.status}`)
323
- } catch (e) {
324
- throw new Error(`Failed to retrieve bearer token; ${typeof e == "string" ? e : (e as Error).message}`)
325
- }
326
- }
327
-
328
- async getFieldsPromise(data: any, collectContainer: CollectContainer): Promise<Promise<boolean>[]> {
329
- const fields = await this.getFields(data, collectContainer);
330
- if (!fields) return [];
331
-
332
- return fields.map((field: { element: CollectElement, key: string }) => {
333
- return new Promise((resolve) => {
334
- const div = document.createElement("div");
335
- div.hidden = true;
336
- div.id = `id-${field.key}`;
337
- document.querySelector(`body`)?.appendChild(div);
338
- setTimeout(() => {
339
- field.element.mount(`#id-${field.key}`);
340
- setInterval(() => {
341
- if (field.element.isMounted()) {
342
- const value = data[field.key];
343
- field.element.update({ value: value });
344
- return resolve(field.element.isMounted());
345
- }
346
- }, 120);
347
- }, 120);
348
- });
349
- })
350
- }
351
-
352
- async registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse> {
353
- try {
354
- const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/`, {
355
- method: 'POST',
356
- headers: {
357
- 'Authorization': `Token ${customerToken}`,
358
- 'Content-Type': 'application/json'
359
- },
360
- signal: this.signal,
361
- body: JSON.stringify(data)
362
- });
363
-
364
- if (response.ok) return await response.json() as RegisterCustomerCardResponse;
365
- throw await this.buildErrorResponse(response);
366
- } catch (error) {
367
- throw this.buildErrorResponseFromCatch(error);
368
- }
369
- }
370
-
371
- async getCustomerCards(customerToken: string, query: string = ""): Promise<GetCustomerCardsResponse | ErrorResponse> {
372
- try {
373
- const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/${query}`, {
374
- method: 'GET',
375
- headers: {
376
- 'Authorization': `Token ${customerToken}`,
377
- 'Content-Type': 'application/json'
378
- },
379
- signal: this.signal,
380
- });
381
-
382
- if (response.ok) return await response.json() as GetCustomerCardsResponse;
383
- throw await this.buildErrorResponse(response);
384
- } catch (error) {
385
- throw this.buildErrorResponseFromCatch(error);
386
- }
387
- }
388
-
389
- async deleteCustomerCard(customerToken: string, skyflowId: string = ""): Promise<Boolean | ErrorResponse> {
390
- try {
391
- const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/${skyflowId}`, {
392
- method: 'DELETE',
393
- headers: {
394
- 'Authorization': `Token ${customerToken}`,
395
- 'Content-Type': 'application/json'
396
- },
397
- signal: this.signal,
398
- });
399
-
400
- if (response.ok) return true;
401
- throw await this.buildErrorResponse(response);
402
- } catch (error) {
403
- throw this.buildErrorResponseFromCatch(error);
404
- }
405
- }
406
-
407
- private buildErrorResponseFromCatch(e: any): ErrorResponse {
408
-
409
- const error = new ErrorResponse({
410
- code: e?.status ? e.status : e.code,
411
- body: e?.body,
412
- name: e ? typeof e == "string" ? "catch" : (e as Error).name : "Error",
413
- message: e ? (typeof e == "string" ? e : (e as Error).message) : "Error",
414
- stack: typeof e == "string" ? undefined : (e as Error).stack,
415
- })
416
-
417
- return error;
418
- }
419
-
420
- private async buildErrorResponse(
421
- response: Response,
422
- stack: string | undefined = undefined
423
- ): Promise<ErrorResponse> {
424
-
425
- let body, status, message = "Error";
426
-
427
- if(response && "json" in response) {
428
- body = await response?.json();
429
- }
430
-
431
- if(response && "status" in response) {
432
- status = response.status.toString();
433
- }
434
-
435
- if(response && "text" in response) {
436
- message = await response.text();
437
- }
438
-
439
- const error = new ErrorResponse({
440
- code: status,
441
- body: body,
442
- name: status,
443
- message: message,
444
- stack,
445
- } as IErrorResponse)
446
-
447
- return error;
448
- }
449
-
450
- private async getFields(data: any, collectContainer: CollectContainer): Promise<{ element: CollectElement, key: string }[]> {
451
- return await Promise.all(
452
- Object.keys(data).map(async (key) => {
453
- const cardHolderNameElement = await collectContainer.create({
454
- table: "cards",
455
- column: key,
456
- type: Skyflow.ElementType.INPUT_FIELD,
457
- });
458
- return { element: cardHolderNameElement, key: key };
459
- })
460
- )
461
- }
462
- }
1
+ import Skyflow from "skyflow-js";
2
+ import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
3
+ import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
4
+ import { APM, Business, TonderAPM } from "../types/commons";
5
+ import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
6
+ import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetVaultTokenResponse, IErrorResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
7
+ import { ErrorResponse } from "./errorResponse";
8
+ import { buildErrorResponse, buildErrorResponseFromCatch, getBrowserInfo, getPaymentMethodDetails } from "../helpers/utils";
9
+ import { ThreeDSHandler } from "./3dsHandler";
10
+ import { getCustomerAPMs } from "../data/api";
11
+
12
+ declare global {
13
+ interface Window {
14
+ OpenPay: any;
15
+ }
16
+ }
17
+
18
+ export type LiteCheckoutConstructor = {
19
+ signal: AbortSignal;
20
+ baseUrlTonder: string;
21
+ apiKeyTonder: string;
22
+ successUrl?: string;
23
+ };
24
+
25
+ export class LiteCheckout implements LiteCheckoutConstructor {
26
+ signal: AbortSignal;
27
+ baseUrlTonder: string;
28
+ apiKeyTonder: string;
29
+ process3ds: ThreeDSHandler;
30
+ successUrl?: string
31
+ activeAPMs: APM[] = []
32
+ constructor({
33
+ signal,
34
+ baseUrlTonder,
35
+ apiKeyTonder,
36
+ successUrl,
37
+ }: LiteCheckoutConstructor) {
38
+ this.baseUrlTonder = baseUrlTonder;
39
+ this.signal = signal;
40
+ this.apiKeyTonder = apiKeyTonder;
41
+ this.successUrl = successUrl;
42
+
43
+ this.process3ds = new ThreeDSHandler({
44
+ apiKey: this.apiKeyTonder,
45
+ baseUrl: this.baseUrlTonder,
46
+ successUrl: successUrl
47
+ })
48
+ this.getActiveAPMs()
49
+ }
50
+
51
+ async getOpenpayDeviceSessionID(
52
+ merchant_id: string,
53
+ public_key: string,
54
+ is_sandbox: boolean
55
+ ): Promise<string | ErrorResponse> {
56
+ try {
57
+ let openpay = await window.OpenPay;
58
+ openpay.setId(merchant_id);
59
+ openpay.setApiKey(public_key);
60
+ openpay.setSandboxMode(is_sandbox);
61
+ return await openpay.deviceData.setup({
62
+ signal: this.signal,
63
+ }) as string;
64
+ } catch (e) {
65
+ throw buildErrorResponseFromCatch(e);
66
+ }
67
+ }
68
+
69
+ async getBusiness(): Promise<GetBusinessResponse | ErrorResponse> {
70
+ try {
71
+ const getBusiness = await fetch(
72
+ `${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,
73
+ {
74
+ headers: {
75
+ Authorization: `Token ${this.apiKeyTonder}`,
76
+ },
77
+ signal: this.signal,
78
+ }
79
+ );
80
+
81
+ if (getBusiness.ok) return (await getBusiness.json()) as Business;
82
+
83
+ throw await buildErrorResponse(getBusiness);
84
+ } catch (e) {
85
+ throw buildErrorResponseFromCatch(e);
86
+ }
87
+ }
88
+
89
+ async verify3dsTransaction () {
90
+ const result3ds = await this.process3ds.verifyTransactionStatus()
91
+ const resultCheckout = await this.resumeCheckout(result3ds)
92
+ this.process3ds.setPayload(resultCheckout)
93
+ if (resultCheckout && 'is_route_finished' in resultCheckout && 'provider' in resultCheckout && resultCheckout.provider === 'tonder') {
94
+ return resultCheckout
95
+ }
96
+ return this.handle3dsRedirect(resultCheckout)
97
+ }
98
+
99
+ async resumeCheckout(response: any) {
100
+ if (["Failed", "Declined", "Cancelled"].includes(response?.status)) {
101
+ const routerItems = {
102
+ checkout_id: response.checkout?.id,
103
+ };
104
+ const routerResponse = await this.handleCheckoutRouter(
105
+ routerItems
106
+ );
107
+ return routerResponse
108
+ }
109
+ return response
110
+ }
111
+
112
+ async handle3dsRedirect(response: ErrorResponse | StartCheckoutResponse | false | undefined) {
113
+ const iframe = response && 'next_action' in response ? response?.next_action?.iframe_resources?.iframe:null
114
+
115
+ if (iframe) {
116
+ this.process3ds.loadIframe()!.then(() => {
117
+ //TODO: Check if this will be necessary on the frontend side
118
+ // after some the tests in production, since the 3DS process
119
+ // doesn't works properly on the sandbox environment
120
+ // setTimeout(() => {
121
+ // process3ds.verifyTransactionStatus();
122
+ // }, 10000);
123
+ this.process3ds.verifyTransactionStatus();
124
+ }).catch((error: any) => {
125
+ console.log('Error loading iframe:', error)
126
+ })
127
+ } else {
128
+ const redirectUrl = this.process3ds.getRedirectUrl()
129
+ if (redirectUrl) {
130
+ this.process3ds.redirectToChallenge()
131
+ } else {
132
+ return response;
133
+ }
134
+ }
135
+ }
136
+
137
+ async customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse> {
138
+ try {
139
+ const url = `${this.baseUrlTonder}/api/v1/customer/`;
140
+ const data = { email: email };
141
+ const response = await fetch(url, {
142
+ method: "POST",
143
+ headers: {
144
+ "Content-Type": "application/json",
145
+ Authorization: `Token ${this.apiKeyTonder}`,
146
+ },
147
+ signal: this.signal,
148
+ body: JSON.stringify(data),
149
+ });
150
+
151
+ if (response.ok) return await response.json() as CustomerRegisterResponse;
152
+ throw await buildErrorResponse(response);
153
+ } catch (e) {
154
+ throw buildErrorResponseFromCatch(e);
155
+ }
156
+ }
157
+
158
+ async createOrder(orderItems: CreateOrderRequest): Promise<CreateOrderResponse | ErrorResponse> {
159
+ try {
160
+ const url = `${this.baseUrlTonder}/api/v1/orders/`;
161
+ const data = orderItems;
162
+ const response = await fetch(url, {
163
+ method: "POST",
164
+ headers: {
165
+ "Content-Type": "application/json",
166
+ Authorization: `Token ${this.apiKeyTonder}`,
167
+ },
168
+ body: JSON.stringify(data),
169
+ });
170
+ if (response.ok) return await response.json() as CreateOrderResponse;
171
+ throw await buildErrorResponse(response);
172
+ } catch (e) {
173
+ throw buildErrorResponseFromCatch(e);
174
+ }
175
+ }
176
+
177
+ async createPayment(paymentItems: CreatePaymentRequest): Promise<CreatePaymentResponse | ErrorResponse> {
178
+ try {
179
+ const url = `${this.baseUrlTonder}/api/v1/business/${paymentItems.business_pk}/payments/`;
180
+ const data = paymentItems;
181
+ const response = await fetch(url, {
182
+ method: "POST",
183
+ headers: {
184
+ "Content-Type": "application/json",
185
+ Authorization: `Token ${this.apiKeyTonder}`,
186
+ },
187
+ body: JSON.stringify(data),
188
+ });
189
+ if (response.ok) return await response.json() as CreatePaymentResponse;
190
+ throw await buildErrorResponse(response);
191
+ } catch (e) {
192
+ throw buildErrorResponseFromCatch(e);
193
+ }
194
+ }
195
+ async handleCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest){
196
+ try {
197
+ const url = `${this.baseUrlTonder}/api/v1/checkout-router/`;
198
+ const data = routerData;
199
+ const response = await fetch(url, {
200
+ method: "POST",
201
+ headers: {
202
+ "Content-Type": "application/json",
203
+ Authorization: `Token ${this.apiKeyTonder}`,
204
+ },
205
+ body: JSON.stringify(data),
206
+ });
207
+ if (response.ok) return await response.json() as StartCheckoutResponse;
208
+ throw await buildErrorResponse(response);
209
+ } catch (e) {
210
+ throw buildErrorResponseFromCatch(e);
211
+ }
212
+ }
213
+
214
+ async startCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
215
+ const checkoutResult = await this.handleCheckoutRouter(routerData);
216
+ const payload = await this.init3DSRedirect(checkoutResult)
217
+ if(payload)
218
+ return checkoutResult;
219
+ }
220
+
221
+ async startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
222
+
223
+ try {
224
+
225
+ const {
226
+ order,
227
+ total,
228
+ customer,
229
+ skyflowTokens,
230
+ return_url,
231
+ isSandbox,
232
+ metadata,
233
+ currency,
234
+ payment_method
235
+ } = routerFullData;
236
+
237
+ const merchantResult = await this.getBusiness();
238
+
239
+ const customerResult : CustomerRegisterResponse | ErrorResponse = await this.customerRegister(customer.email);
240
+
241
+ if(customerResult && "auth_token" in customerResult && merchantResult && "reference" in merchantResult) {
242
+
243
+ const orderData: CreateOrderRequest = {
244
+ business: this.apiKeyTonder,
245
+ client: customerResult.auth_token,
246
+ billing_address_id: null,
247
+ shipping_address_id: null,
248
+ amount: total,
249
+ reference: merchantResult.reference,
250
+ is_oneclick: true,
251
+ items: order.items,
252
+ };
253
+
254
+ const orderResult = await this.createOrder(orderData);
255
+
256
+ const now = new Date();
257
+
258
+ const dateString = now.toISOString();
259
+
260
+ if("id" in orderResult && "id" in customerResult && "business" in merchantResult) {
261
+
262
+ const paymentItems: CreatePaymentRequest = {
263
+ business_pk: merchantResult.business.pk,
264
+ amount: total,
265
+ date: dateString,
266
+ order_id: orderResult.id,
267
+ client_id: customerResult.id
268
+ };
269
+
270
+ const paymentResult = await this.createPayment(
271
+ paymentItems
272
+ );
273
+
274
+ let deviceSessionIdTonder: any;
275
+
276
+ const { openpay_keys, business } = merchantResult
277
+
278
+ if (openpay_keys.merchant_id && openpay_keys.public_key) {
279
+ deviceSessionIdTonder = await this.getOpenpayDeviceSessionID(
280
+ openpay_keys.merchant_id,
281
+ openpay_keys.public_key,
282
+ isSandbox
283
+ );
284
+ }
285
+
286
+ const routerItems: StartCheckoutRequest = {
287
+ name: customer.name,
288
+ last_name: customer.lastname,
289
+ email_client: customer.email,
290
+ phone_number: customer.phone,
291
+ return_url: return_url,
292
+ id_product: "no_id",
293
+ quantity_product: 1,
294
+ id_ship: "0",
295
+ instance_id_ship: "0",
296
+ amount: total,
297
+ title_ship: "shipping",
298
+ description: "transaction",
299
+ device_session_id: deviceSessionIdTonder ? deviceSessionIdTonder : null,
300
+ token_id: "",
301
+ order_id: ("id" in orderResult) && orderResult.id,
302
+ business_id: business.pk,
303
+ payment_id: ("pk" in paymentResult) && paymentResult.pk,
304
+ source: 'sdk',
305
+ metadata: metadata,
306
+ browser_info: getBrowserInfo(),
307
+ currency: currency,
308
+ ...( !!payment_method
309
+ ? {payment_method}
310
+ : {card: skyflowTokens}
311
+ )
312
+ };
313
+
314
+ const checkoutResult = await this.handleCheckoutRouter(routerItems);
315
+ const payload = await this.init3DSRedirect(checkoutResult)
316
+ if(payload)
317
+ return checkoutResult;
318
+ } else {
319
+
320
+ throw new ErrorResponse({
321
+ code: "500",
322
+ body: orderResult as any,
323
+ name: "Keys error",
324
+ message: "Order response errors"
325
+ } as IErrorResponse)
326
+
327
+ }
328
+
329
+ } else {
330
+
331
+ throw new ErrorResponse({
332
+ code: "500",
333
+ body: merchantResult as any,
334
+ name: "Keys error",
335
+ message: "Merchant or customer reposne errors"
336
+ } as IErrorResponse)
337
+
338
+ }
339
+ } catch (e) {
340
+
341
+ throw buildErrorResponseFromCatch(e);
342
+
343
+ }
344
+ }
345
+
346
+ async init3DSRedirect(checkoutResult: ErrorResponse | StartCheckoutResponse){
347
+ this.process3ds.setPayload(checkoutResult)
348
+ return await this.handle3dsRedirect(checkoutResult)
349
+ }
350
+
351
+ async getSkyflowTokens({
352
+ vault_id,
353
+ vault_url,
354
+ data,
355
+ }: TokensRequest): Promise<any | ErrorResponse> {
356
+ const skyflow = Skyflow.init({
357
+ vaultID: vault_id,
358
+ vaultURL: vault_url,
359
+ getBearerToken: async () => await this.getVaultToken(),
360
+ options: {
361
+ logLevel: Skyflow.LogLevel.ERROR,
362
+ env: Skyflow.Env.DEV,
363
+ },
364
+ });
365
+
366
+ const collectContainer: CollectContainer = skyflow.container(
367
+ Skyflow.ContainerType.COLLECT
368
+ ) as CollectContainer;
369
+
370
+ const fieldPromises = await this.getFieldsPromise(data, collectContainer);
371
+
372
+ const result = await Promise.all(fieldPromises);
373
+
374
+ const mountFail = result.some((item: boolean) => !item);
375
+
376
+ if (mountFail) {
377
+ throw buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));
378
+ } else {
379
+ try {
380
+ const collectResponseSkyflowTonder = await collectContainer.collect() as any;
381
+ if (collectResponseSkyflowTonder) return collectResponseSkyflowTonder["records"][0]["fields"];
382
+ throw buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))
383
+ } catch (error) {
384
+ throw buildErrorResponseFromCatch(error);
385
+ }
386
+ }
387
+ }
388
+
389
+ async getVaultToken(): Promise<string> {
390
+ try {
391
+ const response = await fetch(`${this.baseUrlTonder}/api/v1/vault-token/`, {
392
+ method: "GET",
393
+ headers: {
394
+ Authorization: `Token ${this.apiKeyTonder}`,
395
+ },
396
+ signal: this.signal,
397
+ });
398
+ if (response.ok) return (await response.json() as GetVaultTokenResponse)?.token;
399
+ throw new Error(`HTTPCODE: ${response.status}`)
400
+ } catch (e) {
401
+ throw new Error(`Failed to retrieve bearer token; ${typeof e == "string" ? e : (e as Error).message}`)
402
+ }
403
+ }
404
+
405
+ async getFieldsPromise(data: any, collectContainer: CollectContainer): Promise<Promise<boolean>[]> {
406
+ const fields = await this.getFields(data, collectContainer);
407
+ if (!fields) return [];
408
+
409
+ return fields.map((field: { element: CollectElement, key: string }) => {
410
+ return new Promise((resolve) => {
411
+ const div = document.createElement("div");
412
+ div.hidden = true;
413
+ div.id = `id-${field.key}`;
414
+ document.querySelector(`body`)?.appendChild(div);
415
+ setTimeout(() => {
416
+ field.element.mount(`#id-${field.key}`);
417
+ setInterval(() => {
418
+ if (field.element.isMounted()) {
419
+ const value = data[field.key];
420
+ field.element.update({ value: value });
421
+ return resolve(field.element.isMounted());
422
+ }
423
+ }, 120);
424
+ }, 120);
425
+ });
426
+ })
427
+ }
428
+
429
+ async registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse> {
430
+ try {
431
+ const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/`, {
432
+ method: 'POST',
433
+ headers: {
434
+ 'Authorization': `Token ${customerToken}`,
435
+ 'Content-Type': 'application/json'
436
+ },
437
+ signal: this.signal,
438
+ body: JSON.stringify(data)
439
+ });
440
+
441
+ if (response.ok) return await response.json() as RegisterCustomerCardResponse;
442
+ throw await buildErrorResponse(response);
443
+ } catch (error) {
444
+ throw buildErrorResponseFromCatch(error);
445
+ }
446
+ }
447
+
448
+ async getCustomerCards(customerToken: string, query: string = ""): Promise<GetCustomerCardsResponse | ErrorResponse> {
449
+ try {
450
+ const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/${query}`, {
451
+ method: 'GET',
452
+ headers: {
453
+ 'Authorization': `Token ${customerToken}`,
454
+ 'Content-Type': 'application/json'
455
+ },
456
+ signal: this.signal,
457
+ });
458
+
459
+ if (response.ok) return await response.json() as GetCustomerCardsResponse;
460
+ throw await buildErrorResponse(response);
461
+ } catch (error) {
462
+ throw buildErrorResponseFromCatch(error);
463
+ }
464
+ }
465
+
466
+ async deleteCustomerCard(customerToken: string, skyflowId: string = ""): Promise<Boolean | ErrorResponse> {
467
+ try {
468
+ const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/${skyflowId}`, {
469
+ method: 'DELETE',
470
+ headers: {
471
+ 'Authorization': `Token ${customerToken}`,
472
+ 'Content-Type': 'application/json'
473
+ },
474
+ signal: this.signal,
475
+ });
476
+
477
+ if (response.ok) return true;
478
+ throw await buildErrorResponse(response);
479
+ } catch (error) {
480
+ throw buildErrorResponseFromCatch(error);
481
+ }
482
+ }
483
+
484
+ private async getFields(data: any, collectContainer: CollectContainer): Promise<{ element: CollectElement, key: string }[]> {
485
+ return await Promise.all(
486
+ Object.keys(data).map(async (key) => {
487
+ const cardHolderNameElement = await collectContainer.create({
488
+ table: "cards",
489
+ column: key,
490
+ type: Skyflow.ElementType.INPUT_FIELD,
491
+ });
492
+ return { element: cardHolderNameElement, key: key };
493
+ })
494
+ )
495
+ }
496
+
497
+ async getActiveAPMs(): Promise<APM[]> {
498
+ try {
499
+ const apms_response = await getCustomerAPMs(this.baseUrlTonder, this.apiKeyTonder);
500
+ const apms_results = apms_response && apms_response['results'] && apms_response['results'].length > 0 ? apms_response['results'] : []
501
+ this.activeAPMs = apms_results
502
+ .filter((apmItem: TonderAPM) =>
503
+ apmItem.category.toLowerCase() !== 'cards')
504
+ .map((apmItem: TonderAPM) => {
505
+ const apm: APM = {
506
+ id: apmItem.pk,
507
+ payment_method: apmItem.payment_method,
508
+ priority: apmItem.priority,
509
+ category: apmItem.category,
510
+ ...getPaymentMethodDetails(apmItem.payment_method,)
511
+ }
512
+ return apm;
513
+ }).sort((a: APM, b: APM) => a.priority - b.priority);
514
+
515
+ return this.activeAPMs
516
+ } catch (e) {
517
+ console.error("Error getting APMS", e);
518
+ return [];
519
+ }
520
+ }
521
+ }