@tonder.io/ionic-lite-sdk 0.0.63-beta.DEV-1975.4 → 0.0.63-beta.DEV-1975.5

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.
@@ -17,6 +17,7 @@ export declare class LiteCheckout extends BaseInlineCheckout implements ILiteChe
17
17
  private skyflowInstance;
18
18
  private readonly events;
19
19
  private mountedElementsByContext;
20
+ private customerCardsCache;
20
21
  constructor({ apiKey, mode, returnUrl, callBack, apiKeyTonder, baseUrlTonder, customization, collectorIds, events }: IInlineLiteCheckoutOptions);
21
22
  injectCheckout(): Promise<void>;
22
23
  getCustomerCards(): Promise<ICustomerCardsResponse>;
@@ -25,6 +26,7 @@ export declare class LiteCheckout extends BaseInlineCheckout implements ILiteChe
25
26
  getCustomerPaymentMethods(): Promise<IPaymentMethod[]>;
26
27
  mountCardFields(event: IMountCardFieldsRequest): Promise<void>;
27
28
  private getContainerByCardId;
29
+ private collectCardTokens;
28
30
  unmountCardFields(context?: string): void;
29
31
  /**
30
32
  * Internal helper to unmount elements from a specific context
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{d(r.next(e))}catch(e){i(e)}}function a(e){try{d(r.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((r=r.apply(e,t||[])).next())}))}function r(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function o(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n}function i(e,t,r){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:r});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:r,stack:o}){this.code=e,this.body=t,this.name=n,this.message=r,this.stack=o}}var a;!function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(a||(a={}));const d=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."}),l={[a.INIT_ERROR]:"Error initializing the SDK.",[a.INVALID_TYPE]:"SDK Type invalid.",[a.STATE_ERROR]:"Error updating SDK state.",[a.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[a.INVALID_CONFIG]:"Required configuration options.",[a.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[a.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[a.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[a.TYPE_SDK_REQUIRED]:"SDK type required.",[a.ENVIRONMENT_REQUIRED]:"Environment required.",[a.FETCH_CARDS_ERROR]:"Error retrieving cards.",[a.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[a.SAVE_CARD_ERROR]:"Error saving the card.",[a.REMOVE_CARD_ERROR]:"Error deleting the card.",[a.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[a.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[a.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[a.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[a.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[a.START_CHECKOUT_ERROR]:"Error processing the payment.",[a.CREATE_ORDER_ERROR]:"Error creating the order.",[a.BUSINESS_ID_REQUIRED]:"Business ID is required.",[a.CLIENT_ID_REQUIRED]:"Client ID is required.",[a.INVALID_AMOUNT]:"Invalid amount.",[a.INVALID_ITEMS]:"Invalid items.",[a.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[a.INVALID_EMAIL]:"Invalid email.",[a.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[a.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[a.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[a.SECURE_TOKEN_ERROR]:"Error getting secure token.",[a.SECURE_TOKEN_INVALID]:"Invalid secure token.",[a.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[a.REMOVE_CARD]:"Card deleted successfully",[a.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[a.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[a.INVALID_CARD_DATA]:"Invalid card data.",[a.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[a.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[a.REQUEST_ABORTED]:"Requests canceled.",[a.REQUEST_FAILED]:"Request failed.",[a.UNKNOWN_ERROR]:"An unexpected error occurred.",[a.CREATE_ERROR]:"Error creating the SDK.",[a.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[a.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[a.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};a.INIT_ERROR,a.STATE_ERROR,a.FETCH_BUSINESS_ERROR,a.INVALID_CONFIG,a.TYPE_SDK_REQUIRED,a.ENVIRONMENT_REQUIRED,a.FETCH_CARDS_ERROR,a.SAVE_CARD_ERROR,a.REMOVE_CARD_ERROR,a.CREATE_PAYMENT_ERROR,a.START_CHECKOUT_ERROR,a.CREATE_ORDER_ERROR,a.BUSINESS_ID_REQUIRED,a.CLIENT_ID_REQUIRED,a.INVALID_AMOUNT,a.INVALID_ITEMS,a.CUSTOMER_OPERATION_ERROR,a.INVALID_EMAIL,a.FETCH_PAYMENT_METHODS_ERROR,a.INVALID_VAULT_TOKEN,a.VAULT_TOKEN_ERROR,a.SECURE_TOKEN_ERROR,a.INVALID_SECRET_API_KEY,a.CUSTOMER_AUTH_TOKEN_NOT_VALID,a.SECURE_TOKEN_INVALID,a.REMOVE_CARD,a.SKYFLOW_NOT_INITIALIZED,a.INVALID_TYPE,a.PAYMENT_PROCESS_ERROR,a.INVALID_PAYMENT_REQUEST,a.INVALID_PAYMENT_REQUEST_CARD_PM,a.SAVE_CARD_PROCESS_ERROR,a.ERROR_LOAD_PAYMENT_FORM,a.INVALID_CARD_DATA,a.ERROR_LOAD_ENROLLMENT_FORM,a.MOUNT_COLLECT_ERROR,a.CARD_SAVED_SUCCESSFULLY,a.CARD_REMOVED_SUCCESSFULLY,a.REQUEST_ABORTED,a.REQUEST_FAILED,a.UNKNOWN_ERROR,a.CREATE_ERROR,a.FETCH_TRANSACTION_ERROR,a.THREEDS_REDIRECTION_ERROR,a.REMOVE_SDK_ERROR;class c extends Error{constructor(e){var t,n;const r=e.message||l[e.code]||"Unknown error";super(r),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(n=e.details)||void 0===n?void 0:n.message)||r}}}const u=()=>({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}),h=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},E=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),p=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,r,o="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(r=e.status.toString()),!n&&e&&"text"in e&&(o=yield e.text()),(null==n?void 0:n.detail)&&(o=n.detail);return new s({code:r,body:n,name:r,message:o,stack:t})}));function _(e,t){var n,r;let o=200;try{o=Number((null==t?void 0:t.code)||200)}catch(e){}const i={status:"error",code:o,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(r=null==t?void 0:t.body)||void 0===r?void 0:r.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),e)}class m{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:r,tdsIframeId:o,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.tdsIframeId=o,this.tonderPayButtonId=i,this.redirectOnComplete=r,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,r,o,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,r,o;const i=null===(o=null===(r=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const r=document.createElement("script");r.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(r);const o=document.getElementById("tdsMmethodTgtFrame");o?o.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const r=this,o=e=>n(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),r.callBack&&r.callBack(r.payload),t.removeEventListener("load",o)},i=t=>n(this,void 0,void 0,(function*(){const o=yield new Promise(((e,n)=>e(t)));if(o){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(o))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield i(r.requestTransactionStatus())}))),7e3)}}}));yield i(r.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 e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,n=yield fetch(t,{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 e={},t=new URLSearchParams(window.location.search);for(const[n,r]of t)e[n]=r;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return n(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const r=document.createElement("input");r.type="hidden",r.name=e.term_url,r.value=e.TermUrl,t.appendChild(r),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return n(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const R=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function y(e,t,r){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,o=r,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},o),"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 e=yield i.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function v(e,t,r=!0,o=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(r),yield n.deviceData.setup({signal:o})}))}const A="https://cdn.kushkipagos.com/kushki.min.js";let f=!1,O=null;class T{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t,this.apiUrl=this.isTestEnvironment?"https://api-stage.tonder.io":"https://api.tonder.io",this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return n(this,void 0,void 0,(function*(){yield function(){return n(this,void 0,void 0,(function*(){return f?Promise.resolve():O||(O=new Promise(((e,t)=>{if(document.querySelector(`script[src="${A}"]`))return f=!0,void e();const n=document.createElement("script");n.src=A,n.async=!0,n.onload=()=>{f=!0,e()},n.onerror=()=>{O=null,t(new Error("Failed to load acquirer script"))},document.head.appendChild(n)})),O)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw new Error("Acquirer script not loaded. Call initialize() first.");return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw new Error("CardOnFile not initialized. Call initialize() first.");return this.acquirerInstance}getJwt(e){return n(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((n,r)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void r(new Error(`Error getting JWT: ${e.message}`));const t=e;t.jwt?n(t.jwt):r(new Error("No JWT returned from acquirer"))}))}))}))}generateToken(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to generate token: ${t.status} - ${e}`)}return t.json()}))}createSubscription(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/create`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to create subscription: ${t.status} - ${e}`)}return t.json()}))}validate3DS(e,t){return n(this,void 0,void 0,(function*(){const n=this.getAcquirerInstance();return new Promise(((r,o)=>{n.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?o(new Error("3DS validation failed}")):!1!==t.isValid?r(!0):o(new Error("3DS validation failed"))}))}))}))}process(e){var t,r;return n(this,void 0,void 0,(function*(){const n=yield this.getJwt(e.cardBin),o=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:n}),i=o.secureId||(null===(t=o.details)||void 0===t?void 0:t.secureId),s=o.security||(null===(r=o.details)||void 0===r?void 0:r.security);if(!i||!s)throw new Error("Missing secureId or security in token response");return yield this.validate3DS(i,s),this.createSubscription({token:o.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}var g,I,C,S,N,b,D,M,U,L,w,P,k;class j{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:r,returnUrl:o,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.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,I.set(this,void 0),C.set(this,void 0),this.apiKeyTonder=r||n||"",this.returnUrl=o,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||R[this.mode]||R.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new m({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(e){"secureToken"in e&&r(this,g,"m",b).call(this,e.secureToken),r(this,g,"m",S).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield r(this,g,"m",w).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,o)=>n(this,void 0,void 0,(function*(){try{r(this,g,"m",S).call(this,e);const n=yield this._checkout(e);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(n),t(n)}}catch(e){o(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw E(e)}}))}(this.baseUrl,e)}catch(e){throw _({message:d.secureTokenError},e)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return n(this,void 0,void 0,(function*(){return r(this,C,"f")||o(this,C,yield function(e,t,r,o=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,i={email:r.email,first_name:null==r?void 0:r.firstName,last_name:null==r?void 0:r.lastName,phone:null==r?void 0:r.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:o,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,C,"f")}))}_handleCheckout({card:t,payment_method:o,customer:i,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:h}=this.merchantData,E=Number(this.cartTotal);try{let p;!p&&l.merchant_id&&l.public_key&&!o&&(p=yield v(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:_,auth_token:m}=i,R={business:this.apiKeyTonder,client:m,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,o=r,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(o)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,R),f=(new Date).toISOString(),O={business_pk:h.pk,client_id:_,amount:E,date:f,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},T=yield function(e,t,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${r.business_pk}/payments/`,o=r,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(o)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,O),g=Object.assign(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:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:E,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:h.pk,payment_id:T.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:u(),currency:this.currency},o?{payment_method:o}:{card:t}),{apm_config:r(this,I,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),a?{enable_card_on_file:a}:{}),C=yield y(this.baseUrl,this.apiKeyTonder,g);return C||!1}catch(e){throw console.log(e),e}}))}_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(e){return this.merchantData}}))}_getCustomerCards(e,t){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,o,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${o}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield p(s)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,r,o=!1){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,o,i,s=!1){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${o}/cards/`,a=yield fetch(n,{method:"POST",headers:Object.assign({Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(i)});if(a.ok)return yield a.json();throw yield p(a)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,t,r,o)}))}_removeCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,o="",i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/${o}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return d.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield p(s)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,r,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,r={status:"active",pagesize:"10000"},o=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(r).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(i.ok)return yield i.json();throw yield p(i)}catch(e){throw E(e)}}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return n(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new T({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var t,r;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(r=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function V(e,t,r=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:r});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}I=new WeakMap,C=new WeakMap,g=new WeakSet,S=function(e){var t,n;!e||e&&0===Object.keys(e).length||(r(this,g,"m",N).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,g,"m",D).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),r(this,g,"m",M).call(this,e),r(this,g,"m",U).call(this,e),r(this,g,"m",L).call(this,e),r(this,g,"m",P).call(this,e))},N=function(e){e&&(this.customer=e)},b=function(e){this.secureToken=e},D=function(e){this.cartItems=e},M=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},U=function(e){this.currency=null==e?void 0:e.currency},L=function(e){this.card=null==e?void 0:e.card},w=function(e){var t,r,o;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(r=null==e?void 0:e.checkout)||void 0===r?void 0:r.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(o=e.checkout)||void 0===o?void 0:o.id)||(null==e?void 0:e.checkout_id)};try{return yield y(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},P=function(e){o(this,I,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(k||(k={}));const K={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},F=RegExp("^(?!s*$).+"),x={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:F,error:"El campo es requerido"}},B="Titular de la tarjeta",$="Número de tarjeta",Y="CVC/CVV",H="Mes",z="Año",W="Fecha de expiración",Q="Nombre como aparece en la tarjeta",q="1234 1234 1234 1234",J="3-4 dígitos",X="MM",G="AA",Z={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},ee={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},te={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ne({baseUrl:e,apiKey:r,vault_id:o,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:o,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,r){return n(this,void 0,void 0,(function*(){const o=yield function(e,r){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>n(this,void 0,void 0,(function*(){return{element:yield r.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,r);return o?o.map((t=>new Promise((n=>{var r;const o=document.createElement("div");o.hidden=!0,o.id=`id-${t.key}`,null===(r=document.querySelector("body"))||void 0===r||r.appendChild(o),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const r=e[t.key];return t.element.setValue(r),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw E(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw E(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw E(e)}}))}function re(e){const{element:n,fieldMessage:r="",errorStyles:o={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{ie({eventName:"onChange",data:e,events:a}),oe({element:n,errorStyles:o,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(ie({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=r?`El campo ${r} no es válido`:s;n.setError(t)}oe({element:n,errorStyles:o})})),n.on(t.EventName.FOCUS,(e=>{ie({eventName:"onFocus",data:e,events:a}),oe({element:n,errorStyles:o,color:"transparent"}),n.resetError()})))}function oe(e){const{element:t,errorStyles:n={},color:r=""}=e;Object.keys(n).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},n),{base:Object.assign(Object.assign({},n.base&&Object.assign({},n.base)),""!=r&&{color:r})})})}const ie=t=>{const{eventName:n,data:r,events:o}=t;if(o&&n in o){const t=o[n];"function"==typeof t&&t({elementType:e(r,"elementType",""),isEmpty:e(r,"isEmpty",""),isFocused:e(r,"isFocused",""),isValid:e(r,"isValid","")})}};function se(e){return n(this,void 0,void 0,(function*(){const{element:t,containerId:n,retries:r=2,delay:o=30}=e;for(let e=0;e<=r;e++){if(document.querySelector(n))return void t.mount(n);e<r&&(yield new Promise((e=>setTimeout(e,o))))}console.warn(`[mountCardFields] Container ${n} was not found after ${r+1} attempts`)}))}const ae=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"}),de={[ae.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[ae.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[ae.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[ae.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[ae.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[ae.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[ae.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[ae.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[ae.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[ae.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[ae.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[ae.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[ae.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[ae.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[ae.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[ae.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[ae.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[ae.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[ae.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[ae.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[ae.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[ae.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[ae.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[ae.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[ae.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[ae.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[ae.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[ae.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[ae.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[ae.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[ae.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[ae.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},le=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return de[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ce extends j{constructor({apiKey:e,mode:t,returnUrl:n,callBack:r,apiKeyTonder:o,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:r,apiKeyTonder:o,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.skyflowInstance=null,this.events=d||{}}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:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw _({message:d.getCardsError},e)}}))}saveCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{vault_id:n,vault_url:r,business:o}=this.merchantData,i=yield ne({vault_id:n,vault_url:r,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(t,null==o?void 0:o.pk,i)}catch(e){throw _({message:d.saveCardError},e)}}))}removeCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(t,null==n?void 0:n.pk,e)}catch(e){throw _({message:d.removeCardError},e)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw _({message:d.getPaymentMethodsError},e)}}))}mountCardFields(e){var r;return n(this,void 0,void 0,(function*(){const o=e.card_id?`update:${e.card_id}`:"create",i=null!==(r=e.unmount_context)&&void 0!==r?r:"all";"none"!==i&&("current"===i?this.unmountCardFields(o):this.unmountCardFields(i)),yield this.createSkyflowInstance();const s=yield function(e){var r,o,i,s,a,d,l,c,u,h,E,p,_,m,R,y,v;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:f,events:O}=e,T=n.container(t.ContainerType.COLLECT),g=[],I={[k.CVV]:t.ElementType.CVV,[k.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[k.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[k.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[k.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},C={[k.CVV]:[x],[k.CARD_NUMBER]:[x],[k.EXPIRATION_MONTH]:[x],[k.EXPIRATION_YEAR]:[x],[k.CARDHOLDER_NAME]:[K,x]},S={errorStyles:(null===(o=null===(r=null==f?void 0:f.styles)||void 0===r?void 0:r.cardForm)||void 0===o?void 0:o.errorStyles)||te,inputStyles:(null===(s=null===(i=null==f?void 0:f.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||Z,labelStyles:(null===(d=null===(a=null==f?void 0:f.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||ee},N={name:(null===(l=null==f?void 0:f.labels)||void 0===l?void 0:l.name)||B,card_number:(null===(c=null==f?void 0:f.labels)||void 0===c?void 0:c.card_number)||$,cvv:(null===(u=null==f?void 0:f.labels)||void 0===u?void 0:u.cvv)||Y,expiration_date:(null===(h=null==f?void 0:f.labels)||void 0===h?void 0:h.expiry_date)||W,expiration_month:(null===(E=null==f?void 0:f.labels)||void 0===E?void 0:E.expiration_month)||H,expiration_year:(null===(p=null==f?void 0:f.labels)||void 0===p?void 0:p.expiration_year)||z},b={name:(null===(_=null==f?void 0:f.placeholders)||void 0===_?void 0:_.name)||Q,card_number:(null===(m=null==f?void 0:f.placeholders)||void 0===m?void 0:m.card_number)||q,cvv:(null===(R=null==f?void 0:f.placeholders)||void 0===R?void 0:R.cvv)||J,expiration_month:(null===(y=null==f?void 0:f.placeholders)||void 0===y?void 0:y.expiration_month)||X,expiration_year:(null===(v=null==f?void 0:f.placeholders)||void 0===v?void 0:v.expiration_year)||G},D={[k.CVV]:null==O?void 0:O.cvvEvents,[k.CARD_NUMBER]:null==O?void 0:O.cardNumberEvents,[k.EXPIRATION_MONTH]:null==O?void 0:O.monthEvents,[k.EXPIRATION_YEAR]:null==O?void 0:O.yearEvents,[k.CARDHOLDER_NAME]:null==O?void 0:O.cardHolderEvents};if("fields"in A&&Array.isArray(A.fields))if(A.fields.length>0&&"string"==typeof A.fields[0])for(const e of A.fields){const t=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:I[e],validations:C[e]},S),{label:N[e],placeholder:b[e]}),A.card_id?{skyflowID:A.card_id}:{}));re({element:t,errorStyles:S.errorStyles,fieldMessage:[k.CVV,k.EXPIRATION_MONTH,k.EXPIRATION_YEAR].includes(e)?"":N[e],events:D[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:t,containerId:n}),g.push({element:t,containerId:n})}else for(const e of A.fields){const t=e.field,n=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:I[t],validations:C[t]},S),{label:N[t],placeholder:b[t]}),A.card_id?{skyflowID:A.card_id}:{})),r=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:n,containerId:r}),g.push({element:n,containerId:r})}return{elements:g.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(o,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const n=`update:${e}`,r=this.mountedElementsByContext.get(n);return(null===(t=null==r?void 0:r.container)||void 0===t?void 0:t.container)||null}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:n}=t;n&&n.length>0&&n.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw _({message:d.getBusinessError},e)}}))}createSkyflowInstance(){return n(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:r}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:r,vault_id:o,vault_url:i}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:o,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,r){return n(this,void 0,void 0,(function*(){try{return yield v(e,t,r)}catch(e){throw E(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:r}){return n(this,void 0,void 0,(function*(){return yield ne({vault_id:e,vault_url:t,data:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:r,returnUrl:o}){var i;return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:s,vault_url:d}=this.merchantData;let l;if(!t)if("string"==typeof e){const t=this.getContainerByCardId(e);try{t&&(yield t.collect())}catch(e){if(t){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw new c({code:a.MOUNT_COLLECT_ERROR,details:{message:t}})}}l={skyflow_id:e}}else l=yield ne({vault_id:s,vault_url:d,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._handleCheckout({card:l,payment_method:t,customer:n,isSandbox:r,returnUrl:o})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw E(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw E(e)}}))}createPayment(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,n=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw E(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield y(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return n(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:r,skyflowTokens:o,return_url:i,isSandbox:a,metadata:d,currency:l,payment_method:c}=e,h=yield this._fetchMerchantData(),E=yield this.customerRegister(r.email);if(!(E&&"auth_token"in E&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:E.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},p=yield this.createOrder(e),_=(new Date).toISOString();if(!("id"in p&&"id"in E&&"business"in h))throw new s({code:"500",body:p,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:_,order_id:p.id,client_id:E.id},t=yield this.createPayment(e);let s;const{openpay_keys:m,business:R}=h;m.merchant_id&&m.public_key&&(s=yield v(m.merchant_id,m.public_key,a));const A=Object.assign(Object.assign({name:r.name,last_name:r.lastname,email_client:r.email,phone_number:r.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 p&&p.id,business_id:R.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:u(),currency:l},c?{payment_method:c}:{card:o}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),f=yield y(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw E(e)}}))}registerCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${h(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},r))});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw E(e)}}))}deleteCustomerCard(e,t=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${h(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield p(n)}catch(e){throw E(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,r="?status=active&page_size=10000&country=México",o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw E(e)}}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function ue(e){return/^\d{12,19}$/.test(e)&&me(e)}function he(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Ee(e){return/^\d{3,4}$/.test(e)}function pe(e){return/^(0[1-9]|1[0-2])$/.test(e)}function _e(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const me=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let r=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return r+=n,r%10==0};export{j as BaseInlineCheckout,ce as LiteCheckout,Ee as validateCVV,ue as validateCardNumber,he as validateCardholderName,pe as validateExpirationMonth,_e as validateExpirationYear};
1
+ import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{d(r.next(e))}catch(e){o(e)}}function a(e){try{d(r.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((r=r.apply(e,t||[])).next())}))}function r(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function i(e,t,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(e,n):i?i.value=n:t.set(e,n),n}function o(e,t,r){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:r});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:r,stack:i}){this.code=e,this.body=t,this.name=n,this.message=r,this.stack=i}}var a;!function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(a||(a={}));const d=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."}),l={[a.INIT_ERROR]:"Error initializing the SDK.",[a.INVALID_TYPE]:"SDK Type invalid.",[a.STATE_ERROR]:"Error updating SDK state.",[a.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[a.INVALID_CONFIG]:"Required configuration options.",[a.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[a.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[a.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[a.TYPE_SDK_REQUIRED]:"SDK type required.",[a.ENVIRONMENT_REQUIRED]:"Environment required.",[a.FETCH_CARDS_ERROR]:"Error retrieving cards.",[a.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[a.SAVE_CARD_ERROR]:"Error saving the card.",[a.REMOVE_CARD_ERROR]:"Error deleting the card.",[a.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[a.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[a.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[a.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[a.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[a.START_CHECKOUT_ERROR]:"Error processing the payment.",[a.CREATE_ORDER_ERROR]:"Error creating the order.",[a.BUSINESS_ID_REQUIRED]:"Business ID is required.",[a.CLIENT_ID_REQUIRED]:"Client ID is required.",[a.INVALID_AMOUNT]:"Invalid amount.",[a.INVALID_ITEMS]:"Invalid items.",[a.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[a.INVALID_EMAIL]:"Invalid email.",[a.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[a.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[a.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[a.SECURE_TOKEN_ERROR]:"Error getting secure token.",[a.SECURE_TOKEN_INVALID]:"Invalid secure token.",[a.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[a.REMOVE_CARD]:"Card deleted successfully",[a.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[a.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[a.INVALID_CARD_DATA]:"Invalid card data.",[a.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[a.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[a.REQUEST_ABORTED]:"Requests canceled.",[a.REQUEST_FAILED]:"Request failed.",[a.UNKNOWN_ERROR]:"An unexpected error occurred.",[a.CREATE_ERROR]:"Error creating the SDK.",[a.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[a.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[a.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};a.INIT_ERROR,a.STATE_ERROR,a.FETCH_BUSINESS_ERROR,a.INVALID_CONFIG,a.TYPE_SDK_REQUIRED,a.ENVIRONMENT_REQUIRED,a.FETCH_CARDS_ERROR,a.SAVE_CARD_ERROR,a.REMOVE_CARD_ERROR,a.CREATE_PAYMENT_ERROR,a.START_CHECKOUT_ERROR,a.CREATE_ORDER_ERROR,a.BUSINESS_ID_REQUIRED,a.CLIENT_ID_REQUIRED,a.INVALID_AMOUNT,a.INVALID_ITEMS,a.CUSTOMER_OPERATION_ERROR,a.INVALID_EMAIL,a.FETCH_PAYMENT_METHODS_ERROR,a.INVALID_VAULT_TOKEN,a.VAULT_TOKEN_ERROR,a.SECURE_TOKEN_ERROR,a.INVALID_SECRET_API_KEY,a.CUSTOMER_AUTH_TOKEN_NOT_VALID,a.SECURE_TOKEN_INVALID,a.REMOVE_CARD,a.SKYFLOW_NOT_INITIALIZED,a.INVALID_TYPE,a.PAYMENT_PROCESS_ERROR,a.INVALID_PAYMENT_REQUEST,a.INVALID_PAYMENT_REQUEST_CARD_PM,a.SAVE_CARD_PROCESS_ERROR,a.ERROR_LOAD_PAYMENT_FORM,a.INVALID_CARD_DATA,a.ERROR_LOAD_ENROLLMENT_FORM,a.MOUNT_COLLECT_ERROR,a.CARD_SAVED_SUCCESSFULLY,a.CARD_REMOVED_SUCCESSFULLY,a.REQUEST_ABORTED,a.REQUEST_FAILED,a.UNKNOWN_ERROR,a.CREATE_ERROR,a.FETCH_TRANSACTION_ERROR,a.THREEDS_REDIRECTION_ERROR,a.REMOVE_SDK_ERROR;class c extends Error{constructor(e){var t,n;const r=e.message||l[e.code]||"Unknown error";super(r),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(n=e.details)||void 0===n?void 0:n.message)||r}}}const u=()=>({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}),h=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},p=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),_=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,r,i="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(r=e.status.toString()),!n&&e&&"text"in e&&(i=yield e.text()),(null==n?void 0:n.detail)&&(i=n.detail);return new s({code:r,body:n,name:r,message:i,stack:t})}));function m(e,t){var n,r;let i=200;try{i=Number((null==t?void 0:t.code)||200)}catch(e){}const o={status:"error",code:i,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(r=null==t?void 0:t.body)||void 0===r?void 0:r.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},o),e)}class E{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:r,tdsIframeId:i,tonderPayButtonId:o,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.tdsIframeId=i,this.tonderPayButtonId=o,this.redirectOnComplete=r,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,r,i,o;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(o=null===(i=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===o?void 0:o.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,r,i;const o=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.iframe;if(o){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=o,document.body.appendChild(n);const r=document.createElement("script");r.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(r);const i=document.getElementById("tdsMmethodTgtFrame");i?i.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const r=this,i=e=>n(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),r.callBack&&r.callBack(r.payload),t.removeEventListener("load",i)},o=t=>n(this,void 0,void 0,(function*(){const i=yield new Promise(((e,n)=>e(t)));if(i){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(i))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield o(r.requestTransactionStatus())}))),7e3)}}}));yield o(r.requestTransactionStatus())}));t.addEventListener("load",i)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,n=yield fetch(t,{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 e={},t=new URLSearchParams(window.location.search);for(const[n,r]of t)e[n]=r;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return n(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const r=document.createElement("input");r.type="hidden",r.name=e.term_url,r.value=e.TermUrl,t.appendChild(r),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return n(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const y=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function R(e,t,r){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,i=r,o=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(o.status>=200&&o.status<=299)return yield o.json();{const e=yield o.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function v(e,t,r=!0,i=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(r),yield n.deviceData.setup({signal:i})}))}const A="https://cdn.kushkipagos.com/kushki.min.js";let f=!1,T=null;class O{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t,this.apiUrl=this.isTestEnvironment?"https://api-stage.tonder.io":"https://api.tonder.io",this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return n(this,void 0,void 0,(function*(){yield function(){return n(this,void 0,void 0,(function*(){return f?Promise.resolve():T||(T=new Promise(((e,t)=>{if(document.querySelector(`script[src="${A}"]`))return f=!0,void e();const n=document.createElement("script");n.src=A,n.async=!0,n.onload=()=>{f=!0,e()},n.onerror=()=>{T=null,t(new Error("Failed to load acquirer script"))},document.head.appendChild(n)})),T)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw new Error("Acquirer script not loaded. Call initialize() first.");return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw new Error("CardOnFile not initialized. Call initialize() first.");return this.acquirerInstance}getJwt(e){return n(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((n,r)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void r(new Error(`Error getting JWT: ${e.message}`));const t=e;t.jwt?n(t.jwt):r(new Error("No JWT returned from acquirer"))}))}))}))}generateToken(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to generate token: ${t.status} - ${e}`)}return t.json()}))}createSubscription(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/create`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to create subscription: ${t.status} - ${e}`)}return t.json()}))}validate3DS(e,t){return n(this,void 0,void 0,(function*(){const n=this.getAcquirerInstance();return new Promise(((r,i)=>{n.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(new Error("3DS validation failed}")):!1!==t.isValid?r(!0):i(new Error("3DS validation failed"))}))}))}))}process(e){var t,r;return n(this,void 0,void 0,(function*(){const n=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:n}),o=i.secureId||(null===(t=i.details)||void 0===t?void 0:t.secureId),s=i.security||(null===(r=i.details)||void 0===r?void 0:r.security);if(!o||!s)throw new Error("Missing secureId or security in token response");return yield this.validate3DS(o,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}var g,I,C,S,N,b,D,M,U,L,w,k,P;class j{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:r,returnUrl:i,tdsIframeId:o,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){g.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,I.set(this,void 0),C.set(this,void 0),this.apiKeyTonder=r||n||"",this.returnUrl=i,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||y[this.mode]||y.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new E({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:o,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=o}configureCheckout(e){"secureToken"in e&&r(this,g,"m",b).call(this,e.secureToken),r(this,g,"m",S).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield r(this,g,"m",w).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,i)=>n(this,void 0,void 0,(function*(){try{r(this,g,"m",S).call(this,e);const n=yield this._checkout(e);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(n),t(n)}}catch(e){i(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield _(n)}catch(e){throw p(e)}}))}(this.baseUrl,e)}catch(e){throw m({message:d.secureTokenError},e)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return n(this,void 0,void 0,(function*(){return r(this,C,"f")||i(this,C,yield function(e,t,r,i=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,o={email:r.email,first_name:null==r?void 0:r.firstName,last_name:null==r?void 0:r.lastName,phone:null==r?void 0:r.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:i,body:JSON.stringify(o)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,C,"f")}))}_handleCheckout({card:t,payment_method:i,customer:o,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:h}=this.merchantData,p=Number(this.cartTotal);try{let _;!_&&l.merchant_id&&l.public_key&&!i&&(_=yield v(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:m,auth_token:E}=o,y={business:this.apiKeyTonder,client:E,billing_address_id:null,shipping_address_id:null,amount:p,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,i=r,o=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(i)});if(201===o.status)return yield o.json();throw new Error(`Error: ${o.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,y),f=(new Date).toISOString(),T={business_pk:h.pk,client_id:m,amount:p,date:f,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},O=yield function(e,t,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${r.business_pk}/payments/`,i=r,o=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(i)});if(o.status>=200&&o.status<=299)return yield o.json();throw new Error(`Error: ${o.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,T),g=Object.assign(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:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:p,title_ship:"shipping",description:"transaction",device_session_id:_||null,token_id:"",order_id:A.id,business_id:h.pk,payment_id:O.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:u(),currency:this.currency},i?{payment_method:i}:{card:t}),{apm_config:r(this,I,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==a?{enable_card_on_file:a}:{}),C=yield R(this.baseUrl,this.apiKeyTonder,g);return C||!1}catch(e){throw console.log(e),e}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield o(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.merchantData}}))}_getCustomerCards(e,t){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,i,o=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t},signal:o});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield _(s)}catch(e){throw p(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,r,i=!1){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,i,o,s=!1){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(n,{method:"POST",headers:Object.assign({Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(o)});if(a.ok)return yield a.json();throw yield _(a)}catch(e){throw p(e)}}))}(this.baseUrl,e,this.secureToken,t,r,i)}))}_removeCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,i="",o){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${o}/cards/${i}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return d.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield _(s)}catch(e){throw p(e)}}))}(this.baseUrl,e,this.secureToken,r,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,r={status:"active",pagesize:"10000"},i=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(r).toString(),o=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:i});if(o.ok)return yield o.json();throw yield _(o)}catch(e){throw p(e)}}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return n(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new O({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var t,r;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(r=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function V(e,t,r=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:r});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}I=new WeakMap,C=new WeakMap,g=new WeakSet,S=function(e){var t,n;!e||e&&0===Object.keys(e).length||(r(this,g,"m",N).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,g,"m",D).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),r(this,g,"m",M).call(this,e),r(this,g,"m",U).call(this,e),r(this,g,"m",L).call(this,e),r(this,g,"m",k).call(this,e))},N=function(e){e&&(this.customer=e)},b=function(e){this.secureToken=e},D=function(e){this.cartItems=e},M=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},U=function(e){this.currency=null==e?void 0:e.currency},L=function(e){this.card=null==e?void 0:e.card},w=function(e){var t,r,i;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(r=null==e?void 0:e.checkout)||void 0===r?void 0:r.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield R(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},k=function(e){i(this,I,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(P||(P={}));const K={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},F=RegExp("^(?!s*$).+"),x={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:F,error:"El campo es requerido"}},B="Titular de la tarjeta",Y="Número de tarjeta",$="CVC/CVV",H="Mes",z="Año",W="Fecha de expiración",Q="Nombre como aparece en la tarjeta",q="1234 1234 1234 1234",X="3-4 dígitos",J="MM",G="AA",Z={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},ee={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},te={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ne({baseUrl:e,apiKey:r,vault_id:i,vault_url:o,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:i,vaultURL:o,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,r){return n(this,void 0,void 0,(function*(){const i=yield function(e,r){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>n(this,void 0,void 0,(function*(){return{element:yield r.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,r);return i?i.map((t=>new Promise((n=>{var r;const i=document.createElement("div");i.hidden=!0,i.id=`id-${t.key}`,null===(r=document.querySelector("body"))||void 0===r||r.appendChild(i),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const r=e[t.key];return t.element.setValue(r),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw p(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw p(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw p(e)}}))}function re(e){const{element:n,fieldMessage:r="",errorStyles:i={},requiredMessage:o="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{oe({eventName:"onChange",data:e,events:a}),ie({element:n,errorStyles:i,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(oe({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?o:""!=r?`El campo ${r} no es válido`:s;n.setError(t)}ie({element:n,errorStyles:i})})),n.on(t.EventName.FOCUS,(e=>{oe({eventName:"onFocus",data:e,events:a}),ie({element:n,errorStyles:i,color:"transparent"}),n.resetError()})))}function ie(e){const{element:t,errorStyles:n={},color:r=""}=e;Object.keys(n).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},n),{base:Object.assign(Object.assign({},n.base&&Object.assign({},n.base)),""!=r&&{color:r})})})}const oe=t=>{const{eventName:n,data:r,events:i}=t;if(i&&n in i){const t=i[n];"function"==typeof t&&t({elementType:e(r,"elementType",""),isEmpty:e(r,"isEmpty",""),isFocused:e(r,"isFocused",""),isValid:e(r,"isValid","")})}};function se(e){return n(this,void 0,void 0,(function*(){const{element:t,containerId:n,retries:r=2,delay:i=30}=e;for(let e=0;e<=r;e++){if(document.querySelector(n))return void t.mount(n);e<r&&(yield new Promise((e=>setTimeout(e,i))))}console.warn(`[mountCardFields] Container ${n} was not found after ${r+1} attempts`)}))}const ae=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"}),de={[ae.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[ae.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[ae.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[ae.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[ae.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[ae.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[ae.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[ae.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[ae.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[ae.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[ae.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[ae.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[ae.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[ae.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[ae.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[ae.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[ae.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[ae.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[ae.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[ae.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[ae.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[ae.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[ae.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[ae.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[ae.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[ae.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[ae.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[ae.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[ae.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[ae.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[ae.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[ae.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},le=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return de[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ce extends j{constructor({apiKey:e,mode:t,returnUrl:n,callBack:r,apiKeyTonder:i,baseUrlTonder:o,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:r,apiKeyTonder:i,baseUrlTonder:o,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.skyflowInstance=null,this.events=d||{}}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:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return this.customerCardsCache=t,Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw m({message:d.getCardsError},e)}}))}saveCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield this._getCustomer(),{auth_token:n,first_name:r="",last_name:i="",email:o=""}=t,{vault_id:s,vault_url:a,business:d}=this.merchantData,l=this._hasCardOnFileKeys(),c={card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")},u=yield ne({vault_id:s,vault_url:a,data:c,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),h=yield this._saveCustomerCard(n,null==d?void 0:d.pk,u,l);if(l){const t=h.card_bin;if(!t)throw new Error("Card BIN not returned from save card");const s=yield this._initializeCardOnFile(),a=yield s.process({cardTokens:{name:e.cardholder_name.trim(),number:c.card_number,expiryMonth:c.expiration_month,expiryYear:c.expiration_year,cvv:c.cvv},cardBin:t,contactDetails:{firstName:r||"",lastName:i||"",email:o||""},customerId:n,currency:this.currency||"MXN"}),l={skyflow_id:u.skyflow_id,subscription_id:a.subscriptionId};yield this._saveCustomerCard(n,null==d?void 0:d.pk,l)}return h}catch(e){throw m({message:d.saveCardError},e)}}))}removeCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(t,null==n?void 0:n.pk,e)}catch(e){throw m({message:d.removeCardError},e)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw m({message:d.getPaymentMethodsError},e)}}))}mountCardFields(e){var r;return n(this,void 0,void 0,(function*(){const i=e.card_id?`update:${e.card_id}`:"create",o=null!==(r=e.unmount_context)&&void 0!==r?r:"all";"none"!==o&&("current"===o?this.unmountCardFields(i):this.unmountCardFields(o)),yield this.createSkyflowInstance();const s=yield function(e){var r,i,o,s,a,d,l,c,u,h,p,_,m,E,y,R,v;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:f,events:T}=e,O=n.container(t.ContainerType.COLLECT),g=[],I={[P.CVV]:t.ElementType.CVV,[P.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[P.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[P.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[P.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},C={[P.CVV]:[x],[P.CARD_NUMBER]:[x],[P.EXPIRATION_MONTH]:[x],[P.EXPIRATION_YEAR]:[x],[P.CARDHOLDER_NAME]:[K,x]},S={errorStyles:(null===(i=null===(r=null==f?void 0:f.styles)||void 0===r?void 0:r.cardForm)||void 0===i?void 0:i.errorStyles)||te,inputStyles:(null===(s=null===(o=null==f?void 0:f.styles)||void 0===o?void 0:o.cardForm)||void 0===s?void 0:s.inputStyles)||Z,labelStyles:(null===(d=null===(a=null==f?void 0:f.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||ee},N={name:(null===(l=null==f?void 0:f.labels)||void 0===l?void 0:l.name)||B,card_number:(null===(c=null==f?void 0:f.labels)||void 0===c?void 0:c.card_number)||Y,cvv:(null===(u=null==f?void 0:f.labels)||void 0===u?void 0:u.cvv)||$,expiration_date:(null===(h=null==f?void 0:f.labels)||void 0===h?void 0:h.expiry_date)||W,expiration_month:(null===(p=null==f?void 0:f.labels)||void 0===p?void 0:p.expiration_month)||H,expiration_year:(null===(_=null==f?void 0:f.labels)||void 0===_?void 0:_.expiration_year)||z},b={name:(null===(m=null==f?void 0:f.placeholders)||void 0===m?void 0:m.name)||Q,card_number:(null===(E=null==f?void 0:f.placeholders)||void 0===E?void 0:E.card_number)||q,cvv:(null===(y=null==f?void 0:f.placeholders)||void 0===y?void 0:y.cvv)||X,expiration_month:(null===(R=null==f?void 0:f.placeholders)||void 0===R?void 0:R.expiration_month)||J,expiration_year:(null===(v=null==f?void 0:f.placeholders)||void 0===v?void 0:v.expiration_year)||G},D={[P.CVV]:null==T?void 0:T.cvvEvents,[P.CARD_NUMBER]:null==T?void 0:T.cardNumberEvents,[P.EXPIRATION_MONTH]:null==T?void 0:T.monthEvents,[P.EXPIRATION_YEAR]:null==T?void 0:T.yearEvents,[P.CARDHOLDER_NAME]:null==T?void 0:T.cardHolderEvents};if("fields"in A&&Array.isArray(A.fields))if(A.fields.length>0&&"string"==typeof A.fields[0])for(const e of A.fields){const t=O.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:I[e],validations:C[e]},S),{label:N[e],placeholder:b[e]}),A.card_id?{skyflowID:A.card_id}:{}));re({element:t,errorStyles:S.errorStyles,fieldMessage:[P.CVV,P.EXPIRATION_MONTH,P.EXPIRATION_YEAR].includes(e)?"":N[e],events:D[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:t,containerId:n}),g.push({element:t,containerId:n})}else for(const e of A.fields){const t=e.field,n=O.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:I[t],validations:C[t]},S),{label:N[t],placeholder:b[t]}),A.card_id?{skyflowID:A.card_id}:{})),r=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:n,containerId:r}),g.push({element:n,containerId:r})}return{elements:g.map((e=>e.element)),container:O}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const n=`update:${e}`,r=this.mountedElementsByContext.get(n);return(null===(t=null==r?void 0:r.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var t,r,i;return n(this,void 0,void 0,(function*(){const n=this.getContainerByCardId(e);if(!n)return null;try{const e=yield n.collect();return(null===(r=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===r?void 0:r.fields)||null}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw new c({code:a.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:n}=t;n&&n.length>0&&n.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield o(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw m({message:d.getBusinessError},e)}}))}createSkyflowInstance(){return n(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:r}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:r,vault_id:i,vault_url:o}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:i,vaultURL:o,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,r){return n(this,void 0,void 0,(function*(){try{return yield v(e,t,r)}catch(e){throw p(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:r}){return n(this,void 0,void 0,(function*(){return yield ne({vault_id:e,vault_url:t,data:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:r,returnUrl:i}){var o,s;return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const a=yield this._getCustomer(this.abortController.signal),{vault_id:d,vault_url:l,business:c}=this.merchantData,{auth_token:u,first_name:h="",last_name:p="",email:_=""}=a,m=this._hasCardOnFileKeys();let E,y=null,R=null,v=null,A=!1;const f=()=>n(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(u,this.merchantData.business.pk))}));if(!t){if("string"==typeof e)if(R=e,E={skyflow_id:e},m){yield f();const t=null===(s=null===(o=this.customerCardsCache)||void 0===o?void 0:o.cards)||void 0===s?void 0:s.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const n=!!t.fields.subscription_id;n||(yield this.collectCardTokens(e)),n&&(y={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else{const t=Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")});E=yield ne({vault_id:d,vault_url:l,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),R=E.skyflow_id,m&&(v={name:E.cardholder_name,number:E.card_number,expiryMonth:E.expiration_month,expiryYear:E.expiration_year,cvv:E.cvv},A=!0)}if(A){if(!R||!v)throw new Error("Missing card data for card-on-file processing");const e=(yield this._saveCustomerCard(u,null==c?void 0:c.pk,{skyflow_id:R},!0)).card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();y={subscriptionId:(yield t.process({cardTokens:v,cardBin:e,contactDetails:{firstName:h||"",lastName:p||"",email:_||""},customerId:u,currency:this.currency||"MXN"})).subscriptionId},yield this._saveCustomerCard(u,null==c?void 0:c.pk,{skyflow_id:R,subscription_id:y.subscriptionId})}}return yield this._handleCheckout({card:E,payment_method:t,customer:a,isSandbox:r,returnUrl:i,enable_card_on_file:!!(null==y?void 0:y.subscriptionId)})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield _(r)}catch(e){throw p(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield _(r)}catch(e){throw p(e)}}))}createPayment(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,n=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield _(r)}catch(e){throw p(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield R(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return n(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:r,skyflowTokens:i,return_url:o,isSandbox:a,metadata:d,currency:l,payment_method:c}=e,h=yield this._fetchMerchantData(),p=yield this.customerRegister(r.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 e={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),m=(new Date).toISOString();if(!("id"in _&&"id"in p&&"business"in h))throw new s({code:"500",body:_,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:m,order_id:_.id,client_id:p.id},t=yield this.createPayment(e);let s;const{openpay_keys:E,business:y}=h;E.merchant_id&&E.public_key&&(s=yield v(E.merchant_id,E.public_key,a));const A=Object.assign(Object.assign({name:r.name,last_name:r.lastname,email_client:r.email,phone_number:r.phone,return_url:o,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 _&&_.id,business_id:y.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:u(),currency:l},c?{payment_method:c}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),f=yield R(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw p(e)}}))}registerCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${h(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},r))});if(n.ok)return yield n.json();throw yield _(n)}catch(e){throw p(e)}}))}deleteCustomerCard(e,t=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${h(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield _(n)}catch(e){throw p(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,r="?status=active&page_size=10000&country=México",i=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:i});if(n.ok)return yield n.json();throw yield _(n)}catch(e){throw p(e)}}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function ue(e){return/^\d{12,19}$/.test(e)&&Ee(e)}function he(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function pe(e){return/^\d{3,4}$/.test(e)}function _e(e){return/^(0[1-9]|1[0-2])$/.test(e)}function me(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const Ee=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let r=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return r+=n,r%10==0};export{j as BaseInlineCheckout,ce as LiteCheckout,pe as validateCVV,ue as validateCardNumber,he as validateCardholderName,_e as validateExpirationMonth,me as validateExpirationYear};
@@ -9,6 +9,7 @@ export interface ICardSkyflowFields {
9
9
  skyflow_id: string;
10
10
  card_scheme: string;
11
11
  cardholder_name: string;
12
+ subscription_id?: string;
12
13
  }
13
14
  export interface ICustomerCardsResponse {
14
15
  user_id: number;
@@ -25,6 +26,7 @@ export interface ISaveCardInternalResponse {
25
26
  }
26
27
  export interface ISaveCardSkyflowRequest {
27
28
  skyflow_id: string;
29
+ subscription_id?: string;
28
30
  }
29
31
  export interface ISaveCardRequest {
30
32
  card_number: string;
@@ -12,6 +12,8 @@ export type CustomerRegisterResponse = {
12
12
  id: number | string;
13
13
  email: string;
14
14
  auth_token: string;
15
+ first_name?: string;
16
+ last_name?: string;
15
17
  };
16
18
  export type CreateOrderResponse = {
17
19
  id: number | string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonder.io/ionic-lite-sdk",
3
- "version": "0.0.63-beta.DEV-1975.4",
3
+ "version": "0.0.63-beta.DEV-1975.5",
4
4
  "description": "Tonder ionic lite SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -292,7 +292,7 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
292
292
  ...(!!payment_method ? { payment_method } : { card }),
293
293
  apm_config: this.#apm_config,
294
294
  ...(this.customer && "identification" in this.customer ? { identification: this.customer.identification } : {}),
295
- ...(!!enable_card_on_file ? { enable_card_on_file } : {}),
295
+ ...(enable_card_on_file !== undefined ? { enable_card_on_file } : {}),
296
296
  };
297
297
 
298
298
  const jsonResponseRouter = await startCheckoutRouter(
@@ -3,12 +3,12 @@ import {ErrorResponse} from "./errorResponse";
3
3
  import TonderError from "../shared/utils/errors";
4
4
  import {ErrorKeyEnum} from "../shared/enum/ErrorKeyEnum";
5
5
  import {
6
- buildErrorResponse,
7
- buildErrorResponseFromCatch,
8
- formatPublicErrorResponse,
9
- getBrowserInfo,
10
- getBusinessId,
11
- getCardType,
6
+ buildErrorResponse,
7
+ buildErrorResponseFromCatch,
8
+ formatPublicErrorResponse,
9
+ getBrowserInfo,
10
+ getBusinessId,
11
+ getCardType,
12
12
  } from "../helpers/utils";
13
13
  import {getCustomerAPMs} from "../data/api";
14
14
  import {BaseInlineCheckout} from "./BaseInlineCheckout";
@@ -17,38 +17,32 @@ import {getSkyflowTokens, initSkyflowInstance, mountSkyflowFields} from "../help
17
17
  import {startCheckoutRouter} from "../data/checkoutApi";
18
18
  import {getOpenpayDeviceSessionID} from "../data/openPayApi";
19
19
  import {getPaymentMethodDetails} from "../shared/catalog/paymentMethodsCatalog";
20
+ import {APM, IEvents, IInlineLiteCheckoutOptions, InCollectorContainer, TonderAPM} from "../types/commons";
20
21
  import {
21
- APM, IEvents,
22
- IInlineLiteCheckoutOptions,
23
- ILiteCustomizationOptions,
24
- InCollectorContainer,
25
- TonderAPM
26
- } from "../types/commons";
27
- import {
28
- ICustomerCardsResponse,
29
- IMountCardFieldsRequest,
30
- ISaveCardRequest,
31
- ISaveCardResponse,
32
- ISaveCardSkyflowRequest
22
+ ICustomerCardsResponse,
23
+ IMountCardFieldsRequest,
24
+ ISaveCardRequest,
25
+ ISaveCardResponse,
26
+ ISaveCardSkyflowRequest
33
27
  } from "../types/card";
34
28
  import {IPaymentMethod} from "../types/paymentMethod";
35
29
  import {
36
- CreateOrderResponse,
37
- CreatePaymentResponse,
38
- CustomerRegisterResponse,
39
- GetBusinessResponse,
40
- IErrorResponse,
41
- RegisterCustomerCardResponse,
42
- StartCheckoutResponse
30
+ CreateOrderResponse,
31
+ CreatePaymentResponse,
32
+ CustomerRegisterResponse,
33
+ GetBusinessResponse,
34
+ IErrorResponse,
35
+ RegisterCustomerCardResponse,
36
+ StartCheckoutResponse
43
37
  } from "../types/responses";
44
38
  import {
45
- CreateOrderRequest,
46
- CreatePaymentRequest,
47
- RegisterCustomerCardRequest,
48
- StartCheckoutFullRequest,
49
- StartCheckoutIdRequest,
50
- StartCheckoutRequest,
51
- TokensRequest
39
+ CreateOrderRequest,
40
+ CreatePaymentRequest,
41
+ RegisterCustomerCardRequest,
42
+ StartCheckoutFullRequest,
43
+ StartCheckoutIdRequest,
44
+ StartCheckoutRequest,
45
+ TokensRequest
52
46
  } from "../types/requests";
53
47
  import {ICardFields, IStartCheckoutResponse} from "../types/checkout";
54
48
  import {ILiteCheckout} from "../types/liteInlineCheckout";
@@ -69,6 +63,7 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
69
63
  private readonly events: IEvents
70
64
  // Store mounted elements by context: 'create' or 'update:card_id'
71
65
  private mountedElementsByContext: Map<string, { elements: any[], container: InCollectorContainer | null }> = new Map();
66
+ private customerCardsCache: ICustomerCardsResponse | null = null;
72
67
 
73
68
  constructor({ apiKey, mode, returnUrl, callBack, apiKeyTonder, baseUrlTonder, customization, collectorIds, events }: IInlineLiteCheckoutOptions) {
74
69
  super({ mode, apiKey, returnUrl, callBack, apiKeyTonder, baseUrlTonder, customization, tdsIframeId: collectorIds && 'tdsIframe' in collectorIds ? collectorIds?.tdsIframe : "tdsIframe"});
@@ -88,13 +83,14 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
88
83
  auth_token,
89
84
  this.merchantData!.business.pk,
90
85
  );
86
+ this.customerCardsCache = response;
91
87
 
92
88
  return {
93
- ...response,
94
- cards: response.cards.map((ic) => ({
95
- ...ic,
96
- icon: getCardType(ic.fields.card_scheme),
97
- })),
89
+ ...response,
90
+ cards: response.cards.map((ic) => ({
91
+ ...ic,
92
+ icon: getCardType(ic.fields.card_scheme),
93
+ })),
98
94
  };
99
95
  } catch (error) {
100
96
  throw formatPublicErrorResponse(
@@ -111,28 +107,71 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
111
107
  ): Promise<ISaveCardResponse> {
112
108
  try {
113
109
  await this._fetchMerchantData();
114
- const { auth_token } = await this._getCustomer();
110
+ const customerResponse = await this._getCustomer() as CustomerRegisterResponse;
111
+ const { auth_token, first_name = "", last_name = "", email = "" } = customerResponse;
115
112
  const { vault_id, vault_url, business } = this.merchantData!;
113
+ const cardOnFileEnabled = this._hasCardOnFileKeys();
114
+
115
+ const sanitizedCard = {
116
+ card_number: card.card_number.replace(/\s+/g, ""),
117
+ expiration_month: card.expiration_month.replace(/\s+/g, ""),
118
+ expiration_year: card.expiration_year.replace(/\s+/g, ""),
119
+ cvv: card.cvv.replace(/\s+/g, ""),
120
+ cardholder_name: card.cardholder_name.replace(/\s+/g, ""),
121
+ };
116
122
 
117
123
  const skyflowTokens: ISaveCardSkyflowRequest = await getSkyflowTokens({
118
124
  vault_id: vault_id,
119
125
  vault_url: vault_url,
120
- data: {...card,
121
- card_number: card.card_number.replace(/\s+/g, ""),
122
- expiration_month: card.expiration_month.replace(/\s+/g, ""),
123
- expiration_year: card.expiration_year.replace(/\s+/g, ""),
124
- cvv: card.cvv.replace(/\s+/g, ""),
125
- cardholder_name: card.cardholder_name.replace(/\s+/g, ""),
126
- },
126
+ data: sanitizedCard,
127
127
  baseUrl: this.baseUrl,
128
128
  apiKey: this.apiKeyTonder,
129
129
  });
130
130
 
131
- return await this._saveCustomerCard(
131
+ const saveResponse = await this._saveCustomerCard(
132
132
  auth_token,
133
133
  business?.pk,
134
134
  skyflowTokens,
135
+ cardOnFileEnabled,
135
136
  );
137
+
138
+ if (cardOnFileEnabled) {
139
+ const cardBin = saveResponse.card_bin;
140
+ if (!cardBin) {
141
+ throw new Error("Card BIN not returned from save card");
142
+ }
143
+
144
+ const cardOnFile = await this._initializeCardOnFile();
145
+ const result = await cardOnFile.process({
146
+ cardTokens: {
147
+ name: card.cardholder_name.trim(),
148
+ number: sanitizedCard.card_number,
149
+ expiryMonth: sanitizedCard.expiration_month,
150
+ expiryYear: sanitizedCard.expiration_year,
151
+ cvv: sanitizedCard.cvv,
152
+ },
153
+ cardBin,
154
+ contactDetails: {
155
+ firstName: first_name || "",
156
+ lastName: last_name || "",
157
+ email: email || "",
158
+ },
159
+ customerId: auth_token,
160
+ currency: this.currency || "MXN",
161
+ });
162
+
163
+ const updatePayload: ISaveCardSkyflowRequest = {
164
+ skyflow_id: skyflowTokens.skyflow_id,
165
+ subscription_id: result.subscriptionId,
166
+ };
167
+ await this._saveCustomerCard(
168
+ auth_token,
169
+ business?.pk,
170
+ updatePayload,
171
+ );
172
+ }
173
+
174
+ return saveResponse;
136
175
  } catch (error) {
137
176
  throw formatPublicErrorResponse(
138
177
  {
@@ -233,6 +272,26 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
233
272
  return (contextData?.container?.container as CollectorContainer) || null;
234
273
  }
235
274
 
275
+ private async collectCardTokens(cardId: string): Promise<Record<string, any> | null> {
276
+ const container = this.getContainerByCardId(cardId);
277
+ if (!container) {
278
+ return null;
279
+ }
280
+
281
+ try {
282
+ const collectResponse: any = await container.collect();
283
+ return collectResponse?.records?.[0]?.fields || null;
284
+ } catch (e: any) {
285
+ const errorDescription = e?.error?.description;
286
+ throw new TonderError({
287
+ code: ErrorKeyEnum.MOUNT_COLLECT_ERROR,
288
+ details: {
289
+ message: errorDescription
290
+ }
291
+ });
292
+ }
293
+ }
294
+
236
295
  public unmountCardFields(context: string = 'all'): void {
237
296
  if (context === 'all') {
238
297
  this.mountedElementsByContext.forEach((contextData, ctx) => {
@@ -346,40 +405,120 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
346
405
  returnUrl?: string;
347
406
  }) {
348
407
  await this._fetchMerchantData();
349
- const customer = await this._getCustomer(this.abortController.signal);
350
- const { vault_id, vault_url } = this.merchantData!;
408
+ const customer = await this._getCustomer(this.abortController.signal) as CustomerRegisterResponse;
409
+ const { vault_id, vault_url, business } = this.merchantData!;
410
+ const { auth_token, first_name = "", last_name = "", email = "" } = customer;
411
+ const cardOnFileEnabled = this._hasCardOnFileKeys();
351
412
  let skyflowTokens;
413
+ let subscriptionCard: { subscriptionId: string } | null = null;
414
+ let skyflowId: string | null = null;
415
+ let cardTokensForCardOnFile: { name: string; number: string; expiryMonth: string; expiryYear: string; cvv: string } | null = null;
416
+ let shouldProcessCardOnFile = false;
417
+
418
+ const ensureCustomerCards = async () => {
419
+ if (!this.customerCardsCache?.cards?.length) {
420
+ this.customerCardsCache = await this._getCustomerCards(
421
+ auth_token,
422
+ this.merchantData!.business.pk,
423
+ );
424
+ }
425
+ };
426
+
352
427
  if (!payment_method) {
353
428
  if (typeof card === "string") {
354
- // Get the container from the specific context for this card
355
- const container = this.getContainerByCardId(card);
429
+ skyflowId = card;
430
+ skyflowTokens = {
431
+ skyflow_id: card,
432
+ };
433
+
434
+ if (cardOnFileEnabled) {
435
+ await ensureCustomerCards();
436
+ const selectedCard = this.customerCardsCache?.cards?.find(
437
+ (item) => item.fields.skyflow_id === card,
438
+ );
439
+ if (!selectedCard) {
440
+ throw new Error("Card not found for card-on-file processing");
441
+ }
442
+ const hasSubscriptionId = !!selectedCard.fields.subscription_id;
356
443
 
357
- try{
358
- if (container) {
359
- await container.collect();
444
+ if (!hasSubscriptionId) {
445
+ await this.collectCardTokens(card);
360
446
  }
361
- }catch (e: any){
362
- if (container) {
363
- const errorDescription = e?.error?.description;
364
- throw new TonderError({
365
- code: ErrorKeyEnum.MOUNT_COLLECT_ERROR,
366
- details: {
367
- message: errorDescription
368
- }
369
- });
447
+
448
+ if (hasSubscriptionId) {
449
+ subscriptionCard = { subscriptionId: selectedCard.fields.subscription_id! };
370
450
  }
451
+ } else {
452
+ await this.collectCardTokens(card);
371
453
  }
372
- skyflowTokens = {
373
- skyflow_id: card,
374
- };
375
454
  } else {
455
+ const sanitizedCard = {
456
+ ...card!,
457
+ card_number: card!.card_number.replace(/\s+/g, ""),
458
+ expiration_month: card!.expiration_month.replace(/\s+/g, ""),
459
+ expiration_year: card!.expiration_year.replace(/\s+/g, ""),
460
+ cvv: card!.cvv.replace(/\s+/g, ""),
461
+ cardholder_name: card!.cardholder_name.replace(/\s+/g, ""),
462
+ };
376
463
  skyflowTokens = await getSkyflowTokens({
377
464
  vault_id: vault_id,
378
465
  vault_url: vault_url,
379
- data: { ...card, card_number: card!.card_number.replace(/\s+/g, "") },
466
+ data: sanitizedCard,
380
467
  baseUrl: this.baseUrl,
381
468
  apiKey: this.apiKeyTonder,
382
469
  });
470
+ skyflowId = skyflowTokens.skyflow_id;
471
+
472
+ if (cardOnFileEnabled) {
473
+ cardTokensForCardOnFile = {
474
+ name: skyflowTokens.cardholder_name,
475
+ number: skyflowTokens.card_number,
476
+ expiryMonth: skyflowTokens.expiration_month,
477
+ expiryYear: skyflowTokens.expiration_year,
478
+ cvv: skyflowTokens.cvv,
479
+ };
480
+ shouldProcessCardOnFile = true;
481
+ }
482
+ }
483
+
484
+ if (shouldProcessCardOnFile) {
485
+ if (!skyflowId || !cardTokensForCardOnFile) {
486
+ throw new Error("Missing card data for card-on-file processing");
487
+ }
488
+
489
+ const saveResponse = await this._saveCustomerCard(
490
+ auth_token,
491
+ business?.pk,
492
+ { skyflow_id: skyflowId },
493
+ true,
494
+ );
495
+ const cardBin = saveResponse.card_bin;
496
+ if (!cardBin) {
497
+ throw new Error("Card BIN not returned from save card");
498
+ }
499
+
500
+ const cardOnFile = await this._initializeCardOnFile();
501
+ const result = await cardOnFile.process({
502
+ cardTokens: cardTokensForCardOnFile,
503
+ cardBin,
504
+ contactDetails: {
505
+ firstName: first_name || "",
506
+ lastName: last_name || "",
507
+ email: email || "",
508
+ },
509
+ customerId: auth_token,
510
+ currency: this.currency || "MXN",
511
+ });
512
+ subscriptionCard = { subscriptionId: result.subscriptionId };
513
+
514
+ await this._saveCustomerCard(
515
+ auth_token,
516
+ business?.pk,
517
+ {
518
+ skyflow_id: skyflowId,
519
+ subscription_id: subscriptionCard.subscriptionId,
520
+ },
521
+ );
383
522
  }
384
523
  }
385
524
 
@@ -388,7 +527,8 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
388
527
  payment_method,
389
528
  customer,
390
529
  isSandbox,
391
- returnUrl: returnUrlData
530
+ returnUrl: returnUrlData,
531
+ enable_card_on_file: !!subscriptionCard?.subscriptionId,
392
532
  });
393
533
  }
394
534
 
package/src/types/card.ts CHANGED
@@ -10,6 +10,7 @@ export interface ICardSkyflowFields {
10
10
  skyflow_id: string;
11
11
  card_scheme: string;
12
12
  cardholder_name: string;
13
+ subscription_id?: string;
13
14
  }
14
15
 
15
16
  export interface ICustomerCardsResponse {
@@ -30,6 +31,7 @@ export interface ISaveCardInternalResponse {
30
31
 
31
32
  export interface ISaveCardSkyflowRequest {
32
33
  skyflow_id: string;
34
+ subscription_id?: string;
33
35
  }
34
36
 
35
37
  export interface ISaveCardRequest {
@@ -15,6 +15,8 @@ export type CustomerRegisterResponse = {
15
15
  id: number | string;
16
16
  email: string;
17
17
  auth_token: string;
18
+ first_name?:string;
19
+ last_name?: string;
18
20
  };
19
21
 
20
22
  export type CreateOrderResponse = {