@tonder.io/ionic-lite-sdk 0.0.56-beta.1 → 0.0.57

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,7 @@ 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
+ - **order_reference**: Unique order reference from the merchant. Used to visually identify/filter the order in dashboard.
144
145
  - **apm_config**: (Optional) Configuration object for APM-specific options. Only applicable when using alternative payment methods like Mercado Pago.
145
146
  <details>
146
147
  <summary>APM Config Fields - Mercado Pago</summary>
@@ -26,6 +26,7 @@ export declare class BaseInlineCheckout<T extends CustomizationOptions = Customi
26
26
  customization: T;
27
27
  cartItems?: IItem[];
28
28
  metadata: {};
29
+ order_reference?: string | null;
29
30
  card?: {} | undefined;
30
31
  currency?: string;
31
32
  constructor({ mode, customization, apiKey, apiKeyTonder, returnUrl, tdsIframeId, callBack, baseUrlTonder, tonderPayButtonId }: IInlineCheckoutBaseOptions);
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,I;class k{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||{}),console.log("this.customization.redirectOnComplete",this.customization.redirectOnComplete),console.log("this.tdsIframeId",i),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",I).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}}))},I=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 k{constructor({apiKey:t,mode:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,collectorIds:a}){super({mode:e,apiKey:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),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:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,""),expiration_month:t.expiration_month.replace(/\s+/g,""),expiration_year:t.expiration_year.replace(/\s+/g,""),cvv:t.cvv.replace(/\s+/g,""),cardholder_name:t.cardholder_name.replace(/\s+/g,"")}),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{k as BaseInlineCheckout,N as LiteCheckout,D as validateCVV,P as validateCardNumber,L as validateCardholderName,$ as validateExpirationMonth,B as validateExpirationYear};
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,I;class k{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.order_reference=null,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,currency:this.currency,metadata:this.metadata},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,customer_order_reference:this.order_reference?this.order_reference:l,items:this.cartItems,currency:this.currency,metadata:this.metadata},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",items:this.cartItems,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",I).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,this.order_reference=null==t?void 0:t.order_reference},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}}))},I=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 k{constructor({apiKey:t,mode:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,collectorIds:a}){super({mode:e,apiKey:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),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:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,""),expiration_month:t.expiration_month.replace(/\s+/g,""),expiration_year:t.expiration_year.replace(/\s+/g,""),cvv:t.cvv.replace(/\s+/g,""),cardholder_name:t.cardholder_name.replace(/\s+/g,"")}),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{k as BaseInlineCheckout,N as LiteCheckout,D as validateCVV,P as validateCardNumber,L as validateCardholderName,$ as validateExpirationMonth,B as validateExpirationYear};
@@ -103,6 +103,7 @@ export interface IProcessPaymentRequest {
103
103
  * Use the `returnUrl` field when creating the instance of LiteCheckout or InlineCheckout.
104
104
  */
105
105
  returnUrl?: string;
106
+ order_reference?: string | null;
106
107
  }
107
108
  export interface ICardFields {
108
109
  card_number: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonder.io/ionic-lite-sdk",
3
- "version": "0.0.56-beta.1",
3
+ "version": "0.0.57",
4
4
  "description": "Tonder ionic lite SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -55,6 +55,7 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
55
55
 
56
56
  cartItems?: IItem[];
57
57
  metadata = {};
58
+ order_reference?: string | null = null;
58
59
  card? = {};
59
60
  currency?: string = "";
60
61
  #apm_config?:IMPConfigRequest | Record<string, any>
@@ -82,8 +83,6 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
82
83
  ...this.customization,
83
84
  ...(customization || {}),
84
85
  }
85
- console.log("this.customization.redirectOnComplete", this.customization.redirectOnComplete)
86
- console.log("this.tdsIframeId", tdsIframeId)
87
86
 
88
87
  this.process3ds = new ThreeDSHandler({
89
88
  apiKey: apiKey,
@@ -224,6 +223,8 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
224
223
  reference: reference,
225
224
  is_oneclick: true,
226
225
  items: this.cartItems!,
226
+ currency: this.currency,
227
+ metadata: this.metadata,
227
228
  };
228
229
  const jsonResponseOrder = await createOrder(
229
230
  this.baseUrl,
@@ -241,6 +242,10 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
241
242
  amount: total,
242
243
  date: dateString,
243
244
  order_id: jsonResponseOrder.id,
245
+ customer_order_reference: this.order_reference ? this.order_reference : reference,
246
+ items: this.cartItems,
247
+ currency: this.currency,
248
+ metadata: this.metadata,
244
249
  };
245
250
  const jsonResponsePayment = await createPayment(
246
251
  this.baseUrl,
@@ -272,6 +277,7 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
272
277
  business_id: business.pk,
273
278
  payment_id: jsonResponsePayment.pk,
274
279
  source: "sdk",
280
+ items: this.cartItems,
275
281
  metadata: this.metadata,
276
282
  browser_info: getBrowserInfo(),
277
283
  currency: this.currency!,
@@ -375,8 +381,9 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
375
381
  this.cartItems = items;
376
382
  }
377
383
 
378
- #handleMetadata(data: { metadata?: any }) {
384
+ #handleMetadata(data: { metadata?: any; order_reference?: string | null }) {
379
385
  this.metadata = data?.metadata;
386
+ this.order_reference = data?.order_reference;
380
387
  }
381
388
 
382
389
  #handleCurrency(data: { currency?: string }) {
@@ -115,6 +115,7 @@ export interface IProcessPaymentRequest {
115
115
  * Use the `returnUrl` field when creating the instance of LiteCheckout or InlineCheckout.
116
116
  */
117
117
  returnUrl?: string;
118
+ order_reference?: string | null;
118
119
  }
119
120
 
120
121
  export interface ICardFields {