@tonder.io/ionic-lite-sdk 0.0.52-beta.DEV-1610.4 → 0.0.53-beta.DEV-1630.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -141,6 +141,59 @@ When calling the `payment` method, use the following data structure:
141
141
  - This is only used when not paying with a payment_method.
142
142
 
143
143
  - **payment_method**: (for LiteCheckout) String indicating the alternative payment method to be used (e.g., "Spei"). This is only used when not paying with a card.
144
+ - **apm_config**: (Optional) Configuration object for APM-specific options. Only applicable when using alternative payment methods like Mercado Pago.
145
+ <details>
146
+ <summary>APM Config Fields - Mercado Pago</summary>
147
+
148
+ | **Field** | **Type** | **Description** |
149
+ |-------------------------------------|--------------------------------------------|---------------------------------------------------------------------------|
150
+ | `binary_mode` | `boolean` | If `true`, payment must be approved or rejected immediately (no pending). |
151
+ | `additional_info` | `string` | Extra info shown during checkout and in payment details. |
152
+ | `back_urls` | `object` | URLs to redirect the user after payment. |
153
+ | └─ `success` | `string` | Redirect URL after successful payment. |
154
+ | └─ `pending` | `string` | Redirect URL after pending payment. |
155
+ | └─ `failure` | `string` | Redirect URL after failed/canceled payment. |
156
+ | `auto_return` | `"approved"` \| `"all"` | Enables auto redirection after payment completion. |
157
+ | `payment_methods` | `object` | Payment method restrictions and preferences. |
158
+ | └─ `excluded_payment_methods[]` | `array` | List of payment methods to exclude. |
159
+ | └─ `excluded_payment_methods[].id` | `string` | ID of payment method to exclude (e.g., "visa"). |
160
+ | └─ `excluded_payment_types[]` | `array` | List of payment types to exclude. |
161
+ | └─ `excluded_payment_types[].id` | `string` | ID of payment type to exclude (e.g., "ticket"). |
162
+ | └─ `default_payment_method_id` | `string` | Default payment method (e.g., "master"). |
163
+ | └─ `installments` | `number` | Max number of installments allowed. |
164
+ | └─ `default_installments` | `number` | Default number of installments suggested. |
165
+ | `expires` | `boolean` | Whether the preference has expiration. |
166
+ | `expiration_date_from` | `string` (ISO 8601) | Start of validity period (e.g. `"2025-01-01T12:00:00-05:00"`). |
167
+ | `expiration_date_to` | `string` (ISO 8601) | End of validity period. |
168
+ | `differential_pricing` | `object` | Configuration for differential pricing. |
169
+ | └─ `id` | `number` | ID of the differential pricing strategy. |
170
+ | `marketplace` | `string` | Marketplace identifier (default: "NONE"). |
171
+ | `marketplace_fee` | `number` | Fee to collect as marketplace commission. |
172
+ | `tracks[]` | `array` | Ad tracking configurations. |
173
+ | └─ `type` | `"google_ad"` \| `"facebook_ad"` | Type of tracker. |
174
+ | └─ `values.conversion_id` | `string` | Google Ads conversion ID. |
175
+ | └─ `values.conversion_label` | `string` | Google Ads label. |
176
+ | └─ `values.pixel_id` | `string` | Facebook Pixel ID. |
177
+ | `statement_descriptor` | `string` | Text on payer’s card statement (max 16 characters). |
178
+ | `shipments` | `object` | Shipping configuration. |
179
+ | └─ `mode` | `"custom"` \| `"me2"` \| `"not_specified"` | Type of shipping mode. |
180
+ | └─ `local_pickup` | `boolean` | Enable pickup at local branch (for `me2`). |
181
+ | └─ `dimensions` | `string` | Package dimensions (e.g. `10x10x10,500`). |
182
+ | └─ `default_shipping_method` | `number` | Default shipping method (for `me2`). |
183
+ | └─ `free_methods[]` | `array` | Shipping methods offered for free (for `me2`). |
184
+ | └─ `free_methods[].id` | `number` | ID of free shipping method. |
185
+ | └─ `cost` | `number` | Shipping cost (only for `custom` mode). |
186
+ | └─ `free_shipping` | `boolean` | If `true`, shipping is free (`custom` only). |
187
+ | └─ `receiver_address` | `object` | Shipping address. |
188
+ | └─ `receiver_address.zip_code` | `string` | ZIP or postal code. |
189
+ | └─ `receiver_address.street_name` | `string` | Street name. |
190
+ | └─ `receiver_address.street_number` | `number` | Street number. |
191
+ | └─ `receiver_address.city_name` | `string` | City name. |
192
+ | └─ `receiver_address.state_name` | `string` | State name. |
193
+ | └─ `receiver_address.country_name` | `string` | Country name. |
194
+ | └─ `receiver_address.floor` | `string` | Floor (optional). |
195
+ | └─ `receiver_address.apartment` | `string` | Apartment or unit (optional). |
196
+ </details>
144
197
 
