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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,318 +1,356 @@
1
- import {ThreeDSHandler} from "./3dsHandler";
2
- import {Business, IConfigureCheckout, IInlineCheckoutBaseOptions} from "../types/commons";
3
- import {ErrorResponse} from "./errorResponse";
4
- import {fetchBusiness} from "../data/businessApi";
5
- import {injectMercadoPagoSecurity} from "../helpers/mercadopago";
6
- import {TONDER_URL_BY_MODE} from "../shared/constants/tonderUrl";
7
- import {ICardFields, IItem, IProcessPaymentRequest, IStartCheckoutResponse} from "../types/checkout";
8
- import {StartCheckoutResponse} from "../types/responses";
9
- import {createOrder, createPayment, startCheckoutRouter} from "../data/checkoutApi";
10
- import {getOpenpayDeviceSessionID} from "../data/openPayApi";
11
- import {getBrowserInfo} from "../helpers/utils";
12
- import {registerOrFetchCustomer} from "../data/customerApi";
13
- import {ICustomer} from "../types/customer";
14
-
1
+ import { ThreeDSHandler } from "./3dsHandler";
2
+ import { ErrorResponse } from "./errorResponse";
3
+ import { fetchBusiness } from "../data/businessApi";
4
+ import { injectMercadoPagoSecurity } from "../helpers/mercadopago";
5
+ import { TONDER_URL_BY_MODE } from "../shared/constants/tonderUrl";
6
+ import {
7
+ createOrder,
8
+ createPayment,
9
+ startCheckoutRouter,
10
+ } from "../data/checkoutApi";
11
+ import { getOpenpayDeviceSessionID } from "../data/openPayApi";
12
+ import { getBrowserInfo } from "../helpers/utils";
13
+ import { registerOrFetchCustomer } from "../data/customerApi";
14
+ import {
15
+ Business,
16
+ ICustomer,
17
+ IItem,
18
+ IInlineCheckoutBaseOptions,
19
+ IConfigureCheckout,
20
+ IProcessPaymentRequest,
21
+ IStartCheckoutResponse,
22
+ StartCheckoutResponse,
23
+ ICardFields,
24
+ } from "../types";
15
25
  export class BaseInlineCheckout {
16
- baseUrl = "";
17
- cartTotal = "0";
18
- process3ds: ThreeDSHandler;
19
- mode?: "production" | "sandbox" | "stage" | "development" | undefined;
20
- apiKeyTonder: string;
21
- returnUrl: string;
22
- callBack?: ((response: any) => void) | undefined;
23
- merchantData?: Business;
24
- abortController: AbortController;
25
-
26
- firstName?: string
27
- lastName?: string
28
- country?: string
29
- address?: string
30
- city?: string
31
- state?: string
32
- postCode?: string
33
- email?: string
34
- phone?: string
35
- customer?: ICustomer
36
-
37
- cartItems?: IItem[]
38
- metadata = {}
39
- card? = {}
40
- currency?: string = ""
41
-
42
- #customerData?: Record<string, any>;
43
-
44
- constructor({ mode = "stage", apiKey, apiKeyTonder, returnUrl, callBack = () => {} }: IInlineCheckoutBaseOptions) {
45
- this.apiKeyTonder = apiKey || apiKeyTonder || '';
46
- this.returnUrl = returnUrl;
47
- this.callBack = callBack;
48
- this.mode = mode;
49
- this.baseUrl = TONDER_URL_BY_MODE[this.mode] || TONDER_URL_BY_MODE["stage"];
50
- this.abortController = new AbortController();
51
- this.process3ds = new ThreeDSHandler({
52
- apiKey: apiKey,
53
- baseUrl: this.baseUrl,
54
- });
55
- }
56
-
57
-
58
- configureCheckout(data: IConfigureCheckout) {
59
- if ("customer" in data) this.#handleCustomer(data["customer"]);
60
- }
61
-
62
- async verify3dsTransaction () {
63
- const result3ds = await this.process3ds.verifyTransactionStatus()
64
- const resultCheckout = await this.#resumeCheckout(result3ds)
65
- this.process3ds.setPayload(resultCheckout)
66
- return this._handle3dsRedirect(resultCheckout)
67
- }
68
-
69
- payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse> {
70
- return new Promise(async (resolve, reject) => {
71
- try {
72
- this.#handleCustomer(data.customer);
73
- this._setCartTotal(data.cart?.total);
74
- this.#setCartItems(data.cart?.items);
75
- this.#handleMetadata(data);
76
- this.#handleCurrency(data);
77
- this.#handleCard(data);
78
- const response = await this._checkout(data);
79
- this.process3ds.setPayload(response);
80
- if(this.callBack)
81
- this.callBack!(response);
82
- const payload = await this._handle3dsRedirect(response);
83
- if (payload) {
84
- resolve(response);
85
- }
86
- } catch (error) {
87
- reject(error);
88
- }
89
- });
90
- }
91
-
92
- async _initializeCheckout() {
93
- const business_response = await this._fetchMerchantData();
94
-
95
- if (!!business_response && !!business_response.mercado_pago && business_response.mercado_pago.active) {
96
- injectMercadoPagoSecurity();
26
+ baseUrl = "";
27
+ cartTotal = "0";
28
+ process3ds: ThreeDSHandler;
29
+ mode?: "production" | "sandbox" | "stage" | "development" | undefined;
30
+ apiKeyTonder: string;
31
+ returnUrl: string;
32
+ callBack?: ((response: any) => void) | undefined;
33
+ merchantData?: Business;
34
+ abortController: AbortController;
35
+
36
+ firstName?: string;
37
+ lastName?: string;
38
+ country?: string;
39
+ address?: string;
40
+ city?: string;
41
+ state?: string;
42
+ postCode?: string;
43
+ email?: string;
44
+ phone?: string;
45
+ customer?: ICustomer;
46
+
47
+ cartItems?: IItem[];
48
+ metadata = {};
49
+ card? = {};
50
+ currency?: string = "";
51
+
52
+ #customerData?: Record<string, any>;
53
+
54
+ constructor({
55
+ mode = "stage",
56
+ apiKey,
57
+ apiKeyTonder,
58
+ returnUrl,
59
+ callBack = () => {},
60
+ }: IInlineCheckoutBaseOptions) {
61
+ this.apiKeyTonder = apiKey || apiKeyTonder || "";
62
+ this.returnUrl = returnUrl;
63
+ this.callBack = callBack;
64
+ this.mode = mode;
65
+ this.baseUrl = TONDER_URL_BY_MODE[this.mode] || TONDER_URL_BY_MODE["stage"];
66
+ this.abortController = new AbortController();
67
+ this.process3ds = new ThreeDSHandler({
68
+ apiKey: apiKey,
69
+ baseUrl: this.baseUrl,
70
+ });
71
+ }
72
+
73
+ configureCheckout(data: IConfigureCheckout) {
74
+ if ("customer" in data) this.#handleCustomer(data["customer"]);
75
+ }
76
+
77
+ async verify3dsTransaction() {
78
+ const result3ds = await this.process3ds.verifyTransactionStatus();
79
+ const resultCheckout = await this.#resumeCheckout(result3ds);
80
+ this.process3ds.setPayload(resultCheckout);
81
+ return this._handle3dsRedirect(resultCheckout);
82
+ }
83
+
84
+ payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse> {
85
+ return new Promise(async (resolve, reject) => {
86
+ try {
87
+ this.#handleCustomer(data.customer);
88
+ this._setCartTotal(data.cart?.total);
89
+ this.#setCartItems(data.cart?.items);
90
+ this.#handleMetadata(data);
91
+ this.#handleCurrency(data);
92
+ this.#handleCard(data);
93
+ const response = await this._checkout(data);
94
+ this.process3ds.setPayload(response);
95
+ if (this.callBack) this.callBack!(response);
96
+ const payload = await this._handle3dsRedirect(response);
97
+ if (payload) {
98
+ resolve(response);
97
99
  }
100
+ } catch (error) {
101
+ reject(error);
102
+ }
103
+ });
104
+ }
105
+
106
+ async _initializeCheckout() {
107
+ const business_response = await this._fetchMerchantData();
108
+
109
+ if (
110
+ !!business_response &&
111
+ !!business_response.mercado_pago &&
112
+ business_response.mercado_pago.active
113
+ ) {
114
+ injectMercadoPagoSecurity();
98
115
  }
99
-
100
- async _checkout(data: any): Promise<any> {
101
- throw new Error(
102
- "The #checkout method should be implement in child classes.",
103
- );
104
- }
105
-
106
- _setCartTotal(total: string | number) {
107
- throw new Error(
108
- "The #setCartTotal method should be implement in child classes.",
116
+ }
117
+
118
+ async _checkout(data: any): Promise<any> {
119
+ throw new Error(
120
+ "The #checkout method should be implement in child classes.",
121
+ );
122
+ }
123
+
124
+ _setCartTotal(total: string | number) {
125
+ throw new Error(
126
+ "The #setCartTotal method should be implement in child classes.",
127
+ );
128
+ }
129
+
130
+ async _getCustomer(signal: AbortSignal | null = null) {
131
+ if (!!this.#customerData) return this.#customerData!;
132
+
133
+ this.#customerData = await registerOrFetchCustomer(
134
+ this.baseUrl,
135
+ this.apiKeyTonder,
136
+ this.customer!,
137
+ signal,
138
+ );
139
+ return this.#customerData!;
140
+ }
141
+
142
+ async _handleCheckout({
143
+ card,
144
+ payment_method,
145
+ customer,
146
+ isSandbox,
147
+ }: {
148
+ card?: string;
149
+ payment_method?: string;
150
+ customer: Record<string, any>;
151
+ isSandbox?: boolean;
152
+ }) {
153
+ const { openpay_keys, reference, business } = this.merchantData!;
154
+ const total = Number(this.cartTotal);
155
+ try {
156
+ let deviceSessionIdTonder;
157
+ if (
158
+ !deviceSessionIdTonder &&
159
+ openpay_keys.merchant_id &&
160
+ openpay_keys.public_key
161
+ ) {
162
+ deviceSessionIdTonder = await getOpenpayDeviceSessionID(
163
+ openpay_keys.merchant_id,
164
+ openpay_keys.public_key,
165
+ isSandbox,
166
+ this.abortController.signal,
109
167
  );
168
+ }
169
+
170
+ const { id, auth_token } = customer;
171
+
172
+ const orderItems = {
173
+ business: this.apiKeyTonder,
174
+ client: auth_token,
175
+ billing_address_id: null,
176
+ shipping_address_id: null,
177
+ amount: total,
178
+ status: "A",
179
+ reference: reference,
180
+ is_oneclick: true,
181
+ items: this.cartItems!,
182
+ };
183
+ const jsonResponseOrder = await createOrder(
184
+ this.baseUrl,
185
+ this.apiKeyTonder,
186
+ orderItems,
187
+ );
188
+
189
+ // Create payment
190
+ const now = new Date();
191
+ const dateString = now.toISOString();
192
+
193
+ const paymentItems = {
194
+ business_pk: business.pk,
195
+ client_id: id,
196
+ amount: total,
197
+ date: dateString,
198
+ order_id: jsonResponseOrder.id,
199
+ };
200
+ const jsonResponsePayment = await createPayment(
201
+ this.baseUrl,
202
+ this.apiKeyTonder,
203
+ paymentItems,
204
+ );
205
+
206
+ // Checkout router
207
+ const routerItems = {
208
+ name: this.firstName || "",
209
+ last_name: this.lastName || "",
210
+ email_client: this.email,
211
+ phone_number: this.phone,
212
+ return_url: this.returnUrl,
213
+ id_product: "no_id",
214
+ quantity_product: 1,
215
+ id_ship: "0",
216
+ instance_id_ship: "0",
217
+ amount: total,
218
+ title_ship: "shipping",
219
+ description: "transaction",
220
+ device_session_id: deviceSessionIdTonder ? deviceSessionIdTonder : null,
221
+ token_id: "",
222
+ order_id: jsonResponseOrder.id,
223
+ business_id: business.pk,
224
+ payment_id: jsonResponsePayment.pk,
225
+ source: "sdk",
226
+ metadata: this.metadata,
227
+ browser_info: getBrowserInfo(),
228
+ currency: this.currency!,
229
+ ...(!!payment_method ? { payment_method } : { card }),
230
+ };
231
+
232
+ const jsonResponseRouter = await startCheckoutRouter(
233
+ this.baseUrl,
234
+ this.apiKeyTonder,
235
+ routerItems,
236
+ );
237
+
238
+ if (jsonResponseRouter) {
239
+ return jsonResponseRouter;
240
+ } else {
241
+ return false;
242
+ }
243
+ } catch (error) {
244
+ console.log(error);
245
+ throw error;
110
246
  }
111
-
112
- async _getCustomer(signal: AbortSignal | null = null) {
113
- if (!!this.#customerData) return this.#customerData!;
114
-
115
- this.#customerData = await registerOrFetchCustomer(
116
- this.baseUrl,
117
- this.apiKeyTonder,
118
- this.customer!,
119
- signal
247
+ }
248
+
249
+ async _fetchMerchantData() {
250
+ try {
251
+ if (!this.merchantData) {
252
+ this.merchantData = await fetchBusiness(
253
+ this.baseUrl,
254
+ this.apiKeyTonder,
255
+ this.abortController.signal,
120
256
  );
121
- return this.#customerData!;
257
+ }
258
+ return this.merchantData;
259
+ } catch (e) {
260
+ return this.merchantData;
122
261
  }
123
-
124
- async _handleCheckout({ card, payment_method, customer, isSandbox }: {card?: string; payment_method?: string; customer: Record<string, any>; isSandbox?: boolean}) {
125
- const { openpay_keys, reference, business } = this.merchantData!;
126
- const total = Number(this.cartTotal);
127
- try {
128
- let deviceSessionIdTonder;
129
- if (
130
- !deviceSessionIdTonder &&
131
- openpay_keys.merchant_id &&
132
- openpay_keys.public_key
133
- ) {
134
- deviceSessionIdTonder = await getOpenpayDeviceSessionID(
135
- openpay_keys.merchant_id,
136
- openpay_keys.public_key,
137
- isSandbox,
138
- this.abortController.signal,
139
- );
140
- }
141
-
142
- const { id, auth_token } = customer;
143
-
144
- const orderItems = {
145
- business: this.apiKeyTonder,
146
- client: auth_token,
147
- billing_address_id: null,
148
- shipping_address_id: null,
149
- amount: total,
150
- status: "A",
151
- reference: reference,
152
- is_oneclick: true,
153
- items: this.cartItems!,
154
- };
155
- const jsonResponseOrder = await createOrder(
156
- this.baseUrl,
157
- this.apiKeyTonder,
158
- orderItems,
159
- );
160
-
161
- // Create payment
162
- const now = new Date();
163
- const dateString = now.toISOString();
164
-
165
- const paymentItems = {
166
- business_pk: business.pk,
167
- client_id: id,
168
- amount: total,
169
- date: dateString,
170
- order_id: jsonResponseOrder.id,
171
- };
172
- const jsonResponsePayment = await createPayment(
173
- this.baseUrl,
174
- this.apiKeyTonder,
175
- paymentItems,
176
- );
177
-
178
- // Checkout router
179
- const routerItems = {
180
- name: this.firstName || "",
181
- last_name: this.lastName || "",
182
- email_client: this.email,
183
- phone_number: this.phone,
184
- return_url: this.returnUrl,
185
- id_product: "no_id",
186
- quantity_product: 1,
187
- id_ship: "0",
188
- instance_id_ship: "0",
189
- amount: total,
190
- title_ship: "shipping",
191
- description: "transaction",
192
- device_session_id: deviceSessionIdTonder ? deviceSessionIdTonder : null,
193
- token_id: "",
194
- order_id: jsonResponseOrder.id,
195
- business_id: business.pk,
196
- payment_id: jsonResponsePayment.pk,
197
- source: "sdk",
198
- metadata: this.metadata,
199
- browser_info: getBrowserInfo(),
200
- currency: this.currency!,
201
- ...(!!payment_method ? { payment_method } : { card }),
202
- };
203
-
204
- const jsonResponseRouter = await startCheckoutRouter(
205
- this.baseUrl,
206
- this.apiKeyTonder,
207
- routerItems,
208
- );
209
-
210
- if (jsonResponseRouter) {
211
- return jsonResponseRouter;
212
- } else {
213
- return false;
214
- }
215
- } catch (error) {
216
- console.log(error);
217
- throw error;
218
- }
219
- }
220
-
221
-
222
- async _fetchMerchantData() {
223
- try {
224
- if (!this.merchantData){
225
- this.merchantData = await fetchBusiness(this.baseUrl, this.apiKeyTonder, this.abortController.signal);
226
- }
227
- return this.merchantData
228
- }catch(e){
229
- return this.merchantData
230
- }
231
- }
232
-
233
- #handleCustomer(customer: ICustomer) {
234
- if (!customer) return;
235
-
236
- this.firstName = customer?.firstName;
237
- this.lastName = customer?.lastName;
238
- this.country = customer?.country;
239
- this.address = customer?.street;
240
- this.city = customer?.city;
241
- this.state = customer?.state;
242
- this.postCode = customer?.postCode;
243
- this.email = customer?.email;
244
- this.phone = customer?.phone;
245
- this.customer = customer;
246
- }
247
-
248
- #setCartItems(items: IItem[]) {
249
- this.cartItems = items;
250
- }
251
-
252
- #handleMetadata(data: { metadata?: any }) {
253
- this.metadata = data?.metadata;
262
+ }
263
+
264
+ #handleCustomer(customer: ICustomer) {
265
+ if (!customer) return;
266
+
267
+ this.firstName = customer?.firstName;
268
+ this.lastName = customer?.lastName;
269
+ this.country = customer?.country;
270
+ this.address = customer?.street;
271
+ this.city = customer?.city;
272
+ this.state = customer?.state;
273
+ this.postCode = customer?.postCode;
274
+ this.email = customer?.email;
275
+ this.phone = customer?.phone;
276
+ this.customer = customer;
277
+ }
278
+
279
+ #setCartItems(items: IItem[]) {
280
+ this.cartItems = items;
281
+ }
282
+
283
+ #handleMetadata(data: { metadata?: any }) {
284
+ this.metadata = data?.metadata;
285
+ }
286
+
287
+ #handleCurrency(data: { currency?: string }) {
288
+ this.currency = data?.currency;
289
+ }
290
+
291
+ #handleCard(data: { card?: ICardFields | string }) {
292
+ this.card = data?.card;
293
+ }
294
+
295
+ // TODO: Make private after remove deprecated functions of liteCheckout
296
+ async _handle3dsRedirect(
297
+ response: ErrorResponse | StartCheckoutResponse | false | undefined,
298
+ ) {
299
+ const iframe =
300
+ response && "next_action" in response
301
+ ? response?.next_action?.iframe_resources?.iframe
302
+ : null;
303
+
304
+ if (iframe) {
305
+ this.process3ds
306
+ .loadIframe()!
307
+ .then(() => {
308
+ //TODO: Check if this will be necessary on the frontend side
309
+ // after some the tests in production, since the 3DS process
310
+ // doesn't works properly on the sandbox environment
311
+ // setTimeout(() => {
312
+ // process3ds.verifyTransactionStatus();
313
+ // }, 10000);
314
+ this.process3ds.verifyTransactionStatus();
315
+ })
316
+ .catch((error) => {
317
+ console.log("Error loading iframe:", error);
318
+ });
319
+ } else {
320
+ const redirectUrl = this.process3ds.getRedirectUrl();
321
+ if (redirectUrl) {
322
+ this.process3ds.redirectToChallenge();
323
+ } else {
324
+ return response;
325
+ }
254
326
  }
327
+ }
255
328
 
