tonder-web-sdk 1.12.0-beta.1 → 1.12.0-beta.11

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tonder-web-sdk",
3
- "version": "1.12.0-beta.1",
3
+ "version": "1.12.0-beta.11",
4
4
  "description": "tonder sdk for integrations",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -1,20 +1,19 @@
1
1
  import { ThreeDSHandler } from "./3dsHandler.js";
2
- import {createOrder, fetchBusiness, getOpenpayDeviceSessionID, registerOrFetchCustomer} from "../data";
2
+ import {
3
+ createOrder,
4
+ fetchBusiness,
5
+ getOpenpayDeviceSessionID,
6
+ registerOrFetchCustomer,
7
+ } from "../data";
3
8
  import { TONDER_URL_BY_MODE } from "../shared/constants/tonderUrl";
4
9
  import { globalLoader } from "./globalLoader";
5
- import {createPayment, startCheckoutRouter} from "../data/checkoutApi";
6
- import {getBrowserInfo, injectMercadoPagoSecurity} from "../helpers/utils";
10
+ import { createPayment, startCheckoutRouter } from "../data/checkoutApi";
11
+ import { getBrowserInfo, injectMercadoPagoSecurity } from "../helpers/utils";
7
12
 
8
13
  export class BaseInlineCheckout {
9
14
  baseUrl = "";
10
- cartTotal = "0"
11
- constructor({
12
- mode = "stage",
13
- apiKey,
14
- returnUrl,
15
- callBack = () => {},
16
- sdkMode = "full",
17
- }) {
15
+ cartTotal = "0";
16
+ constructor({ mode = "stage", apiKey, returnUrl, callBack = () => {} }) {
18
17
  this.apiKeyTonder = apiKey;
19
18
  this.returnUrl = returnUrl;
20
19
  this.callBack = callBack;
@@ -25,22 +24,43 @@ export class BaseInlineCheckout {
25
24
  apiKey: apiKey,
26
25
  baseUrl: this.baseUrl,
27
26
  });
28
- this.sdkMode = sdkMode;
29
27
  }
30
28
 
29
+ /**
30
+ * The configureCheckout function allows you to set initial information, such as the customer's email, which is used to retrieve a list of saved cards.
31
+ * @param {import("../../types").IConfigureCheckout} data - Configuration data including customer information and potentially other settings.
32
+ * @returns {Promise<void>}.
33
+ * @public
34
+ */
31
35
  configureCheckout(data) {
32
36
  if ("customer" in data) this.#handleCustomer(data["customer"]);
33
37
  }
34
38
 
39
+ /**
40
+ * Verifies the 3DS transaction status.
41
+ * @returns {Promise<import("../../types").ITransaction | void>} The result of the 3DS verification and checkout resumption.
42
+ * @public
43
+ */
35
44
  async verify3dsTransaction() {
36
- globalLoader.show(); // TODO: HOW?
45
+ globalLoader.show();
37
46
  const result3ds = await this.process3ds.verifyTransactionStatus();
38
47
  const resultCheckout = await this.#resumeCheckout(result3ds);
39
48
  this.process3ds.setPayload(resultCheckout);
40
- globalLoader.remove(); // TODO: HOW?
49
+ globalLoader.remove();
41
50
  return this.#handle3dsRedirect(resultCheckout);
42
51
  }
43
52
 
53
+ /**
54
+ * Processes a payment.
55
+ * @param {import("../../types").IProcessPaymentRequest} data - Payment data including customer, cart, and other relevant information.
56
+ * @returns {Promise<import("../../types").IStartCheckoutResponse>} A promise that resolves with the payment response or 3DS redirect or is rejected with an error.
57
+ *
58
+ * @throws {Error} Throws an error if the checkout process fails. The error object contains
59
+ * additional `details` property with the response from the server if available.
60
+ * @property {import("../../types").IStartCheckoutErrorResponse} error.details - The response body from the server when an error occurs.
61
+ *
62
+ * @public
63
+ */
44
64
  payment(data) {
45
65
  return new Promise(async (resolve, reject) => {
46
66
  try {
@@ -92,13 +112,7 @@ export class BaseInlineCheckout {
92
112
  );
93
113
  }
94
114
 
95
- async _handleCheckout(
96
- {
97
- card,
98
- payment_method,
99
- customer
100
- }
101
- ) {
115
+ async _handleCheckout({ card, payment_method, customer }) {
102
116
  const { openpay_keys, reference, business } = this.merchantData;
103
117
  const total = Number(this.cartTotal);
104
118
 
@@ -4,81 +4,163 @@ import {
4
4
  fetchCustomerCards,
5
5
  saveCustomerCard,
6
6
  removeCustomerCard,
7
+ registerOrFetchCustomer,
7
8
  } from "../data";
8
- import { buildErrorResponseFromCatch } from "../helpers/utils";
9
- import { getVaultToken } from "../data/skyflowApi";
10
9
  import { getSkyflowTokens } from "../helpers/skyflow";
10
+ import { getPaymentMethodDetails } from "../shared/catalog/paymentMethodsCatalog";
11
+ import { formatPublicErrorResponse } from "../helpers/utils";
12
+ import { MESSAGES } from "../shared/constants/messages";
11
13
 
12
14
  export class LiteInlineCheckout extends BaseInlineCheckout {
15
+ #customerData;
13
16
  constructor({ mode = "stage", apiKey, returnUrl, callBack = () => {} }) {
14
17
  super({ mode, apiKey, returnUrl, callBack });
15
18
  }
16
19
 
20
+ /**
21
+ * Initializes and prepares the checkout for use.
22
+ * This method set up the initial environment.
23
+ * @returns {Promise<void>} A promise that resolves when the checkout has been initialized.
24
+ * @throws {Error} If there's any problem during the checkout initialization.
25
+ * @public
26
+ */
17
27
  async injectCheckout() {
18
28
  await this._initializeCheckout();
19
29
  }
20
30
 
21
31
  /**
22
32
  * Retrieves the list of cards associated with a customer.
23
- * @param {string} authToken - The customer's authentication token.
24
- * @param {string} businessId - The business primary key.
25
- * @returns {Promise<Object>} A promise that resolves with the customer's card data.
33
+ * @returns {Promise<import("../../types").ICustomerCardsResponse>} A promise that resolves with the customer's card data.
34
+ *
35
+ * @throws {import("../../types").IPublicError} Throws an error object if the operation fails.
36
+ *
26
37
  * @public
27
38
  */
28
- async getCustomerCards(authToken, businessId) {
29
- return await fetchCustomerCards(this.baseUrl, authToken, businessId);
39
+ async getCustomerCards() {
40
+ try {
41
+ const { auth_token } = await this.#getCustomer();
42
+ return await fetchCustomerCards(
43
+ this.baseUrl,
44
+ auth_token,
45
+ this.merchantData.business.pk,
46
+ );
47
+ } catch (error) {
48
+ throw formatPublicErrorResponse(
49
+ {
50
+ message: MESSAGES.getCardsError,
51
+ },
52
+ error,
53
+ );
54
+ }
30
55
  }
31
56
 
32
57
  /**
33
58
  * Saves a card to a customer's account. This method can be used to add a new card
34
59
  * or update an existing one.
35
- * @param {string} authToken - The customer's authentication token.
36
- * @param {string} businessId - The business primary key.
37
- * @param {Object} card - The card information to be saved.
38
- * @returns {Promise<Object>} A promise that resolves with the saved card data.
60
+ * @param {import("../../types").ISaveCardRequest} card - The card information to be saved.
61
+ * @returns {Promise<import("../../types").ISaveCardResponse>} A promise that resolves with the saved card data.
62
+ *
63
+ * @throws {import("../../types").IPublicError} Throws an error object if the operation fails.
64
+ *
39
65
  * @public
40
66
  */
41
- async saveCustomerCard(authToken, businessId, card) {
42
- const skyflowTokens = await getSkyflowTokens({
43
- vault_id: vault_id,
44
- vault_url: vault_url,
45
- data: card,
46
- baseUrl: this.baseUrl,
47
- apiKey: this.apiKeyTonder,
48
- });
49
-
50
- return await saveCustomerCard(
51
- this.baseUrl,
52
- authToken,
53
- businessId,
54
- skyflowTokens,
55
- );
67
+ async saveCustomerCard(card) {
68
+ try {
69
+ const { auth_token } = await this.#getCustomer();
70
+ const { vault_id, vault_url, business } = this.merchantData;
71
+
72
+ const skyflowTokens = await getSkyflowTokens({
73
+ vault_id: vault_id,
74
+ vault_url: vault_url,
75
+ data: card,
76
+ baseUrl: this.baseUrl,
77
+ apiKey: this.apiKeyTonder,
78
+ });
79
+
80
+ return await saveCustomerCard(
81
+ this.baseUrl,
82
+ auth_token,
83
+ business?.pk,
84
+ skyflowTokens,
85
+ );
86
+ } catch (error) {
87
+ throw formatPublicErrorResponse(
88
+ {
89
+ message: MESSAGES.saveCardError,
90
+ },
91
+ error,
92
+ );
93
+ }
56
94
  }
57
95
 
58
96
  /**
59
97
  * Removes a card from a customer's account.
60
- * @param {string} authToken - The customer's authentication token.
61
98
  * @param {string} skyflowId - The unique identifier of the card to be deleted.
62
- * @param {string} businessId - The business primary key.
63
- * @returns {Promise<Object>} A promise that resolves when the card is successfully deleted.
99
+ * @returns {Promise<string>} A promise that resolves when the card is successfully deleted.
100
+ *
101
+ * @throws {import("../../types").IPublicError} Throws an error object if the operation fails.
102
+ *
64
103
  * @public
65
104
  */
66
- async removeCustomerCard(authToken, skyflowId, businessId) {
67
- return await removeCustomerCard(
68
- this.baseUrl,
69
- authToken,
70
- skyflowId,
71
- businessId,
72
- );
105
+ async removeCustomerCard(skyflowId) {
106
+ try {
107
+ const { auth_token } = await this.#getCustomer();
108
+ const { business } = this.merchantData;
109
+
110
+ return await removeCustomerCard(
111
+ this.baseUrl,
112
+ auth_token,
113
+ skyflowId,
114
+ business?.pk,
115
+ );
116
+ } catch (error) {
117
+ throw formatPublicErrorResponse(
118
+ {
119
+ message: MESSAGES.removeCardError,
120
+ },
121
+ error,
122
+ );
123
+ }
73
124
  }
74
125
 
75
126
  /**
76
127
  * Retrieves the list of available Alternative Payment Methods (APMs).
77
- * @returns {Promise<Object>} A promise that resolves with the list of APMs.
128
+ * @returns {Promise<import("../../types").IPaymentMethod[]>} A promise that resolves with the list of APMs.
129
+ *
130
+ * @throws {import("../../types").IPublicError} Throws an error object if the operation fails.
131
+ *
78
132
  * @public
79
133
  */
80
- async getCustomerAPMs() {
81
- return await fetchCustomerAPMs(this.baseUrl, this.apiKeyTonder);
134
+ async getCustomerPaymentMethods() {
135
+ try {
136
+ const response = await fetchCustomerAPMs(this.baseUrl, this.apiKeyTonder);
137
+
138
+ const apms_results =
139
+ response && "results" in response && response["results"].length > 0
140
+ ? response["results"]
141
+ : [];
142
+
143
+ return apms_results
144
+ .filter((apmItem) => apmItem.category.toLowerCase() !== "cards")
145
+ .map((apmItem) => {
146
+ const apm = {
147
+ id: apmItem.pk,
148
+ payment_method: apmItem.payment_method,
149
+ priority: apmItem.priority,
150
+ category: apmItem.category,
151
+ ...getPaymentMethodDetails(apmItem.payment_method),
152
+ };
153
+ return apm;
154
+ })
155
+ .sort((a, b) => a.priority - b.priority);
156
+ } catch (error) {
157
+ throw formatPublicErrorResponse(
158
+ {
159
+ message: MESSAGES.getPaymentMethodsError,
160
+ },
161
+ error,
162
+ );
163
+ }
82
164
  }
83
165
 
84
166
  _setCartTotal(total) {
@@ -92,13 +174,21 @@ export class LiteInlineCheckout extends BaseInlineCheckout {
92
174
  );
93
175
  const { vault_id, vault_url } = this.merchantData;
94
176
  let skyflowTokens;
95
- skyflowTokens = await getSkyflowTokens({
96
- vault_id: vault_id,
97
- vault_url: vault_url,
98
- data: card,
99
- baseUrl: this.baseUrl,
100
- apiKey: this.apiKeyTonder,
101
- });
177
+ if (!payment_method || payment_method !== "" || payment_method === null) {
178
+ if (typeof payment_method === "string") {
179
+ skyflowTokens = {
180
+ skyflow_id: card,
181
+ };
182
+ } else {
183
+ skyflowTokens = await getSkyflowTokens({
184
+ vault_id: vault_id,
185
+ vault_url: vault_url,
186
+ data: card,
187
+ baseUrl: this.baseUrl,
188
+ apiKey: this.apiKeyTonder,
189
+ });
190
+ }
191
+ }
102
192
 
103
193
  return await this._handleCheckout({
104
194
  card: skyflowTokens,
@@ -106,4 +196,15 @@ export class LiteInlineCheckout extends BaseInlineCheckout {
106
196
  customer,
107
197
  });
108
198
  }
199
+
200
+ async #getCustomer() {
201
+ if (!!this.#customerData) return this.#customerData;
202
+
203
+ this.#customerData = await registerOrFetchCustomer(
204
+ this.baseUrl,
205
+ this.apiKeyTonder,
206
+ this.customer,
207
+ );
208
+ return this.#customerData;
209
+ }
109
210
  }
@@ -1,4 +1,4 @@
1
- import {apmItemsTemplate, cardItemsTemplate, cardTemplate} from '../helpers/template.js'
1
+ import { apmItemsTemplate, cardItemsTemplate, cardTemplate } from '../helpers/template.js'
2
2
  import {
3
3
  clearSpace,
4
4
  injectMercadoPagoSecurity,
@@ -6,17 +6,18 @@ import {
6
6
  showError,
7
7
  showMessage
8
8
  } from '../helpers/utils';
9
- import {initSkyflow} from '../helpers/skyflow'
10
- import {globalLoader} from './globalLoader.js';
11
- import {BaseInlineCheckout} from "./BaseInlineCheckout";
9
+ import { initSkyflow } from '../helpers/skyflow'
10
+ import { globalLoader } from './globalLoader.js';
11
+ import { BaseInlineCheckout } from "./BaseInlineCheckout";
12
12
  import {
13
13
  fetchCustomerCards,
14
14
  removeCustomerCard,
15
15
  saveCustomerCard,
16
16
  fetchCustomerAPMs
17
17
  } from "../data";
18
+ import { MESSAGES } from "../shared/constants/messages";
18
19
 
19
- export class InlineCheckout extends BaseInlineCheckout{
20
+ export class InlineCheckout extends BaseInlineCheckout {
20
21
  static injected = false;
21
22
  static cardsInjected = false
22
23
  static apmsInjected = false
@@ -101,18 +102,23 @@ export class InlineCheckout extends BaseInlineCheckout{
101
102
  this.cb = cb
102
103
  }
103
104
 
104
- injectCheckout() {
105
- console.log("HERE: 1", InlineCheckout.injected)
105
+ /**
106
+ * Injects the checkout into the DOM and initializes it.
107
+ * Checks for an existing container and sets up an observer if needed.
108
+ * @returns {void}
109
+ * @public
110
+ */
111
+ async injectCheckout() {
106
112
  if (InlineCheckout.injected) return
107
113
  const containerTonderCheckout = document.querySelector("#tonder-checkout");
108
114
  if (containerTonderCheckout) {
109
- this.#mount(containerTonderCheckout)
115
+ await this.#mount(containerTonderCheckout)
110
116
  return;
111
117
  }
112
- const observer = new MutationObserver((mutations, obs) => {
118
+ const observer = new MutationObserver(async (mutations, obs) => {
113
119
  const containerTonderCheckout = document.querySelector("#tonder-checkout");
114
120
  if (containerTonderCheckout) {
115
- this.#mount(containerTonderCheckout)
121
+ await this.#mount(containerTonderCheckout)
116
122
  obs.disconnect();
117
123
  }
118
124
  });
@@ -123,21 +129,21 @@ export class InlineCheckout extends BaseInlineCheckout{
123
129
  });
124
130
  }
125
131
 
126
- #mount(containerTonderCheckout) {
127
- containerTonderCheckout.innerHTML = cardTemplate({renderPaymentButton: this.renderPaymentButton, customStyles: this.customStyles});
132
+ async #mount(containerTonderCheckout) {
133
+ containerTonderCheckout.innerHTML = cardTemplate({ renderPaymentButton: this.renderPaymentButton, customStyles: this.customStyles });
128
134
  globalLoader.show()
129
- this.#mountTonder();
135
+ await this.#mountTonder();
130
136
  InlineCheckout.injected = true;
131
137
  }
132
138
 
133
139
  async #mountAPMs() {
134
- try{
140
+ try {
135
141
  const apms = await fetchCustomerAPMs(this.baseUrl, this.apiKeyTonder);
136
- if(apms && apms['results'] && apms['results'].length > 0){
142
+ if (apms && apms['results'] && apms['results'].length > 0) {
137
143
  this.apmsData = apms['results']
138
144
  this.#loadAPMList(apms['results'])
139
145
  }
140
- }catch(e){
146
+ } catch (e) {
141
147
  console.warn("Error getting APMS")
142
148
  }
143
149
  }
@@ -189,6 +195,21 @@ export class InlineCheckout extends BaseInlineCheckout{
189
195
  }
190
196
  }
191
197
 
198
+ /**
199
+ * Removes the checkout from the DOM and cleans up associated resources.
200
+ *
201
+ * This method performs the following actions:
202
+ * 1. Resets the injection status flags for the checkout, cards, and APMs.
203
+ * 2. Aborts any ongoing requests using the AbortController.
204
+ * 3. Creates a new AbortController for future use.
205
+ * 4. Clears any existing injection intervals.
206
+ *
207
+ * Note: This method should be called when you want to completely remove
208
+ * the checkout from the page and reset its state.
209
+ *
210
+ * @returns {void}
211
+ * @public
212
+ */
192
213
  removeCheckout() {
193
214
  InlineCheckout.injected = false
194
215
  InlineCheckout.cardsInjected = false
@@ -235,39 +256,15 @@ export class InlineCheckout extends BaseInlineCheckout{
235
256
  )
236
257
  const { auth_token } = customerData;
237
258
  if (auth_token && this.email) {
238
- const saveCard = document.getElementById("save-checkout-card");
239
- if (saveCard && "checked" in saveCard && saveCard.checked) {
240
- try {
241
- await saveCustomerCard(this.baseUrl, auth_token, business.pk, {
242
- skyflow_id: cardTokens.skyflow_id,
243
- });
244
- showMessage("Tarjeta registrada con éxito", this.collectorIds.msgNotification);
245
- } catch (error) {
246
- if (error?.message) {
247
- showError(error.message)
248
- }
249
- }
250
-
251
- this.cardsInjected = false;
252
-
253
- const cards = await fetchCustomerCards(
254
- this.baseUrl,
255
- auth_token,
256
- this.merchantData.business.pk,
257
- );
258
- if ("cards" in cards) {
259
- const cardsMapped = cards.cards.map((card) => mapCards(card))
260
- this.#loadCardsList(cardsMapped, auth_token)
261
- }
262
- }
259
+ await this.#handleSaveCard(auth_token, business.pk, cardTokens)
263
260
  }
264
261
 
265
- const selected_apm = this.apmsData ? this.apmsData.find((iapm) => iapm.pk === this.radioChecked):{};
262
+ const selected_apm = this.apmsData ? this.apmsData.find((iapm) => iapm.pk === this.radioChecked) : {};
266
263
 
267
264
  const jsonResponseRouter = await this._handleCheckout({
268
- ...( selected_apm && Object.keys(selected_apm).length > 0
269
- ? {payment_method: selected_apm.payment_method}
270
- : {card: cardTokens}),
265
+ ...(selected_apm && Object.keys(selected_apm).length > 0
266
+ ? { payment_method: selected_apm.payment_method }
267
+ : { card: cardTokens }),
271
268
  customer: customerData
272
269
  });
273
270
 
@@ -287,6 +284,33 @@ export class InlineCheckout extends BaseInlineCheckout{
287
284
  }
288
285
  };
289
286
 
287
+ async #handleSaveCard(auth_token, businessId, cardTokens) {
288
+ const saveCard = document.getElementById("save-checkout-card");
289
+ if (saveCard && "checked" in saveCard && saveCard.checked) {
290
+ try {
291
+ await saveCustomerCard(this.baseUrl, auth_token, businessId, {
292
+ skyflow_id: cardTokens.skyflow_id,
293
+ });
294
+ showMessage(MESSAGES.cardSaved, this.collectorIds.msgNotification);
295
+ } catch (error) {
296
+ if (error?.message) {
297
+ showError(error.message)
298
+ }
299
+ }
300
+
301
+ this.cardsInjected = false;
302
+
303
+ const cards = await fetchCustomerCards(
304
+ this.baseUrl,
305
+ auth_token,
306
+ this.merchantData.business.pk,
307
+ );
308
+ if ("cards" in cards) {
309
+ const cardsMapped = cards.cards.map((card) => mapCards(card))
310
+ this.#loadCardsList(cardsMapped, auth_token)
311
+ }
312
+ }
313
+ }
290
314
  #loadCardsList(cards, token) {
291
315
  if (this.cardsInjected) return;
292
316
  const injectInterval = setInterval(() => {
@@ -370,8 +394,7 @@ export class InlineCheckout extends BaseInlineCheckout{
370
394
  }
371
395
  const businessId = this.merchantData.business.pk
372
396
  await removeCustomerCard(this.baseUrl, customerToken, skyflow_id, businessId)
373
- } catch {
374
- } finally {
397
+ } catch (error) { } finally {
375
398
  this.deletingCards = this.deletingCards.filter(id => id !== skyflow_id);
376
399
  this.#refreshCardOnDelete(customerToken)
377
400
  }
@@ -9,7 +9,7 @@ import {
9
9
  * @param {string} apiKey - The API key for authentication.
10
10
  * @param params - The query params to filter APMs
11
11
  * @param {AbortSignal} signal - The abort signal to cancel the request.
12
- * @returns {Promise<Object>} The available APMs.
12
+ * @returns {Promise<import("../../types").IPaymentMethodResponse>} The available APMs.
13
13
  */
14
14
  export async function fetchCustomerAPMs(
15
15
  baseUrl,
@@ -2,14 +2,20 @@ import {
2
2
  buildErrorResponse,
3
3
  buildErrorResponseFromCatch,
4
4
  } from "../helpers/utils";
5
+ import {MESSAGES} from "../shared/constants/messages";
5
6
 
6
7
  /**
7
- * Saves/Update a customer's card information.
8
- * @param {string} baseUrl - The base URL of the API.
8
+ * Saves or updates a customer's card information.
9
+ *
10
+ * This function sends a POST request to save or update the card information for a customer.
11
+ *
12
+ * @param {string} baseUrl - The base URL of the API.
9
13
  * @param {string} customerToken - The customer's authentication token.
10
- * @param {string} businessId - The business ID.
11
- * @param {Object} data - The card information to be saved.
12
- * @returns {Promise<Object>} The saved card data.
14
+ * @param {string | number} businessId - The business ID.
15
+ * @param {import("../../types").ISaveCardSkyflowRequest} data - The card information to be saved.
16
+ * @returns {Promise<import("../../types").ISaveCardResponse>} The saved card data.
17
+ *
18
+ * @throws {import("../../types").IApiError} Throws an error object if the save/update operation fails.
13
19
  */
14
20
  export async function saveCustomerCard(
15
21
  baseUrl,
@@ -31,7 +37,6 @@ export async function saveCustomerCard(
31
37
  if (response.ok) return await response.json();
32
38
 
33
39
  const res_json = await response.json();
34
-
35
40
  if (response.status === 409) {
36
41
  if ((res_json.error = "Card number already exists.")) {
37
42
  return {
@@ -54,7 +59,9 @@ export async function saveCustomerCard(
54
59
  * @param {string} customerToken - The customer's authentication token.
55
60
  * @param {string} skyflowId - The Skyflow ID of the card to be removed.
56
61
  * @param {string} businessId - The business ID.
57
- * @returns {Promise<Object>} The result of the card removal operation.
62
+ * @returns {Promise<string>} The result of the card removal operation.
63
+ *
64
+ * @throws {import("../../types").IApiError} Throws an error object if the operation fails.
58
65
  */
59
66
  export async function removeCustomerCard(
60
67
  baseUrl,
@@ -73,7 +80,8 @@ export async function removeCustomerCard(
73
80
  },
74
81
  });
75
82
 
76
- if (response.ok) return await response.json();
83
+ if(response.status === 204) return MESSAGES.cardSaved;
84
+ if (response.ok && "json" in response) return await response.json();
77
85
  const res_json = await response.json();
78
86
 
79
87
  throw await buildErrorResponse(response, res_json);
@@ -88,7 +96,9 @@ export async function removeCustomerCard(
88
96
  * @param {string} customerToken - The customer's authentication token.
89
97
  * @param {string} businessId - The business ID.
90
98
  * @param {AbortSignal} signal - The abort signal to cancel the request.
91
- * @returns {Promise<Object>} The customer's saved cards.
99
+ * @returns {Promise<import("../../types").ICustomerCardsResponse>} The customer's saved cards.
100
+ *
101
+ * @throws {import("../../types").IApiError} Throws an error object if the operation fails.
92
102
  */
93
103
  export async function fetchCustomerCards(
94
104
  baseUrl,
@@ -106,11 +116,11 @@ export async function fetchCustomerCards(
106
116
  },
107
117
  signal,
108
118
  });
109
-
110
119
  if (response.ok) return await response.json();
111
120
  const res_json = await response.json();
112
- throw await buildErrorResponse(response, res_json);
121
+
122
+ throw await buildErrorResponse(response, res_json, MESSAGES.getCardsError);
113
123
  } catch (error) {
114
- throw buildErrorResponseFromCatch(error);
124
+ throw buildErrorResponseFromCatch(error, MESSAGES.getCardsError);
115
125
  }
116
126
  }
@@ -52,10 +52,19 @@ export async function createPayment(baseUrl, apiKey, paymentItems) {
52
52
 
53
53
  /**
54
54
  * Initiates the checkout process.
55
- * @param {string} baseUrl - The base URL of the API.
55
+ *
56
+ * This function sends a POST request to the checkout router API with the provided
57
+ * checkout details. If the request is successful, it returns the response data.
58
+ * If the request fails, it throws an error that includes the status and details of the failure.
59
+ *
60
+ * @param {string} baseUrl - The base URL of the API.
56
61
  * @param {string} apiKey - The API key for authentication.
57
- * @param {Object} routerItems - The checkout details.
58
- * @returns {Promise<Object>} The checkout process result.
62
+ * @param {import("../../types").IStartCheckoutRequest | import("../../types").IStartCheckoutIdRequest} routerItems - The checkout details to be sent in the request body.
63
+ * @returns {Promise<import("../../types").IStartCheckoutResponse>} The checkout process result.
64
+ *
65
+ * @throws {Error} Throws an error if the checkout process fails. The error object contains
66
+ * additional `details` property with the response from the server if available.
67
+ * @property {import("../../types").IStartCheckoutErrorResponse} error.details - The response body from the server when an error occurs.
59
68
  */
60
69
  export async function startCheckoutRouter(baseUrl, apiKey, routerItems) {
61
70
  try {
@@ -70,10 +79,12 @@ export async function startCheckoutRouter(baseUrl, apiKey, routerItems) {
70
79
  body: JSON.stringify(data),
71
80
  });
72
81
  if (response.status >= 200 && response.status <= 299) {
73
- const jsonResponse = await response.json();
74
- return jsonResponse;
82
+ return await response.json();
75
83
  } else {
76
- throw new Error("Failed to start checkout router")
84
+ const errorResponse = await response.json();
85
+ const error = new Error("Failed to start checkout router");
86
+ error.details = errorResponse;
87
+ throw error;
77
88
  }
78
89
  } catch (error) {
79
90
  throw error