145
198
  ```javascript
146
199
  const paymentData = {
@@ -154,6 +207,10 @@ const paymentData = {
154
207
  postCode: "12345",
155
208
  email: "john.doe@example.com",
156
209
  phone: "1234567890",
210
+ identification:{
211
+ type: "CPF",
212
+ number: "19119119100"
213
+ }
157
214
  },
158
215
  cart: {
159
216
  total: "100.00",
@@ -184,6 +241,7 @@ const paymentData = {
184
241
  },
185
242
  // card: "skyflow_id" // for a selected saved card.
186
243
  // payment_method: "Spei", // For the selected payment method.
244
+ // apm_config: {} // Optional, only for APMs like Mercado Pago, Oxxo Pay
187
245
  };
188
246
  ```
189
247
 
@@ -27,7 +27,7 @@ export declare class ThreeDSHandler {
27
27
  getVerifyTransactionUrl(): string | null;
28
28
  loadIframe(): Promise<unknown> | undefined;
29
29
  getRedirectUrl(): any;
30
- redirectToChallenge(): void;
30
+ redirectToChallenge(): Promise<void>;
31
31
  requestTransactionStatus(): Promise<any>;
32
32
  getURLParameters(): any;
33
33
  handleSuccessTransaction(response: any): any;
@@ -36,5 +36,6 @@ export declare class ThreeDSHandler {
36
36
  handleTransactionResponse(response: any): Promise<any>;
37
37
  verifyTransactionStatus(): Promise<any>;
38
38
  setPayload: (payload: any) => void;
39
+ openInCapacitorBrowser(url: string): Promise<void>;
39
40
  }
40
41
  export {};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{get as t}from"lodash";import e from"skyflow-js";function n(t,e,n,o){return new(n||(n=Promise))((function(r,i){function s(t){try{d(o.next(t))}catch(t){i(t)}}function a(t){try{d(o.throw(t))}catch(t){i(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}d((o=o.apply(t,e||[])).next())}))}function o(t,e,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(t):o?o.value:e.get(t)}function r(t,e,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(t,n):r?r.value=n:e.set(t,n),n}function i(t,e,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:t,body:e,name:n,message:o,stack:r}){this.code=t,this.body=e,this.name=n,this.message=o,this.stack=r}}const a=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),d=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},c=t=>new s({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),l=(t,e=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";t&&"json"in t&&(n=yield null==t?void 0:t.json()),t&&"status"in t&&(o=t.status.toString()),!n&&t&&"text"in t&&(r=yield t.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new s({code:o,body:n,name:o,message:r,stack:e})}));function u(t,e){var n,o;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.detail)||(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class h{constructor({payload:t=null,apiKey:e,baseUrl:n,redirectOnComplete:o,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=t=>{this.payload=t},this.baseUrl=n,this.apiKey=e,this.payload=t,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,n,o,r,i;const s=null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,n;if(null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((t,e)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,n;return null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const t=this.getRedirectUrl();if(t)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=t;else{const e=document.querySelector(`#${this.tdsIframeId}`);if(e){e.setAttribute("src",t),e.setAttribute("style","display: block");const o=this,r=t=>n(this,void 0,void 0,(function*(){const t=()=>{try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}e&&e.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),e.removeEventListener("load",r)},i=e=>n(this,void 0,void 0,(function*(){const r=yield new Promise(((t,n)=>t(e)));if(r){if((t=>"Pending"!==(null==t?void 0:t.transaction_status))(r))return t();{const t=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(t),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));e.addEventListener("load",r)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration(),e=t.startsWith("https://")?t:`${this.baseUrl}${t}`,n=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==n.status)return console.error("La verificación de la transacción falló."),null;return yield n.json()}))}getURLParameters(){const t={},e=new URLSearchParams(window.location.search);for(const[n,o]of e)t[n]=o;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return n(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=t.creq,n.value=t.creq,e.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=t.term_url,o.value=t.TermUrl,e.appendChild(o),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return n(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=t.startsWith("https://")?t:`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const p=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function m(t,e,o){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function y(t,e,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(t),n.setApiKey(e),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const f=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var v,g,_,A,b,E,T,O,C,S,j,k;class I{constructor({mode:t="stage",customization:e,apiKey:n,apiKeyTonder:o,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){v.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.card={},this.currency="",g.set(this,void 0),_.set(this,void 0),this.apiKeyTonder=o||n||"",this.returnUrl=r,this.callBack=s,this.mode=t,this.customer={},this.baseUrl=a||p[this.mode]||p.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),e||{}),this.process3ds=new h({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(t){"secureToken"in t&&o(this,v,"m",E).call(this,t.secureToken),o(this,v,"m",A).call(this,t)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield o(this,v,"m",j).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,r)=>n(this,void 0,void 0,(function*(){try{o(this,v,"m",A).call(this,t);const n=yield this._checkout(t);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}this.callBack&&this.callBack(n),e(n)}}catch(t){r(t)}}))))}getSecureToken(t){return n(this,void 0,void 0,(function*(){try{return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}(this.baseUrl,t)}catch(t){throw u({message:f.secureTokenError},t)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return n(this,void 0,void 0,(function*(){return o(this,_,"f")||r(this,_,yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,t),"f"),o(this,_,"f")}))}_handleCheckout({card:e,payment_method:r,customer:i,isSandbox:s,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:c,reference:l,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&c.merchant_id&&c.public_key&&!r&&(p=yield y(c.merchant_id,c.public_key,s,this.abortController.signal));const{id:f,auth_token:v}=i,_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:l,is_oneclick:!0,items:this.cartItems},A=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,_),b=(new Date).toISOString(),E={business_pk:u.pk,client_id:f,amount:h,date:b,order_id:A.id},T=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E),O=Object.assign(Object.assign(Object.assign({name:t(this.customer,"firstName",t(this.customer,"name","")),last_name:t(this.customer,"lastName",t(this.customer,"lastname","")),email_client:t(this.customer,"email",""),phone_number:t(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:u.pk,payment_id:T.pk,source:"sdk",metadata:this.metadata,browser_info:a(),currency:this.currency},r?{payment_method:r}:{card:e}),{apm_config:o(this,g,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),C=yield m(this.baseUrl,this.apiKeyTonder,O);return C||!1}catch(t){throw console.log(t),t}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(t){return this.merchantData}}))}_getCustomerCards(t,e){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,e)}))}_saveCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,e,o)}))}_removeCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e}});if(204===s.status)return f.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,o,e)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(t,e,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${t}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield l(i)}catch(t){throw c(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,o;return n(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(o=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function w({baseUrl:t,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=e.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${e}`},signal:o});if(n.ok)return(yield n.json()).token;throw new Error("Failed to retrieve bearer token")}))}(t,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}),d=a.container(e.ContainerType.COLLECT),l=yield function(t,o){return n(this,void 0,void 0,(function*(){const r=yield function(t,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(t).map((t=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:t,type:e.ElementType.INPUT_FIELD}),key:t}})))))}))}(t,o);return r?r.map((e=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=t[e.key];return e.element.update({value:o}),n(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,d);if((yield Promise.all(l)).some((t=>!t)))throw c(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const t=yield d.collect();if(t)return t.records[0].fields;throw c(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(t){throw c(t)}}))}g=new WeakMap,_=new WeakMap,v=new WeakSet,A=function(t){var e,n;!t||t&&0===Object.keys(t).length||(o(this,v,"m",b).call(this,t.customer),this._setCartTotal((null===(e=t.cart)||void 0===e?void 0:e.total)||0),o(this,v,"m",T).call(this,(null===(n=t.cart)||void 0===n?void 0:n.items)||[]),o(this,v,"m",O).call(this,t),o(this,v,"m",C).call(this,t),o(this,v,"m",S).call(this,t),o(this,v,"m",k).call(this,t))},b=function(t){t&&(this.customer=t)},E=function(t){this.secureToken=t},T=function(t){this.cartItems=t},O=function(t){this.metadata=null==t?void 0:t.metadata},C=function(t){this.currency=null==t?void 0:t.currency},S=function(t){this.card=null==t?void 0:t.card},j=function(t){var e,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type)||(null===(o=null==t?void 0:t.checkout)||void 0===o?void 0:o.is_route_finished)||(null==t?void 0:t.is_route_finished)||["Pending"].includes(null==t?void 0:t.transaction_status))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:(null===(r=t.checkout)||void 0===r?void 0:r.id)||(null==t?void 0:t.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))},k=function(t){r(this,g,null==t?void 0:t.apm_config,"f")};const M=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),R={[M.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[M.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[M.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[M.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[M.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[M.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[M.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[M.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[M.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[M.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[M.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[M.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[M.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[M.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[M.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[M.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[M.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[M.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[M.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[M.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[M.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[M.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[M.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[M.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[M.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[M.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[M.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[M.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[M.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[M.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[M.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[M.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},U=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return R[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class N extends I{constructor({apiKey:t,mode:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i}){super({mode:e,apiKey:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i}),this.activeAPMs=[]}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),e=yield this._getCustomerCards(t,this.merchantData.business.pk);return Object.assign(Object.assign({},e),{cards:e.cards.map((t=>{return Object.assign(Object.assign({},t),{icon:(e=t.fields.card_scheme,"Visa"===e?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===e?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===e?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var e}))})}catch(t){throw u({message:f.getCardsError},t)}}))}saveCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{vault_id:n,vault_url:o,business:r}=this.merchantData,i=yield w({vault_id:n,vault_url:o,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(e,null==r?void 0:r.pk,i)}catch(t){throw u({message:f.saveCardError},t)}}))}removeCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(e,null==n?void 0:n.pk,t)}catch(t){throw u({message:f.removeCardError},t)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw u({message:f.getPaymentMethodsError},t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw u({message:f.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,o){return n(this,void 0,void 0,(function*(){try{return yield y(t,e,o)}catch(t){throw c(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:o}){return n(this,void 0,void 0,(function*(){return yield w({vault_id:t,vault_url:e,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(t){this.cartTotal=t}_checkout({card:t,payment_method:e,isSandbox:o,returnUrl:r}){return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:i,vault_url:s}=this.merchantData;let a;return e&&""!==e&&null!==e||(a="string"==typeof t?{skyflow_id:t}:yield w({vault_id:i,vault_url:s,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:a,payment_method:e,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/customer/`,n={email:t},o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}createOrder(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}createPayment(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}startCheckoutRouter(t){return n(this,void 0,void 0,(function*(){const e=yield m(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return n(this,void 0,void 0,(function*(){try{const{order:e,total:n,customer:o,skyflowTokens:r,return_url:i,isSandbox:d,metadata:c,currency:l,payment_method:u}=t,h=yield this._fetchMerchantData(),p=yield this.customerRegister(o.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const t={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:e.items},f=yield this.createOrder(t),v=(new Date).toISOString();if(!("id"in f&&"id"in p&&"business"in h))throw new s({code:"500",body:f,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:n,date:v,order_id:f.id,client_id:p.id},e=yield this.createPayment(t);let s;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(s=yield y(g.merchant_id,g.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in f&&f.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata:c,browser_info:a(),currency:l},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield m(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(t){throw c(t)}}))}registerCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"User-token":e,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}deleteCustomerCard(t,e=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield l(n)}catch(t){throw c(t)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const t=yield function(t,e,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority)),this.activeAPMs}catch(t){return console.error("Error getting APMS",t),[]}}))}}function P(t){return/^\d{12,19}$/.test(t)&&K(t)}function L(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function D(t){return/^\d{3,4}$/.test(t)}function $(t){return/^(0[1-9]|1[0-2])$/.test(t)}function B(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const K=t=>{const e=`${t}`.split("").reverse().map((t=>Number.parseInt(t))),n=e.shift();let o=e.reduce(((t,e,n)=>n%2!=0?t+e:t+((e*=2)>9?e-9:e)),0);return o+=n,o%10==0};export{I as BaseInlineCheckout,N as LiteCheckout,D as validateCVV,P as validateCardNumber,L as validateCardholderName,$ as validateExpirationMonth,B as validateExpirationYear};
1
+ import{Capacitor as t}from"@capacitor/core";import{get as e}from"lodash";import o from"skyflow-js";function n(t,e,o,n){return new(o||(o=Promise))((function(r,i){function s(t){try{d(n.next(t))}catch(t){i(t)}}function a(t){try{d(n.throw(t))}catch(t){i(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(s,a)}d((n=n.apply(t,e||[])).next())}))}function r(t,e,o,n){if("a"===o&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===o?n:"a"===o?n.call(t):n?n.value:e.get(t)}function i(t,e,o,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,o):r?r.value=o:e.set(t,o),o}function s(t,e,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class a{constructor({code:t,body:e,name:o,message:n,stack:r}){this.code=t,this.body=e,this.name=o,this.message=n,this.stack=r}}const d=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),c=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},l=t=>new a({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),u=(t,e=void 0)=>n(void 0,void 0,void 0,(function*(){let o,n,r="Error";t&&"json"in t&&(o=yield null==t?void 0:t.json()),t&&"status"in t&&(n=t.status.toString()),!o&&t&&"text"in t&&(r=yield t.text()),(null==o?void 0:o.detail)&&(r=o.detail);return new a({code:n,body:o,name:n,message:r,stack:e})}));function h(t,e){var o,n;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.detail)||(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class p{constructor({payload:t=null,apiKey:e,baseUrl:o,redirectOnComplete:n,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=t=>{this.payload=t},this.baseUrl=o,this.apiKey=e,this.payload=t,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=n,this.callBack=s}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,o,n,r,i;const s=null===(o=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===o?void 0:o.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=null===(i=null===(r=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,o;if(null===(o=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe)return new Promise(((t,e)=>{var o,n,r;const i=null===(r=null===(n=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const o=document.createElement("div");o.innerHTML=i,document.body.appendChild(o);const n=document.createElement("script");n.textContent='document.getElementById("tdsMmethodForm").submit();',o.appendChild(n);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,o;return null===(o=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===o?void 0:o.url}redirectToChallenge(){var e,o;return n(this,void 0,void 0,(function*(){const r=this.getRedirectUrl();if(r){const i="ios"===(null===(e=t.getPlatform)||void 0===e?void 0:e.call(t));if(console.log("Capacitor.getPlatform?.()",null===(o=t.getPlatform)||void 0===o?void 0:o.call(t)),this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=r;else{if(i)return void(yield this.openInCapacitorBrowser(r));const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",r),t.setAttribute("style","display: block");const e=this,o=r=>n(this,void 0,void 0,(function*(){const r=()=>{try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}t&&t.setAttribute("style","display: none"),e.callBack&&e.callBack(e.payload),t.removeEventListener("load",o)},i=t=>n(this,void 0,void 0,(function*(){const o=yield new Promise(((e,o)=>e(t)));if(o){if((t=>"Pending"!==(null==t?void 0:t.transaction_status))(o))return r();{const t=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(t),yield i(e.requestTransactionStatus())}))),7e3)}}}));yield i(e.requestTransactionStatus())}));t.addEventListener("load",o)}else console.log("No iframe found")}}else this.callBack&&this.callBack(this.payload)}))}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration(),e=t.startsWith("https://")?t:`${this.baseUrl}${t}`,o=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==o.status)return console.error("La verificación de la transacción falló."),null;return yield o.json()}))}getURLParameters(){const t={},e=new URLSearchParams(window.location.search);for(const[o,n]of e)t[o]=n;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return n(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const o=document.createElement("input");o.type="hidden",o.name=t.creq,o.value=t.creq,e.appendChild(o);const n=document.createElement("input");n.type="hidden",n.name=t.term_url,n.value=t.TermUrl,e.appendChild(n),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return n(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=t.startsWith("https://")?t:`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}openInCapacitorBrowser(t){return n(this,void 0,void 0,(function*(){const{Browser:e}=yield import("@capacitor/browser");yield e.open({url:t})}))}}const m=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function y(t,e,o){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function f(t,e,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(t),n.setApiKey(e),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const v=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var g,_,A,b,E,T,O,C,S,j,I,k;class w{constructor({mode:t="stage",customization:e,apiKey:o,apiKeyTonder:n,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){g.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.card={},this.currency="",_.set(this,void 0),A.set(this,void 0),this.apiKeyTonder=n||o||"",this.returnUrl=r,this.callBack=s,this.mode=t,this.customer={},this.baseUrl=a||m[this.mode]||m.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),e||{}),this.process3ds=new p({apiKey:o,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(t){"secureToken"in t&&r(this,g,"m",T).call(this,t.secureToken),r(this,g,"m",b).call(this,t)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield r(this,g,"m",I).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,o)=>n(this,void 0,void 0,(function*(){try{r(this,g,"m",b).call(this,t);const o=yield this._checkout(t);this.process3ds.setPayload(o);if(yield this._handle3dsRedirect(o)){try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}this.callBack&&this.callBack(o),e(o)}}catch(t){o(t)}}))))}getSecureToken(t){return n(this,void 0,void 0,(function*(){try{return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield u(n)}catch(t){throw l(t)}}))}(this.baseUrl,t)}catch(t){throw h({message:v.secureTokenError},t)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return n(this,void 0,void 0,(function*(){return r(this,A,"f")||i(this,A,yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,t),"f"),r(this,A,"f")}))}_handleCheckout({card:t,payment_method:o,customer:i,isSandbox:s,returnUrl:a}){return n(this,void 0,void 0,(function*(){const{openpay_keys:c,reference:l,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&c.merchant_id&&c.public_key&&!o&&(p=yield f(c.merchant_id,c.public_key,s,this.abortController.signal));const{id:m,auth_token:v}=i,g={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:l,is_oneclick:!0,items:this.cartItems},A=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,g),b=(new Date).toISOString(),E={business_pk:u.pk,client_id:m,amount:h,date:b,order_id:A.id},T=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E),O=Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:a||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:u.pk,payment_id:T.pk,source:"sdk",metadata:this.metadata,browser_info:d(),currency:this.currency},o?{payment_method:o}:{card:t}),{apm_config:r(this,_,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),C=yield y(this.baseUrl,this.apiKeyTonder,O);return C||!1}catch(t){throw console.log(t),t}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield s(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(t){return this.merchantData}}))}_getCustomerCards(t,e){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield u(s)}catch(t){throw l(t)}}))}(this.baseUrl,t,this.secureToken,e)}))}_saveCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield u(s)}catch(t){throw l(t)}}))}(this.baseUrl,t,this.secureToken,e,o)}))}_removeCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e}});if(204===s.status)return v.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield u(s)}catch(t){throw l(t)}}))}(this.baseUrl,t,this.secureToken,o,e)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(t,e,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${t}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield u(i)}catch(t){throw l(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,o;return n(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(o=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function M({baseUrl:t,apiKey:e,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=o.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${e}`},signal:o});if(n.ok)return(yield n.json()).token;throw new Error("Failed to retrieve bearer token")}))}(t,e)})),options:{logLevel:o.LogLevel.ERROR,env:o.Env.DEV}}),d=a.container(o.ContainerType.COLLECT),c=yield function(t,e){return n(this,void 0,void 0,(function*(){const r=yield function(t,e){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(t).map((t=>n(this,void 0,void 0,(function*(){return{element:yield e.create({table:"cards",column:t,type:o.ElementType.INPUT_FIELD}),key:t}})))))}))}(t,e);return r?r.map((e=>new Promise((o=>{var n;const r=document.createElement("div");r.hidden=!0,r.id=`id-${e.key}`,null===(n=document.querySelector("body"))||void 0===n||n.appendChild(r),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const n=t[e.key];return e.element.update({value:n}),o(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,d);if((yield Promise.all(c)).some((t=>!t)))throw l(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const t=yield d.collect();if(t)return t.records[0].fields;throw l(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(t){throw l(t)}}))}_=new WeakMap,A=new WeakMap,g=new WeakSet,b=function(t){var e,o;!t||t&&0===Object.keys(t).length||(r(this,g,"m",E).call(this,t.customer),this._setCartTotal((null===(e=t.cart)||void 0===e?void 0:e.total)||0),r(this,g,"m",O).call(this,(null===(o=t.cart)||void 0===o?void 0:o.items)||[]),r(this,g,"m",C).call(this,t),r(this,g,"m",S).call(this,t),r(this,g,"m",j).call(this,t),r(this,g,"m",k).call(this,t))},E=function(t){t&&(this.customer=t)},T=function(t){this.secureToken=t},O=function(t){this.cartItems=t},C=function(t){this.metadata=null==t?void 0:t.metadata},S=function(t){this.currency=null==t?void 0:t.currency},j=function(t){this.card=null==t?void 0:t.card},I=function(t){var e,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type)||(null===(o=null==t?void 0:t.checkout)||void 0===o?void 0:o.is_route_finished)||(null==t?void 0:t.is_route_finished)||["Pending"].includes(null==t?void 0:t.transaction_status))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:(null===(r=t.checkout)||void 0===r?void 0:r.id)||(null==t?void 0:t.checkout_id)};try{return yield y(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))},k=function(t){i(this,_,null==t?void 0:t.apm_config,"f")};const R=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),P={[R.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[R.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[R.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[R.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[R.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[R.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[R.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[R.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[R.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[R.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[R.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[R.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[R.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[R.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[R.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[R.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[R.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[R.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[R.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[R.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[R.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[R.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[R.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[R.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[R.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[R.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[R.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[R.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[R.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[R.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[R.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[R.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[R.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},U=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return P[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class N extends w{constructor({apiKey:t,mode:e,returnUrl:o,callBack:n,apiKeyTonder:r,baseUrlTonder:i}){super({mode:e,apiKey:t,returnUrl:o,callBack:n,apiKeyTonder:r,baseUrlTonder:i}),this.activeAPMs=[]}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),e=yield this._getCustomerCards(t,this.merchantData.business.pk);return Object.assign(Object.assign({},e),{cards:e.cards.map((t=>{return Object.assign(Object.assign({},t),{icon:(e=t.fields.card_scheme,"Visa"===e?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===e?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===e?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var e}))})}catch(t){throw h({message:v.getCardsError},t)}}))}saveCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{vault_id:o,vault_url:n,business:r}=this.merchantData,i=yield M({vault_id:o,vault_url:n,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(e,null==r?void 0:r.pk,i)}catch(t){throw h({message:v.saveCardError},t)}}))}removeCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:o}=this.merchantData;return yield this._removeCustomerCard(e,null==o?void 0:o.pk,t)}catch(t){throw h({message:v.removeCardError},t)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw h({message:v.getPaymentMethodsError},t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield s(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw h({message:v.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,o){return n(this,void 0,void 0,(function*(){try{return yield f(t,e,o)}catch(t){throw l(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:o}){return n(this,void 0,void 0,(function*(){return yield M({vault_id:t,vault_url:e,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(t){this.cartTotal=t}_checkout({card:t,payment_method:e,isSandbox:o,returnUrl:r}){return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:i,vault_url:s}=this.merchantData;let a;return e&&""!==e&&null!==e||(a="string"==typeof t?{skyflow_id:t}:yield M({vault_id:i,vault_url:s,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:a,payment_method:e,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/customer/`,o={email:t},n=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(o)});if(n.ok)return yield n.json();throw yield u(n)}catch(t){throw l(t)}}))}createOrder(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,o=t,n=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(o)});if(n.ok)return yield n.json();throw yield u(n)}catch(t){throw l(t)}}))}createPayment(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,o=t,n=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(o)});if(n.ok)return yield n.json();throw yield u(n)}catch(t){throw l(t)}}))}startCheckoutRouter(t){return n(this,void 0,void 0,(function*(){const e=yield y(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return n(this,void 0,void 0,(function*(){try{const{order:e,total:o,customer:n,skyflowTokens:r,return_url:i,isSandbox:s,metadata:c,currency:l,payment_method:u}=t,h=yield this._fetchMerchantData(),p=yield this.customerRegister(n.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new a({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const t={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:o,reference:h.reference,is_oneclick:!0,items:e.items},m=yield this.createOrder(t),v=(new Date).toISOString();if(!("id"in m&&"id"in p&&"business"in h))throw new a({code:"500",body:m,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:o,date:v,order_id:m.id,client_id:p.id},e=yield this.createPayment(t);let a;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(a=yield f(g.merchant_id,g.public_key,s));const A=Object.assign(Object.assign({name:n.name,last_name:n.lastname,email_client:n.email,phone_number:n.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:o,title_ship:"shipping",description:"transaction",device_session_id:a||null,token_id:"",order_id:"id"in m&&m.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata:c,browser_info:d(),currency:l},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield y(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(t){throw l(t)}}))}registerCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"User-token":e,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield u(n)}catch(t){throw l(t)}}))}deleteCustomerCard(t,e=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const o=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(o.ok)return!0;throw yield u(o)}catch(t){throw l(t)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const t=yield function(t,e,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield u(n)}catch(t){throw l(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority)),this.activeAPMs}catch(t){return console.error("Error getting APMS",t),[]}}))}}function L(t){return/^\d{12,19}$/.test(t)&&x(t)}function D(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function B(t){return/^\d{3,4}$/.test(t)}function $(t){return/^(0[1-9]|1[0-2])$/.test(t)}function K(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const x=t=>{const e=`${t}`.split("").reverse().map((t=>Number.parseInt(t))),o=e.shift();let n=e.reduce(((t,e,o)=>o%2!=0?t+e:t+((e*=2)>9?e-9:e)),0);return n+=o,n%10==0};export{w as BaseInlineCheckout,N as LiteCheckout,B as validateCVV,L as validateCardNumber,D as validateCardholderName,$ as validateExpirationMonth,K as validateExpirationYear};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonder.io/ionic-lite-sdk",
3
- "version": "0.0.52-beta.DEV-1610.4",
3
+ "version": "0.0.53-beta.DEV-1630.1",
4
4
  "description": "Tonder ionic lite SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -20,7 +20,13 @@
20
20
  "access": "public",
21
21
  "registry": "https://registry.npmjs.org/"
22
22
  },
23
+ "peerDependencies": {
24
+ "@capacitor/core": "^5.7.8",
25
+ "@capacitor/browser": "^5.2.1"
26
+ },
23
27
  "devDependencies": {
28
+ "@capacitor/core": "^5.7.8",
29
+ "@capacitor/browser": "^5.2.1",
24
30
  "@rollup/plugin-terser": "^0.4.4",
25
31
  "@rollup/plugin-typescript": "11.1.6",
26
32
  "@types/crypto-js": "^4.2.2",
@@ -1,3 +1,6 @@
1
+ import type { Browser } from '@capacitor/browser';
2
+ import { Capacitor } from '@capacitor/core';
3
+
1
4
  type ThreeDSHandlerContructor = {
2
5
  payload?: any,
3
6
  apiKey?: string,
@@ -140,13 +143,20 @@ export class ThreeDSHandler {
140
143
  return this.payload?.next_action?.redirect_to_url?.url
141
144
  }
142
145
 
143
- redirectToChallenge() {
146
+ async redirectToChallenge() {
144
147
  const url = this.getRedirectUrl()
145
148
  if (url) {
149
+ const isIOS = Capacitor.getPlatform?.() === 'ios';
150
+ console.log('Capacitor.getPlatform?.()', Capacitor.getPlatform?.())
151
+
146
152
  this.saveVerifyTransactionUrl()
147
153
  if(this.redirectOnComplete) {
148
154
  window.location = url;
149
155
  } else {
156
+ if(isIOS){
157
+ await this.openInCapacitorBrowser(url)
158
+ return;
159
+ }
150
160
  const iframe = document.querySelector(`#${this.tdsIframeId}`)
151
161
  if(iframe) {
152
162
 
@@ -156,7 +166,6 @@ export class ThreeDSHandler {
156
166
  const self = this;
157
167
 
158
168
  const listenerHandler = async (event: any) => {
159
-
160
169
  const checkStatus = (result: any) => result?.transaction_status !== "Pending";
161
170
 
162
171
  const executeAction = () => {
@@ -324,4 +333,9 @@ export class ThreeDSHandler {
324
333
  setPayload = (payload: any) => {
325
334
  this.payload = payload
326
335
  }
336
+
337
+ async openInCapacitorBrowser(url: string) {
338
+ const { Browser } = await import('@capacitor/browser');
339
+ await Browser.open({ url });
340
+ }
327
341
  }