256
- #handleCurrency(data: { currency?: string }) {
257
- this.currency = data?.currency;
329
+ async #resumeCheckout(response: any) {
330
+ // Stop the routing process if the transaction is either hard declined or successful
331
+ if (response?.decline?.error_type === "Hard") {
332
+ return response;
258
333
  }
259
334
 
260
- #handleCard(data: { card?: ICardFields | string }) {
261
- this.card = data?.card;
335
+ if (["Success", "Authorized"].includes(response?.transaction_status)) {
336
+ return response;
262
337
  }
263
338
 
264
- // TODO: Make private after remove deprecated functions of liteCheckout
265
- async _handle3dsRedirect(response: ErrorResponse | StartCheckoutResponse | false | undefined) {
266
- const iframe = response && 'next_action' in response ? response?.next_action?.iframe_resources?.iframe:null
267
-
268
- if (iframe) {
269
- this.process3ds.loadIframe()!.then(() => {
270
- //TODO: Check if this will be necessary on the frontend side
271
- // after some the tests in production, since the 3DS process
272
- // doesn't works properly on the sandbox environment
273
- // setTimeout(() => {
274
- // process3ds.verifyTransactionStatus();
275
- // }, 10000);
276
- this.process3ds.verifyTransactionStatus();
277
- }).catch((error) => {
278
- console.log('Error loading iframe:', error)
279
- })
280
- } else {
281
- const redirectUrl = this.process3ds.getRedirectUrl()
282
- if (redirectUrl) {
283
- this.process3ds.redirectToChallenge()
284
- } else {
285
- return response;
286
- }
287
- }
288
- }
289
-
290
- async #resumeCheckout(response: any) {
291
- // Stop the routing process if the transaction is either hard declined or successful
292
- if (response?.decline?.error_type === "Hard") {
293
- return response
294
- }
295
-
296
- if (["Success", "Authorized"].includes(response?.transaction_status)) {
297
- return response;
298
- }
339
+ if (response) {
340
+ const routerItems = {
341
+ checkout_id: response.checkout?.id,
342
+ };
299
343
 
300
- if (response) {
301
- const routerItems = {
302
- checkout_id: response.checkout?.id,
303
- };
304
-
305
- try{
306
- return await startCheckoutRouter(
307
- this.baseUrl,
308
- this.apiKeyTonder,
309
- routerItems
310
- )
311
- }catch (error){
312
- // throw error
313
- }
314
- return response
315
- }
344
+ try {
345
+ return await startCheckoutRouter(
346
+ this.baseUrl,
347
+ this.apiKeyTonder,
348
+ routerItems,
349
+ );
350
+ } catch (error) {
351
+ // throw error
352
+ }
353
+ return response;
316
354
  }
317
-
318
- }
355
+ }
356
+ }
@@ -1,4 +1,4 @@
1
- import { IErrorResponse } from "../types/responses";
1
+ import { IErrorResponse } from "../types";
2
2
 
3
3
  export class ErrorResponse implements IErrorResponse {
4
4
  code?: string | undefined;