@bizzsv/bizz-payment 1.4.2-dev → 1.5.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -46,7 +46,7 @@ Por favor revisa tu información e inténtalo de nuevo`)}buildConfirmPayload(e){
46
46
  }
47
47
  </style>
48
48
  <div class="bizz-spinner"></div>
49
- `,e}var Lt={minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!0};new Intl.NumberFormat(`en-US`,Lt);function Rt(e,t=`USD`,n=`currency`){return new Intl.NumberFormat(`en-US`,{style:n,currency:t,...Lt}).format(e)}function zt(e){return parseInt(e.replace(/,/g,``).replace(`.`,``),0)}var Bt=class e{static instance;orchestrator=wt.getInstance();urlValidateAmount=`external/online_payments/orders/validate`;lastAmountValidate=0;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setLastAmountValidate(e){this.lastAmountValidate=e}getLastAmountValidate(){return this.lastAmountValidate}async validateAmount(e,t=!1){let n=typeof e==`string`?zt(e):e;if(!t&&n===this.getLastAmountValidate())return;this.setLastAmountValidate(n);let r=await _t.getInstance().post(this.urlValidateAmount,{data:{branch_id:this.orchestrator.getConfig().data.branch_id,amount_cents:n}}),i=await r.json();return r.ok,i}},Vt={subtotal_cents:`amount`,billing_document_number:`billingDocumentNumber`,billing_email:`email`,card_network:`cardNumber`,cardholder_name:`cardHolder`,billing_name:`cardHolder`,country:`country`,description:`description`},Ht=new Set([`iv`,`tag`,`encrypted_data`,`encrypted_key`]),Ut=class{origin;constructor(e){this.origin=e}sendServerValidationErrors(e,t){if(typeof t==`string`||!e)return!1;let n=this.buildValidationResults(t);for(let t of n)e.postMessage({type:`payment-form:validation-result`,field:t.field,error:t.error},this.origin);return n.length>0}hasEncryptionPayloadErrors(e){return typeof e==`string`?!1:Object.keys(e).some(e=>Ht.has(e))}resolveServerErrorMessage(e){return typeof e==`string`?e:`Por favor, revisa los campos`}buildValidationResults(e){let t=[];for(let[n,r]of Object.entries(e)){let e=Vt[n],i=Array.isArray(r)?r.find(e=>typeof e==`string`):void 0;!e||!i||t.push({field:e,error:i})}return t}},Wt=class e{request=_t.getInstance();urlPaymentIntent=`external/online_payments/payment_intents`;orchestrator=wt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePaymentIntentPayload(e){let t=this.orchestrator.getConfig(),n=new Nt;try{await n.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let r={card_number:At(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:kt(e.cardExpiry).month,card_expiration_year:kt(e.cardExpiry).year},i=null;try{i=n.encryptData(r)}catch(e){throw Error(`Failed to encrypt data: `+e)}return{branch_id:t.data.branch_id,card_network:Ot(e.cardNumber),operation:e.operation||`default`,iv:i.iv,tag:i.tag,encrypted_data:i.encrypted_data,cardholder_name:e.cardHolder,card_last_digits:e.cardNumber.slice(-4),subtotal_currency:`USD`,billing_name:e.cardHolder,encrypted_key:i.encrypted_key,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),billing_email:e.email,description:e.description,billing_document_number:e.billingDocumentNumber}}async createPaymentIntent(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.urlPaymentIntent,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},Gt=class e{request=_t.getInstance();url=`external/online_payments/points`;orchestrator=wt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePayload(e){let t=this.orchestrator.getConfig(),n=new Nt;await n.getTokenFromServer();let r={card_number:At(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:kt(e.cardExpiry).month,card_expiration_year:kt(e.cardExpiry).year},i=n.encryptData(r);return{branch_id:t.data.branch_id,encrypted_data:i.encrypted_data,iv:i.iv,tag:i.tag,encrypted_key:i.encrypted_key}}async getPointsBalance(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.url,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},Kt=[{code:`51`,title:`¡Fondos insuficientes!`,message:`Intenta con otra tarjeta o confirma que tengas saldo disponible.`},{code:`04`,title:`¡Tarjeta bloqueada!`,message:`Contacta a tu banco o prueba con otra tarjeta.`},{code:`96`,title:`¡Sistema no disponible!`,message:`Vuelve a intentar en unos minutos.`},{code:`54`,title:`¡Tarjeta expirada!`,message:`Revisa la fecha de vencimiento o usa otra tarjeta.`},{code:`06`,title:`¡CVV no válido!`,message:`Verifica el código de seguridad e inténtalo de nuevo.`},{code:`99`,title:`¡Transacción inválida!`,message:`Revisa tus datos e inténtalo de nuevo.`}],qt=e=>Kt.find(t=>t.code===e)||{title:`¡Error al pagar!`,message:`Tu compra no pudo ser procesada!
49
+ `,e}var Lt={minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!0};new Intl.NumberFormat(`en-US`,Lt);function Rt(e,t=`USD`,n=`currency`){return new Intl.NumberFormat(`en-US`,{style:n,currency:t,...Lt}).format(e)}function zt(e){return parseInt(e.replace(/,/g,``).replace(`.`,``),0)}var Bt=class e{static instance;orchestrator=wt.getInstance();urlValidateAmount=`external/online_payments/orders/validate`;lastAmountValidate=0;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setLastAmountValidate(e){this.lastAmountValidate=e}getLastAmountValidate(){return this.lastAmountValidate}async validateAmount(e,t=!1){let n=typeof e==`string`?zt(e):e;if(!t&&n===this.getLastAmountValidate())return;this.setLastAmountValidate(n);let r=await _t.getInstance().post(this.urlValidateAmount,{data:{branch_id:this.orchestrator.getConfig().data.branch_id,amount_cents:n}}),i=await r.json();return r.ok,i}},Vt={subtotal_cents:`amount`,billing_document_number:`billingDocumentNumber`,billing_email:`email`,card_network:`cardNumber`,cardholder_name:`cardHolder`,billing_name:`cardHolder`,country:`country`,description:`description`},Ht=new Set([`iv`,`tag`,`encrypted_data`,`encrypted_key`]),Ut=class{origin;constructor(e){this.origin=e}sendServerValidationErrors(e,t){if(typeof t==`string`||!e)return!1;let n=this.buildValidationResults(t);for(let t of n)try{e.postMessage({type:`payment-form:validation-result`,field:t.field,error:t.error},this.origin)}catch{try{e.postMessage({type:`payment-form:validation-result`,field:t.field,error:t.error},`*`)}catch{}}return n.length>0}hasEncryptionPayloadErrors(e){return typeof e==`string`?!1:Object.keys(e).some(e=>Ht.has(e))}resolveServerErrorMessage(e){return typeof e==`string`?e:`Por favor, revisa los campos`}buildValidationResults(e){let t=[];for(let[n,r]of Object.entries(e)){let e=Vt[n],i=Array.isArray(r)?r.find(e=>typeof e==`string`):void 0;!e||!i||t.push({field:e,error:i})}return t}},Wt=class e{request=_t.getInstance();urlPaymentIntent=`external/online_payments/payment_intents`;orchestrator=wt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePaymentIntentPayload(e){let t=this.orchestrator.getConfig(),n=new Nt;try{await n.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let r={card_number:At(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:kt(e.cardExpiry).month,card_expiration_year:kt(e.cardExpiry).year},i=null;try{i=n.encryptData(r)}catch(e){throw Error(`Failed to encrypt data: `+e)}return{branch_id:t.data.branch_id,card_network:Ot(e.cardNumber),operation:e.operation||`default`,iv:i.iv,tag:i.tag,encrypted_data:i.encrypted_data,cardholder_name:e.cardHolder,card_last_digits:e.cardNumber.slice(-4),subtotal_currency:`USD`,billing_name:e.cardHolder,encrypted_key:i.encrypted_key,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),billing_email:e.email,description:e.description,billing_document_number:e.billingDocumentNumber}}async createPaymentIntent(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.urlPaymentIntent,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},Gt=class e{request=_t.getInstance();url=`external/online_payments/points`;orchestrator=wt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePayload(e){let t=this.orchestrator.getConfig(),n=new Nt;await n.getTokenFromServer();let r={card_number:At(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:kt(e.cardExpiry).month,card_expiration_year:kt(e.cardExpiry).year},i=n.encryptData(r);return{branch_id:t.data.branch_id,encrypted_data:i.encrypted_data,iv:i.iv,tag:i.tag,encrypted_key:i.encrypted_key}}async getPointsBalance(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.url,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},Kt=[{code:`51`,title:`¡Fondos insuficientes!`,message:`Intenta con otra tarjeta o confirma que tengas saldo disponible.`},{code:`04`,title:`¡Tarjeta bloqueada!`,message:`Contacta a tu banco o prueba con otra tarjeta.`},{code:`96`,title:`¡Sistema no disponible!`,message:`Vuelve a intentar en unos minutos.`},{code:`54`,title:`¡Tarjeta expirada!`,message:`Revisa la fecha de vencimiento o usa otra tarjeta.`},{code:`06`,title:`¡CVV no válido!`,message:`Verifica el código de seguridad e inténtalo de nuevo.`},{code:`99`,title:`¡Transacción inválida!`,message:`Revisa tus datos e inténtalo de nuevo.`}],qt=e=>Kt.find(t=>t.code===e)||{title:`¡Error al pagar!`,message:`Tu compra no pudo ser procesada!
50
50
  Por favor revisa tu información e inténtalo de nuevo`,code:0},Jt=[{label:`Documento Único de Identidad (DUI)`,value:`dui`},{label:`Pasaporte`,value:`passport`},{label:`Tarjeta de extranjero`,value:`resident_card`}],Yt=[{label:`Selecciona aquí`,value:``}],Xt=[{label:`Selecciona aquí`,value:``}],Zt={amount:{label:`Monto a pagar`,icon:`currency-dollar`,placeholder:`0.00`,divider:!0},documentType:{label:`Tipo de documento`,icon:`document`,placeholder:`Tipo de documento`,type:`select`,default:`dui`,options:Jt},billingDocumentNumber:{label:`Número de documento`,icon:`document`,placeholder:`1234567890`,type:`text`,mask:`########-#`},email:{label:`Correo electrónico`,icon:`email`,placeholder:`example@example.com`,type:`email`,divider:!0},cardNumber:{label:`Número de tarjeta`,icon:`credit-card`,placeholder:`4111 1111 1111 1111`,mask:`#### #### #### ####`},cardExpiry:{label:`Fecha de expiración`,icon:`calendar`,placeholder:`MM/YY`,mask:`##/##`},cardCvc:{label:`CVV`,icon:`shield-lock`,placeholder:`123`,mask:`###`,autocomplete:`off`},cardHolder:{label:`Nombre en tarjeta`,icon:`user`,placeholder:`John Doe`},description:{label:`Descripción`,icon:`description`,placeholder:`Description`}},Qt={amount:{label:`Monto a pagar`,icon:`currency-dollar`,placeholder:`0.00`,divider:!0},documentType:{label:`Tipo de documento`,icon:`document`,placeholder:`Selecciona tipo de documento`,type:`select`,default:`dui`,options:Jt},billingDocumentNumber:{label:`Número de documento`,icon:`document`,placeholder:`Escribe acá`,type:`text`,mask:`########-#`},firstName:{label:`Nombre`,icon:`user`,placeholder:`Ingresar nombre`},lastName:{label:`Apellido`,icon:`user`,placeholder:`Ingresar apellido`},email:{label:`Correo electrónico`,icon:`email`,placeholder:`Escribe acá`,type:`email`},phone:{label:`Teléfono`,icon:`phone`,placeholder:`Ingresar teléfono`,divider:!0},cardNumber:{label:`Número de tarjeta`,icon:`credit-card`,placeholder:`Escribe acá`,mask:`#### #### #### ####`},cardHolder:{label:`Nombre en tarjeta`,icon:`user`,placeholder:`Escribe acá`},cardExpiry:{label:`Fecha de vencimiento`,icon:`calendar`,placeholder:`Escribe acá`,mask:`##/##`},cardCvc:{label:`CVV`,icon:`shield-lock`,placeholder:`Escribe acá`,mask:`###`,divider:!0,autocomplete:`off`},country:{label:`País`,icon:`map-pin`,placeholder:`Selecciona aquí`,type:`select`,options:Yt},region:{label:`Región`,icon:`map-pin`,placeholder:`Selecciona aquí`,type:`select`,options:Xt},city:{label:`Ciudad`,icon:`map-pin`,placeholder:`Escribe aquí`},address:{label:`Dirección`,icon:`map-pin`,placeholder:`Escribe aquí`},postalCode:{label:`Código postal`,icon:`document`,placeholder:`Escribe aquí`,divider:!0},description:{label:`Descripción`,icon:`description`,placeholder:`Escribe acá`}},$t={amount:{label:`Monto a pagar`,icon:`currency-dollar`,placeholder:`0.00`,divider:!0},firstName:{label:`Nombre`,icon:`user`,placeholder:`Ingresar nombre`},lastName:{label:`Apellido`,icon:`user`,placeholder:`Ingresar apellido`},email:{label:`Correo electrónico`,icon:`email`,placeholder:`Escribe acá`,type:`email`},phone:{label:`Teléfono`,icon:`phone`,placeholder:`Ingresar teléfono`},country:{label:`País`,icon:`map-pin`,placeholder:`Selecciona aquí`,type:`select`,options:Yt},city:{label:`Ciudad`,icon:`map-pin`,placeholder:`Escribe aquí`},address:{label:`Dirección`,icon:`map-pin`,placeholder:`Escribe aquí`},postalCode:{label:`Código postal`,icon:`document`,placeholder:`Escribe aquí`,divider:!0},description:{label:`Descripción`,icon:`description`,placeholder:`Escribe acá`}};function en(e){let t=e?.label??`Pagar`;return`<button type="submit" data-label="${t}" data-loading-label="${e?.loadingLabel??`Procesando...`}">${t}</button>`}function tn(e){let{header:t}=e,n=!0,r=!0,i=!0,a=!0,o=!0;return typeof t==`boolean`&&!t?``:(typeof t==`object`&&(`logo`in t&&typeof t.logo==`boolean`&&(n=t.logo),`totalAmount`in t&&typeof t.totalAmount==`boolean`&&(r=t.totalAmount),`description`in t&&typeof t.description==`boolean`&&(i=t.description),`requestMessage`in t&&typeof t.requestMessage==`boolean`&&(a=t.requestMessage),`date`in t&&typeof t.date==`boolean`&&(o=t.date)),`
51
51
  <header class="form-header">
52
52
  ${n?`<img src="${e.logo}" alt="${e.name} Logo" class="commerce-logo">`:``}
@@ -165,7 +165,7 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Jt=[{label:`Docu
165
165
  ${u}
166
166
  ${i?`\n <template class="operation-form-template" data-operation="crypto">${i}</template>`:``}
167
167
  </div>
168
- `}function vn(e){let t=`<img src="${fn}" alt="Bizz Logo" class="bizz-logo">`,n=_n(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return un.replace(`<!--STYLES-->`,`<style>${pn}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--SCRIPT-->`,`<script>${dn}<\/script>`)}function yn(e){let t=document.createElement(`iframe`);return t.style.border=`none`,t.style.display=`block`,t.style.overflow=`hidden`,t.srcdoc=e,t.style.width=`100%`,t.style.height=`100%`,t}var bn=class e{static instance;customBaseUrl;token=null;apiKey=`a2e9d688-686a-482f-a1ae-ab7741b3861d`;apiSecret=`JNYA8miN6TvEvvflIptPzXOOLp2dWMm3uMQHqVxBssnZRV3X`;get baseUrl(){return this.customBaseUrl?this.customBaseUrl:typeof window>`u`?`https://api.staging.gocrypto.com`:`${window.location.pathname.startsWith(`/paylink`)?`/paylink`:``}/naka-api`}constructor(){}static getInstance(){return e.instance||=new e,e.instance}setCredentials(e,t,n){this.apiKey=e,this.apiSecret=t,n&&(this.customBaseUrl=n),this.token=null}async getAuthToken(){let e=await fetch(`${this.baseUrl}/api/v2/auth`,{method:`POST`,headers:{"Content-Type":`application/json`,"x-api-key":this.apiKey,"x-secret":this.apiSecret}});if(!e.ok)throw Error(`NAKA Auth failed with status ${e.status}: ${e.statusText}`);let t=await e.json();return this.token=t.access_token||t.token,this.token}async createCharge(e){let t=this.token??await this.getAuthToken(),n=await fetch(`${this.baseUrl}/api/v3/ecom/payments/charge`,{method:`POST`,headers:{"Content-Type":`application/json`,"access-token":t},body:JSON.stringify(e)});if(!n.ok)throw Error(`NAKA Create Charge failed with status ${n.status}: ${n.statusText}`);let r=await n.json();return{charge_id:r.charge_id,redirect_url:r.redirect_url}}async getChargeStatus(e){let t=this.token??await this.getAuthToken(),n=await fetch(`${this.baseUrl}/api/v3/ecom/payments/charge/${e}/status/all`,{method:`GET`,headers:{"Content-Type":`application/json`,"access-token":t}});if(!n.ok)throw Error(`NAKA Get Charge Status failed with status ${n.status}: ${n.statusText}`);let r=await n.json();return Array.isArray(r)?r:r.items??r.data??[r]}async getTransactionDetails(e){let t=this.token??await this.getAuthToken(),n=await fetch(`${this.baseUrl}/api/v3/ecom/payments/${e}/details`,{method:`GET`,headers:{"Content-Type":`application/json`,"access-token":t}});if(!n.ok)throw Error(`NAKA Get Transaction Details failed with status ${n.status}: ${n.statusText}`);return await n.json()}},xn=`<svg
168
+ `}function vn(e){let t=`<img src="${fn}" alt="Bizz Logo" class="bizz-logo">`,n=_n(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return un.replace(`<!--STYLES-->`,`<style>${pn}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--SCRIPT-->`,`<script>${dn}<\/script>`)}function yn(e){let t=document.createElement(`iframe`);return t.style.border=`none`,t.style.display=`block`,t.style.overflow=`hidden`,t.srcdoc=e,t.style.width=`100%`,t.style.height=`100%`,t}var bn=class e{static instance;request;constructor(){this.request=_t.getInstance()}static getInstance(){return e.instance||=new e,e.instance}async createCharge(e){let t=await this.request.post(`external/online_payments/orders/crypto/charge`,e);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge creation failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}async getChargeStatus(e){let t=await this.request.get(`external/online_payments/orders/crypto/charge/${e}/status`);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge status failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}},xn=`<svg
169
169
  xmlns="http://www.w3.org/2000/svg"
170
170
  width="24"
171
171
  height="24"
@@ -232,4 +232,4 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Jt=[{label:`Docu
232
232
  <path d="M12 3a12 12 0 0 0 8.5 3a12 12 0 0 1 -8.5 15a12 12 0 0 1 -8.5 -15a12 12 0 0 0 8.5 -3" />
233
233
  <path d="M11 11a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" />
234
234
  <path d="M12 12l0 2.5" />
235
- </svg>`,Tn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,En=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,Dn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,On=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,kn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,An=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,jn={"currency-dollar":xn,"credit-card":Sn,calendar:Cn,"shield-lock":wn,email:Tn,user:En,description:Dn,document:On,phone:kn,"map-pin":An};function Mn(e){let t=jn[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var Nn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?Ot(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Pn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:Mn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?Rt(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}}),Fn=class{config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=Nn.getInstance();origin=u;serverErrorHandler;orchestrator=wt.getInstance();paymentIntent=Wt.getInstance();points=Gt.getInstance();countryContent=Et.getInstance();processPayment=Pt.getInstance();stateContent=Dt.getInstance();amountEvaluation=Bt.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;constructor(e){this.config=e,this.currentAmount=e.totalAmount,this.serverErrorHandler=new Ut(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=It();e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}if(t.remove(),this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.messageHandler=async e=>{if(e.source!==this.iframe?.contentWindow)return;let t=e.data;if(t?.type){if(t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=zt(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=zt(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`||t.value.operation===`naka`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=qt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...$t,country:{...$t.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=ln(Pn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}t.type===`payment-form:return-initial`&&(this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm())}},window.addEventListener(`message`,this.messageHandler),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}applyFixedAmountFromOrderTemplate(){if(!this.config.paymentRequestCode&&!this.config.paymentOrderCode)return;let{data:e}=this.orchestrator.getConfig();if(e.order_template_id==null&&e.order_id==null||typeof e.amount_cents!=`number`||e.amount_cents<=0)return;let t=Rt(e.amount_cents/100,`USD`,`decimal`);this.config.description=e.description,this.config.totalAmount=zt(t),this.currentAmount=zt(t)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`)||r.includes(`naka`)||r.includes(`naka_crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...Qt,country:{...Qt.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:Zt,u=Zt,d=!!this.config.totalAmount,f=Pn(t,l,this.currentAmount,d),p=n?Pn(t,u,this.currentAmount,d):f,m=Pn(t,{...$t,country:{...$t.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=en(this.config.i18n?.submitButton),g=i?on(f):``,_=a?sn(p):``,v=o?cn(p,h):``,y=s?ln(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?Rt(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=yn(vn({headerHtml:tn({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:Mn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}resetForm(){this.iframe?.contentWindow?.postMessage({type:`payment-form:reset`},this.origin)}setSubmitLoading(e){this.iframe?.contentWindow?.postMessage({type:`payment-form:set-submit-loading`,disabled:e},this.origin)}setToken(e){this.iframe?.contentWindow?.postMessage({type:`payment-form:set-token`,token:e},this.origin)}sendAlert(e,t){this.iframe?.contentWindow?.postMessage({type:`payment-form:alert`,title:e,message:t},this.origin)}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=qt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??zt(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.iframe?.contentWindow?.postMessage({type:`payment-form:success`,paymentIntent:e},this.origin);let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=bn.getInstance(),n=this.config.totalAmount??this.currentAmount??zt(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():`SV`),a={shop_name:this.orchestrator.getConfig().data.name||`BIZZ Store`,order_number:`ORD-${Date.now()}`,currency_code:`USD`,amount:n,callback_endpoint:`https://bizz.sv/checkout/success`,webhook_endpoint:`https://bizz.sv/api/webhooks/naka`,kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,nationality:i,country:i,city:e.city||`San Salvador`,zip_code:e.postalCode||`1101`,address:e.address||`San Salvador`,phone_number:e.phone}};try{let r=await t.createCharge(a);this.setSubmitLoading(!1),this.iframe?.contentWindow?.postMessage({type:`payment-form:naka-checkout`,redirectUrl:r.redirect_url,chargeId:r.charge_id},this.origin),this.startNakaPolling(r.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert(`¡Error al crear cobro con Cripto!`,`No se pudo conectar con el servicio de pagos NAKA.`),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en NAKA`)}}startNakaPolling(e,t,n){this.stopNakaPolling();let r=bn.getInstance();this.nakaPollingInterval=setInterval(async()=>{try{let i=(await r.getChargeStatus(e)).find(e=>e.status===`SUCCESS`||e.status===`OVERPAID`);if(i){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:`USD`,response_code:`00`,authorization_number:i.transaction_id||`NAKA-${Date.now()}`,reference_number:i.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Cripto (NAKA)`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig().data.name,branch_name:this.orchestrator.getConfig().data.branch_name,card_network:`NAKA_CRYPTO`,card_last_digits:`CRYPTO`,invoice_serie:null}};this.sendSuccess(r)}}catch{}},3e3)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}};exports.BizzPaymentForm=Fn;
235
+ </svg>`,Tn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,En=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,Dn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,On=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,kn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,An=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,jn={"currency-dollar":xn,"credit-card":Sn,calendar:Cn,"shield-lock":wn,email:Tn,user:En,description:Dn,document:On,phone:kn,"map-pin":An};function Mn(e){let t=jn[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var Nn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?Ot(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Pn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:Mn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?Rt(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}}),Fn=class{config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=Nn.getInstance();origin=u;serverErrorHandler;orchestrator=wt.getInstance();paymentIntent=Wt.getInstance();points=Gt.getInstance();countryContent=Et.getInstance();processPayment=Pt.getInstance();stateContent=Dt.getInstance();amountEvaluation=Bt.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;constructor(e){this.config=e,this.currentAmount=e.totalAmount,this.serverErrorHandler=new Ut(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=It();e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}if(t.remove(),this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.messageHandler=async e=>{if(e.source&&e.source!==this.iframe?.contentWindow&&e.source!==window)return;let t=e.data;if(t?.type){if(t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=zt(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=zt(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`||t.value.operation===`naka`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=qt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...$t,country:{...$t.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=ln(Pn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}if(t.type===`payment-form:naka-callback`){if(t.status===`CANCELED`||t.status===`CANCELLED`){await this.handleNakaTerminalFailure(`¡Pago cancelado!`,`El pago con criptomonedas fue cancelado.`,400);return}if(t.status===`SUCCESS`||t.status===`COMPLETED`||t.status===`PAID`||t.status===`OVERPAID`){this.stopNakaPolling();let e={data:{id:t.chargeId||``,status:`success`,amount_cents:this.config.totalAmount??this.currentAmount??0,amount_currency:`USD`,response_code:`00`,authorization_number:t.chargeId||`NAKA-${Date.now()}`,reference_number:t.orderNumber||t.chargeId||``,billing_document_number:``,description:this.config.description||`Pago con Cripto (NAKA)`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:`NAKA_CRYPTO`,card_last_digits:`CRYPTO`,invoice_serie:null}};this.sendSuccess(e);return}}t.type===`payment-form:return-initial`&&(this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm())}},window.addEventListener(`message`,this.messageHandler),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}applyFixedAmountFromOrderTemplate(){if(!this.config.paymentRequestCode&&!this.config.paymentOrderCode)return;let{data:e}=this.orchestrator.getConfig();if(e.order_template_id==null&&e.order_id==null||typeof e.amount_cents!=`number`||e.amount_cents<=0)return;let t=Rt(e.amount_cents/100,`USD`,`decimal`);this.config.description=e.description,this.config.totalAmount=zt(t),this.currentAmount=zt(t)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`)||r.includes(`naka`)||r.includes(`naka_crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...Qt,country:{...Qt.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:Zt,u=Zt,d=!!this.config.totalAmount,f=Pn(t,l,this.currentAmount,d),p=n?Pn(t,u,this.currentAmount,d):f,m=Pn(t,{...$t,country:{...$t.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=en(this.config.i18n?.submitButton),g=i?on(f):``,_=a?sn(p):``,v=o?cn(p,h):``,y=s?ln(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?Rt(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=yn(vn({headerHtml:tn({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:Mn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}postMessageToIframe(e){try{this.iframe?.contentWindow?.postMessage(e,this.origin)}catch{try{this.iframe?.contentWindow?.postMessage(e,`*`)}catch{}}}resetForm(){this.postMessageToIframe({type:`payment-form:reset`})}setSubmitLoading(e){this.postMessageToIframe({type:`payment-form:set-submit-loading`,disabled:e})}setToken(e){this.postMessageToIframe({type:`payment-form:set-token`,token:e})}sendAlert(e,t){this.postMessageToIframe({type:`payment-form:alert`,title:e,message:t})}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=qt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??zt(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.postMessageToIframe({type:`payment-form:success`,paymentIntent:e});let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=bn.getInstance(),n=this.config.totalAmount??this.currentAmount??zt(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():`SV`),a={data:{branch_id:this.orchestrator.getConfig()?.data?.branch_id||this.config.branchCode,amount_cents:n,currency:`USD`,description:e.description||this.config.description||`Pago con Cripto`,billing_document_number:e.billingDocumentNumber||``,redirect_url:this.config.redirectUrl,kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,country:i,city:e.city||`San Salvador`,postal_code:e.postalCode||`1101`,address:e.address||`San Salvador`,phone_number:e.phone}}};try{let r=await t.createCharge(a);this.setSubmitLoading(!1),this.postMessageToIframe({type:`payment-form:naka-checkout`,redirectUrl:r.data.redirect_url,chargeId:r.data.charge_id}),this.startNakaPolling(r.data.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert(`¡Error al crear cobro con Cripto!`,`No se pudo conectar con el servicio de pagos NAKA.`),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en NAKA`)}}async handleNakaTerminalFailure(e,t,n){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm(),this.sendAlert(e,t),this.sendFailureEmitter(n,t)}startNakaPolling(e,t,n){this.stopNakaPolling();let r=bn.getInstance(),i=0,a=Date.now();this.nakaPollingInterval=setInterval(async()=>{try{if(Date.now()-a>=6e5){await this.handleNakaTerminalFailure(`¡Tiempo de espera agotado!`,`El tiempo para completar el pago con criptomonedas ha expirado.`,408);return}let o=await r.getChargeStatus(e);i=0;let s=o.data,c=s?.status;if(c===`SUCCESS`||c===`COMPLETED`||c===`PAID`||c===`OVERPAID`){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Cripto (NAKA)`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig().data.name,branch_name:this.orchestrator.getConfig().data.branch_name,card_network:`NAKA_CRYPTO`,card_last_digits:`CRYPTO`,invoice_serie:null}};this.sendSuccess(r);return}if(c===`CANCELED`||c===`CANCELLED`){await this.handleNakaTerminalFailure(`¡Pago cancelado!`,`El pago con criptomonedas fue cancelado.`,400);return}if(c===`EXPIRED`){await this.handleNakaTerminalFailure(`¡Cobro expirado!`,`El tiempo para completar el pago con criptomonedas ha finalizado.`,410);return}if(c===`FAILED`||c===`REJECTED`){await this.handleNakaTerminalFailure(`¡Pago fallido!`,`No se pudo procesar el pago con criptomonedas.`,422);return}if(c===`UNDERPAID`){await this.handleNakaTerminalFailure(`¡Monto insuficiente!`,`El monto pagado en criptomonedas es menor al requerido.`,422);return}if(c===`PENDING`||c===`IN_PROGRESS`||c===`OPEN`)return}catch(e){if(e?.status===422){let t=e?.data?.error||`No fue posible procesar el cobro con criptomonedas. Por favor, intenta con otro método.`;await this.handleNakaTerminalFailure(`¡Pago no disponible!`,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure(`¡Orden no encontrada!`,`El cobro no se encuentra disponible o fue cancelado.`,404);return}if(e?.status===401||e?.status===403){await this.handleNakaTerminalFailure(`¡Sesión expirada!`,`Tu sesión ha expirado. Por favor, intenta de nuevo.`,e.status);return}if(i++,i>=5){await this.handleNakaTerminalFailure(`¡Error de conexión!`,`No fue posible verificar el estado del pago con criptomonedas.`,500);return}}},3e3)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}};exports.BizzPaymentForm=Fn;
package/dist/index.d.ts CHANGED
@@ -32,6 +32,7 @@ export declare class BizzPaymentForm {
32
32
  private applyFixedAmountFromOrderTemplate;
33
33
  private renderForm;
34
34
  private notifyCountriesLoadError;
35
+ private postMessageToIframe;
35
36
  private resetForm;
36
37
  private setSubmitLoading;
37
38
  private setToken;
@@ -44,11 +45,14 @@ export declare class BizzPaymentForm {
44
45
  private sendSizingEmitter;
45
46
  private sendSuccess;
46
47
  private handleCryptoPayment;
48
+ private handleNakaTerminalFailure;
47
49
  private startNakaPolling;
48
50
  private stopNakaPolling;
49
51
  destroy(): void;
50
52
  }
51
53
 
54
+ declare type CryptoTransactionStatus = 'IN_PROGRESS' | 'OPEN' | 'PENDING' | 'SUCCESS' | 'COMPLETED' | 'PAID' | 'OVERPAID' | 'EXPIRED' | 'CANCELED' | 'CANCELLED' | 'FAILED' | 'REJECTED' | 'UNDERPAID' | string;
55
+
52
56
  declare type Environment = 'production' | 'sandbox';
53
57
 
54
58
  declare interface FormCustomHeader {
@@ -59,7 +63,7 @@ declare interface FormCustomHeader {
59
63
  date?: boolean;
60
64
  }
61
65
 
62
- declare type NakaTransactionStatus = 'IN_PROGRESS' | 'SUCCESS' | 'EXPIRED' | 'UNDERPAID' | 'OVERPAID' | 'CANCELED';
66
+ declare type NakaTransactionStatus = CryptoTransactionStatus;
63
67
 
64
68
  export declare interface PaymentFormConfig {
65
69
  iframeTarget: string;
@@ -71,6 +75,7 @@ export declare interface PaymentFormConfig {
71
75
  totalAmount?: number;
72
76
  header?: boolean | FormCustomHeader;
73
77
  environment?: Environment;
78
+ redirectUrl?: string;
74
79
  }
75
80
 
76
81
  declare type PaymentFormEventMap = {
@@ -158,6 +163,11 @@ export declare type PaymentFormMessage = {
158
163
  } | {
159
164
  type: 'payment-form:naka-status';
160
165
  status: NakaTransactionStatus;
166
+ } | {
167
+ type: 'payment-form:naka-callback';
168
+ status: string;
169
+ chargeId?: string;
170
+ orderNumber?: string;
161
171
  } | {
162
172
  type: 'payment-form:load-crypto-countries';
163
173
  } | {
@@ -46,7 +46,7 @@ Por favor revisa tu información e inténtalo de nuevo`)}buildConfirmPayload(e){
46
46
  }
47
47
  </style>
48
48
  <div class="bizz-spinner"></div>
49
- `,e}var Rt={minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!0};new Intl.NumberFormat(`en-US`,Rt);function zt(e,t=`USD`,n=`currency`){return new Intl.NumberFormat(`en-US`,{style:n,currency:t,...Rt}).format(e)}function Bt(e){return parseInt(e.replace(/,/g,``).replace(`.`,``),0)}var Vt=class e{static instance;orchestrator=Tt.getInstance();urlValidateAmount=`external/online_payments/orders/validate`;lastAmountValidate=0;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setLastAmountValidate(e){this.lastAmountValidate=e}getLastAmountValidate(){return this.lastAmountValidate}async validateAmount(e,t=!1){let n=typeof e==`string`?Bt(e):e;if(!t&&n===this.getLastAmountValidate())return;this.setLastAmountValidate(n);let r=await vt.getInstance().post(this.urlValidateAmount,{data:{branch_id:this.orchestrator.getConfig().data.branch_id,amount_cents:n}}),i=await r.json();return r.ok,i}},Ht={subtotal_cents:`amount`,billing_document_number:`billingDocumentNumber`,billing_email:`email`,card_network:`cardNumber`,cardholder_name:`cardHolder`,billing_name:`cardHolder`,country:`country`,description:`description`},Ut=new Set([`iv`,`tag`,`encrypted_data`,`encrypted_key`]),Wt=class{origin;constructor(e){this.origin=e}sendServerValidationErrors(e,t){if(typeof t==`string`||!e)return!1;let n=this.buildValidationResults(t);for(let t of n)e.postMessage({type:`payment-form:validation-result`,field:t.field,error:t.error},this.origin);return n.length>0}hasEncryptionPayloadErrors(e){return typeof e==`string`?!1:Object.keys(e).some(e=>Ut.has(e))}resolveServerErrorMessage(e){return typeof e==`string`?e:`Por favor, revisa los campos`}buildValidationResults(e){let t=[];for(let[n,r]of Object.entries(e)){let e=Ht[n],i=Array.isArray(r)?r.find(e=>typeof e==`string`):void 0;!e||!i||t.push({field:e,error:i})}return t}},Gt=class e{request=vt.getInstance();urlPaymentIntent=`external/online_payments/payment_intents`;orchestrator=Tt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePaymentIntentPayload(e){let t=this.orchestrator.getConfig(),n=new Pt;try{await n.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let r={card_number:jt(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:At(e.cardExpiry).month,card_expiration_year:At(e.cardExpiry).year},i=null;try{i=n.encryptData(r)}catch(e){throw Error(`Failed to encrypt data: `+e)}return{branch_id:t.data.branch_id,card_network:kt(e.cardNumber),operation:e.operation||`default`,iv:i.iv,tag:i.tag,encrypted_data:i.encrypted_data,cardholder_name:e.cardHolder,card_last_digits:e.cardNumber.slice(-4),subtotal_currency:`USD`,billing_name:e.cardHolder,encrypted_key:i.encrypted_key,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),billing_email:e.email,description:e.description,billing_document_number:e.billingDocumentNumber}}async createPaymentIntent(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.urlPaymentIntent,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},Kt=class e{request=vt.getInstance();url=`external/online_payments/points`;orchestrator=Tt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePayload(e){let t=this.orchestrator.getConfig(),n=new Pt;await n.getTokenFromServer();let r={card_number:jt(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:At(e.cardExpiry).month,card_expiration_year:At(e.cardExpiry).year},i=n.encryptData(r);return{branch_id:t.data.branch_id,encrypted_data:i.encrypted_data,iv:i.iv,tag:i.tag,encrypted_key:i.encrypted_key}}async getPointsBalance(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.url,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},qt=[{code:`51`,title:`¡Fondos insuficientes!`,message:`Intenta con otra tarjeta o confirma que tengas saldo disponible.`},{code:`04`,title:`¡Tarjeta bloqueada!`,message:`Contacta a tu banco o prueba con otra tarjeta.`},{code:`96`,title:`¡Sistema no disponible!`,message:`Vuelve a intentar en unos minutos.`},{code:`54`,title:`¡Tarjeta expirada!`,message:`Revisa la fecha de vencimiento o usa otra tarjeta.`},{code:`06`,title:`¡CVV no válido!`,message:`Verifica el código de seguridad e inténtalo de nuevo.`},{code:`99`,title:`¡Transacción inválida!`,message:`Revisa tus datos e inténtalo de nuevo.`}],Jt=e=>qt.find(t=>t.code===e)||{title:`¡Error al pagar!`,message:`Tu compra no pudo ser procesada!
49
+ `,e}var Rt={minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!0};new Intl.NumberFormat(`en-US`,Rt);function zt(e,t=`USD`,n=`currency`){return new Intl.NumberFormat(`en-US`,{style:n,currency:t,...Rt}).format(e)}function Bt(e){return parseInt(e.replace(/,/g,``).replace(`.`,``),0)}var Vt=class e{static instance;orchestrator=Tt.getInstance();urlValidateAmount=`external/online_payments/orders/validate`;lastAmountValidate=0;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setLastAmountValidate(e){this.lastAmountValidate=e}getLastAmountValidate(){return this.lastAmountValidate}async validateAmount(e,t=!1){let n=typeof e==`string`?Bt(e):e;if(!t&&n===this.getLastAmountValidate())return;this.setLastAmountValidate(n);let r=await vt.getInstance().post(this.urlValidateAmount,{data:{branch_id:this.orchestrator.getConfig().data.branch_id,amount_cents:n}}),i=await r.json();return r.ok,i}},Ht={subtotal_cents:`amount`,billing_document_number:`billingDocumentNumber`,billing_email:`email`,card_network:`cardNumber`,cardholder_name:`cardHolder`,billing_name:`cardHolder`,country:`country`,description:`description`},Ut=new Set([`iv`,`tag`,`encrypted_data`,`encrypted_key`]),Wt=class{origin;constructor(e){this.origin=e}sendServerValidationErrors(e,t){if(typeof t==`string`||!e)return!1;let n=this.buildValidationResults(t);for(let t of n)try{e.postMessage({type:`payment-form:validation-result`,field:t.field,error:t.error},this.origin)}catch{try{e.postMessage({type:`payment-form:validation-result`,field:t.field,error:t.error},`*`)}catch{}}return n.length>0}hasEncryptionPayloadErrors(e){return typeof e==`string`?!1:Object.keys(e).some(e=>Ut.has(e))}resolveServerErrorMessage(e){return typeof e==`string`?e:`Por favor, revisa los campos`}buildValidationResults(e){let t=[];for(let[n,r]of Object.entries(e)){let e=Ht[n],i=Array.isArray(r)?r.find(e=>typeof e==`string`):void 0;!e||!i||t.push({field:e,error:i})}return t}},Gt=class e{request=vt.getInstance();urlPaymentIntent=`external/online_payments/payment_intents`;orchestrator=Tt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePaymentIntentPayload(e){let t=this.orchestrator.getConfig(),n=new Pt;try{await n.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let r={card_number:jt(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:At(e.cardExpiry).month,card_expiration_year:At(e.cardExpiry).year},i=null;try{i=n.encryptData(r)}catch(e){throw Error(`Failed to encrypt data: `+e)}return{branch_id:t.data.branch_id,card_network:kt(e.cardNumber),operation:e.operation||`default`,iv:i.iv,tag:i.tag,encrypted_data:i.encrypted_data,cardholder_name:e.cardHolder,card_last_digits:e.cardNumber.slice(-4),subtotal_currency:`USD`,billing_name:e.cardHolder,encrypted_key:i.encrypted_key,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),billing_email:e.email,description:e.description,billing_document_number:e.billingDocumentNumber}}async createPaymentIntent(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.urlPaymentIntent,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},Kt=class e{request=vt.getInstance();url=`external/online_payments/points`;orchestrator=Tt.getInstance();static instance;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async generatePayload(e){let t=this.orchestrator.getConfig(),n=new Pt;await n.getTokenFromServer();let r={card_number:jt(e.cardNumber),card_security_code:e.cardCvc,cardholder_name:e.cardHolder,card_expiration_month:At(e.cardExpiry).month,card_expiration_year:At(e.cardExpiry).year},i=n.encryptData(r);return{branch_id:t.data.branch_id,encrypted_data:i.encrypted_data,iv:i.iv,tag:i.tag,encrypted_key:i.encrypted_key}}async getPointsBalance(e){let t=this.orchestrator.getAuthToken(),n=await this.request.post(this.url,{data:e},{headers:{Authorization:`Bearer ${t.access_token}`,"Content-Type":`application/json`}},`api/v2`),r=await n.json();return n.ok,r}},qt=[{code:`51`,title:`¡Fondos insuficientes!`,message:`Intenta con otra tarjeta o confirma que tengas saldo disponible.`},{code:`04`,title:`¡Tarjeta bloqueada!`,message:`Contacta a tu banco o prueba con otra tarjeta.`},{code:`96`,title:`¡Sistema no disponible!`,message:`Vuelve a intentar en unos minutos.`},{code:`54`,title:`¡Tarjeta expirada!`,message:`Revisa la fecha de vencimiento o usa otra tarjeta.`},{code:`06`,title:`¡CVV no válido!`,message:`Verifica el código de seguridad e inténtalo de nuevo.`},{code:`99`,title:`¡Transacción inválida!`,message:`Revisa tus datos e inténtalo de nuevo.`}],Jt=e=>qt.find(t=>t.code===e)||{title:`¡Error al pagar!`,message:`Tu compra no pudo ser procesada!
50
50
  Por favor revisa tu información e inténtalo de nuevo`,code:0},Yt=[{label:`Documento Único de Identidad (DUI)`,value:`dui`},{label:`Pasaporte`,value:`passport`},{label:`Tarjeta de extranjero`,value:`resident_card`}],Xt=[{label:`Selecciona aquí`,value:``}],Zt=[{label:`Selecciona aquí`,value:``}],Qt={amount:{label:`Monto a pagar`,icon:`currency-dollar`,placeholder:`0.00`,divider:!0},documentType:{label:`Tipo de documento`,icon:`document`,placeholder:`Tipo de documento`,type:`select`,default:`dui`,options:Yt},billingDocumentNumber:{label:`Número de documento`,icon:`document`,placeholder:`1234567890`,type:`text`,mask:`########-#`},email:{label:`Correo electrónico`,icon:`email`,placeholder:`example@example.com`,type:`email`,divider:!0},cardNumber:{label:`Número de tarjeta`,icon:`credit-card`,placeholder:`4111 1111 1111 1111`,mask:`#### #### #### ####`},cardExpiry:{label:`Fecha de expiración`,icon:`calendar`,placeholder:`MM/YY`,mask:`##/##`},cardCvc:{label:`CVV`,icon:`shield-lock`,placeholder:`123`,mask:`###`,autocomplete:`off`},cardHolder:{label:`Nombre en tarjeta`,icon:`user`,placeholder:`John Doe`},description:{label:`Descripción`,icon:`description`,placeholder:`Description`}},$t={amount:{label:`Monto a pagar`,icon:`currency-dollar`,placeholder:`0.00`,divider:!0},documentType:{label:`Tipo de documento`,icon:`document`,placeholder:`Selecciona tipo de documento`,type:`select`,default:`dui`,options:Yt},billingDocumentNumber:{label:`Número de documento`,icon:`document`,placeholder:`Escribe acá`,type:`text`,mask:`########-#`},firstName:{label:`Nombre`,icon:`user`,placeholder:`Ingresar nombre`},lastName:{label:`Apellido`,icon:`user`,placeholder:`Ingresar apellido`},email:{label:`Correo electrónico`,icon:`email`,placeholder:`Escribe acá`,type:`email`},phone:{label:`Teléfono`,icon:`phone`,placeholder:`Ingresar teléfono`,divider:!0},cardNumber:{label:`Número de tarjeta`,icon:`credit-card`,placeholder:`Escribe acá`,mask:`#### #### #### ####`},cardHolder:{label:`Nombre en tarjeta`,icon:`user`,placeholder:`Escribe acá`},cardExpiry:{label:`Fecha de vencimiento`,icon:`calendar`,placeholder:`Escribe acá`,mask:`##/##`},cardCvc:{label:`CVV`,icon:`shield-lock`,placeholder:`Escribe acá`,mask:`###`,divider:!0,autocomplete:`off`},country:{label:`País`,icon:`map-pin`,placeholder:`Selecciona aquí`,type:`select`,options:Xt},region:{label:`Región`,icon:`map-pin`,placeholder:`Selecciona aquí`,type:`select`,options:Zt},city:{label:`Ciudad`,icon:`map-pin`,placeholder:`Escribe aquí`},address:{label:`Dirección`,icon:`map-pin`,placeholder:`Escribe aquí`},postalCode:{label:`Código postal`,icon:`document`,placeholder:`Escribe aquí`,divider:!0},description:{label:`Descripción`,icon:`description`,placeholder:`Escribe acá`}},en={amount:{label:`Monto a pagar`,icon:`currency-dollar`,placeholder:`0.00`,divider:!0},firstName:{label:`Nombre`,icon:`user`,placeholder:`Ingresar nombre`},lastName:{label:`Apellido`,icon:`user`,placeholder:`Ingresar apellido`},email:{label:`Correo electrónico`,icon:`email`,placeholder:`Escribe acá`,type:`email`},phone:{label:`Teléfono`,icon:`phone`,placeholder:`Ingresar teléfono`},country:{label:`País`,icon:`map-pin`,placeholder:`Selecciona aquí`,type:`select`,options:Xt},city:{label:`Ciudad`,icon:`map-pin`,placeholder:`Escribe aquí`},address:{label:`Dirección`,icon:`map-pin`,placeholder:`Escribe aquí`},postalCode:{label:`Código postal`,icon:`document`,placeholder:`Escribe aquí`,divider:!0},description:{label:`Descripción`,icon:`description`,placeholder:`Escribe acá`}};function tn(e){let t=e?.label??`Pagar`;return`<button type="submit" data-label="${t}" data-loading-label="${e?.loadingLabel??`Procesando...`}">${t}</button>`}function nn(e){let{header:t}=e,n=!0,r=!0,i=!0,a=!0,o=!0;return typeof t==`boolean`&&!t?``:(typeof t==`object`&&(`logo`in t&&typeof t.logo==`boolean`&&(n=t.logo),`totalAmount`in t&&typeof t.totalAmount==`boolean`&&(r=t.totalAmount),`description`in t&&typeof t.description==`boolean`&&(i=t.description),`requestMessage`in t&&typeof t.requestMessage==`boolean`&&(a=t.requestMessage),`date`in t&&typeof t.date==`boolean`&&(o=t.date)),`
51
51
  <header class="form-header">
52
52
  ${n?`<img src="${e.logo}" alt="${e.name} Logo" class="commerce-logo">`:``}
@@ -165,7 +165,7 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Yt=[{label:`Docu
165
165
  ${u}
166
166
  ${i?`\n <template class="operation-form-template" data-operation="crypto">${i}</template>`:``}
167
167
  </div>
168
- `}function yn(e){let t=`<img src="${pn}" alt="Bizz Logo" class="bizz-logo">`,n=vn(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return dn.replace(`<!--STYLES-->`,`<style>${mn}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--SCRIPT-->`,`<script>${fn}<\/script>`)}function bn(e){let t=document.createElement(`iframe`);return t.style.border=`none`,t.style.display=`block`,t.style.overflow=`hidden`,t.srcdoc=e,t.style.width=`100%`,t.style.height=`100%`,t}var xn=class e{static instance;customBaseUrl;token=null;apiKey=`a2e9d688-686a-482f-a1ae-ab7741b3861d`;apiSecret=`JNYA8miN6TvEvvflIptPzXOOLp2dWMm3uMQHqVxBssnZRV3X`;get baseUrl(){return this.customBaseUrl?this.customBaseUrl:typeof window>`u`?`https://api.staging.gocrypto.com`:`${window.location.pathname.startsWith(`/paylink`)?`/paylink`:``}/naka-api`}constructor(){}static getInstance(){return e.instance||=new e,e.instance}setCredentials(e,t,n){this.apiKey=e,this.apiSecret=t,n&&(this.customBaseUrl=n),this.token=null}async getAuthToken(){let e=await fetch(`${this.baseUrl}/api/v2/auth`,{method:`POST`,headers:{"Content-Type":`application/json`,"x-api-key":this.apiKey,"x-secret":this.apiSecret}});if(!e.ok)throw Error(`NAKA Auth failed with status ${e.status}: ${e.statusText}`);let t=await e.json();return this.token=t.access_token||t.token,this.token}async createCharge(e){let t=this.token??await this.getAuthToken(),n=await fetch(`${this.baseUrl}/api/v3/ecom/payments/charge`,{method:`POST`,headers:{"Content-Type":`application/json`,"access-token":t},body:JSON.stringify(e)});if(!n.ok)throw Error(`NAKA Create Charge failed with status ${n.status}: ${n.statusText}`);let r=await n.json();return{charge_id:r.charge_id,redirect_url:r.redirect_url}}async getChargeStatus(e){let t=this.token??await this.getAuthToken(),n=await fetch(`${this.baseUrl}/api/v3/ecom/payments/charge/${e}/status/all`,{method:`GET`,headers:{"Content-Type":`application/json`,"access-token":t}});if(!n.ok)throw Error(`NAKA Get Charge Status failed with status ${n.status}: ${n.statusText}`);let r=await n.json();return Array.isArray(r)?r:r.items??r.data??[r]}async getTransactionDetails(e){let t=this.token??await this.getAuthToken(),n=await fetch(`${this.baseUrl}/api/v3/ecom/payments/${e}/details`,{method:`GET`,headers:{"Content-Type":`application/json`,"access-token":t}});if(!n.ok)throw Error(`NAKA Get Transaction Details failed with status ${n.status}: ${n.statusText}`);return await n.json()}},Sn=`<svg
168
+ `}function yn(e){let t=`<img src="${pn}" alt="Bizz Logo" class="bizz-logo">`,n=vn(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return dn.replace(`<!--STYLES-->`,`<style>${mn}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--SCRIPT-->`,`<script>${fn}<\/script>`)}function bn(e){let t=document.createElement(`iframe`);return t.style.border=`none`,t.style.display=`block`,t.style.overflow=`hidden`,t.srcdoc=e,t.style.width=`100%`,t.style.height=`100%`,t}var xn=class e{static instance;request;constructor(){this.request=vt.getInstance()}static getInstance(){return e.instance||=new e,e.instance}async createCharge(e){let t=await this.request.post(`external/online_payments/orders/crypto/charge`,e);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge creation failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}async getChargeStatus(e){let t=await this.request.get(`external/online_payments/orders/crypto/charge/${e}/status`);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge status failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}},Sn=`<svg
169
169
  xmlns="http://www.w3.org/2000/svg"
170
170
  width="24"
171
171
  height="24"
@@ -232,4 +232,4 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Yt=[{label:`Docu
232
232
  <path d="M12 3a12 12 0 0 0 8.5 3a12 12 0 0 1 -8.5 15a12 12 0 0 1 -8.5 -15a12 12 0 0 0 8.5 -3" />
233
233
  <path d="M11 11a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" />
234
234
  <path d="M12 12l0 2.5" />
235
- </svg>`,En=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,Dn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,On=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,kn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,An=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,jn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,Mn={"currency-dollar":Sn,"credit-card":Cn,calendar:wn,"shield-lock":Tn,email:En,user:Dn,description:On,document:kn,phone:An,"map-pin":jn};function Nn(e){let t=Mn[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var Pn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?kt(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Fn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:Nn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?zt(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}});return e.BizzPaymentForm=class{config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=Pn.getInstance();origin=d;serverErrorHandler;orchestrator=Tt.getInstance();paymentIntent=Gt.getInstance();points=Kt.getInstance();countryContent=Dt.getInstance();processPayment=Ft.getInstance();stateContent=Ot.getInstance();amountEvaluation=Vt.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;constructor(e){this.config=e,this.currentAmount=e.totalAmount,this.serverErrorHandler=new Wt(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=Lt();e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}if(t.remove(),this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.messageHandler=async e=>{if(e.source!==this.iframe?.contentWindow)return;let t=e.data;if(t?.type){if(t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=Bt(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=Bt(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`||t.value.operation===`naka`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=Jt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...en,country:{...en.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=un(Fn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}t.type===`payment-form:return-initial`&&(this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm())}},window.addEventListener(`message`,this.messageHandler),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}applyFixedAmountFromOrderTemplate(){if(!this.config.paymentRequestCode&&!this.config.paymentOrderCode)return;let{data:e}=this.orchestrator.getConfig();if(e.order_template_id==null&&e.order_id==null||typeof e.amount_cents!=`number`||e.amount_cents<=0)return;let t=zt(e.amount_cents/100,`USD`,`decimal`);this.config.description=e.description,this.config.totalAmount=Bt(t),this.currentAmount=Bt(t)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`)||r.includes(`naka`)||r.includes(`naka_crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...$t,country:{...$t.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:Qt,u=Qt,d=!!this.config.totalAmount,f=Fn(t,l,this.currentAmount,d),p=n?Fn(t,u,this.currentAmount,d):f,m=Fn(t,{...en,country:{...en.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=tn(this.config.i18n?.submitButton),g=i?sn(f):``,_=a?cn(p):``,v=o?ln(p,h):``,y=s?un(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?zt(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=bn(yn({headerHtml:nn({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:Nn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}resetForm(){this.iframe?.contentWindow?.postMessage({type:`payment-form:reset`},this.origin)}setSubmitLoading(e){this.iframe?.contentWindow?.postMessage({type:`payment-form:set-submit-loading`,disabled:e},this.origin)}setToken(e){this.iframe?.contentWindow?.postMessage({type:`payment-form:set-token`,token:e},this.origin)}sendAlert(e,t){this.iframe?.contentWindow?.postMessage({type:`payment-form:alert`,title:e,message:t},this.origin)}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=Jt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??Bt(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.iframe?.contentWindow?.postMessage({type:`payment-form:success`,paymentIntent:e},this.origin);let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=xn.getInstance(),n=this.config.totalAmount??this.currentAmount??Bt(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():`SV`),a={shop_name:this.orchestrator.getConfig().data.name||`BIZZ Store`,order_number:`ORD-${Date.now()}`,currency_code:`USD`,amount:n,callback_endpoint:`https://bizz.sv/checkout/success`,webhook_endpoint:`https://bizz.sv/api/webhooks/naka`,kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,nationality:i,country:i,city:e.city||`San Salvador`,zip_code:e.postalCode||`1101`,address:e.address||`San Salvador`,phone_number:e.phone}};try{let r=await t.createCharge(a);this.setSubmitLoading(!1),this.iframe?.contentWindow?.postMessage({type:`payment-form:naka-checkout`,redirectUrl:r.redirect_url,chargeId:r.charge_id},this.origin),this.startNakaPolling(r.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert(`¡Error al crear cobro con Cripto!`,`No se pudo conectar con el servicio de pagos NAKA.`),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en NAKA`)}}startNakaPolling(e,t,n){this.stopNakaPolling();let r=xn.getInstance();this.nakaPollingInterval=setInterval(async()=>{try{let i=(await r.getChargeStatus(e)).find(e=>e.status===`SUCCESS`||e.status===`OVERPAID`);if(i){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:`USD`,response_code:`00`,authorization_number:i.transaction_id||`NAKA-${Date.now()}`,reference_number:i.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Cripto (NAKA)`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig().data.name,branch_name:this.orchestrator.getConfig().data.branch_name,card_network:`NAKA_CRYPTO`,card_last_digits:`CRYPTO`,invoice_serie:null}};this.sendSuccess(r)}}catch{}},3e3)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}},e})({});
235
+ </svg>`,En=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,Dn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,On=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,kn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,An=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,jn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,Mn={"currency-dollar":Sn,"credit-card":Cn,calendar:wn,"shield-lock":Tn,email:En,user:Dn,description:On,document:kn,phone:An,"map-pin":jn};function Nn(e){let t=Mn[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var Pn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?kt(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Fn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:Nn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?zt(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}});return e.BizzPaymentForm=class{config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=Pn.getInstance();origin=d;serverErrorHandler;orchestrator=Tt.getInstance();paymentIntent=Gt.getInstance();points=Kt.getInstance();countryContent=Dt.getInstance();processPayment=Ft.getInstance();stateContent=Ot.getInstance();amountEvaluation=Vt.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;constructor(e){this.config=e,this.currentAmount=e.totalAmount,this.serverErrorHandler=new Wt(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=Lt();e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}if(t.remove(),this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.messageHandler=async e=>{if(e.source&&e.source!==this.iframe?.contentWindow&&e.source!==window)return;let t=e.data;if(t?.type){if(t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=Bt(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=Bt(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`||t.value.operation===`naka`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=Jt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...en,country:{...en.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=un(Fn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}if(t.type===`payment-form:naka-callback`){if(t.status===`CANCELED`||t.status===`CANCELLED`){await this.handleNakaTerminalFailure(`¡Pago cancelado!`,`El pago con criptomonedas fue cancelado.`,400);return}if(t.status===`SUCCESS`||t.status===`COMPLETED`||t.status===`PAID`||t.status===`OVERPAID`){this.stopNakaPolling();let e={data:{id:t.chargeId||``,status:`success`,amount_cents:this.config.totalAmount??this.currentAmount??0,amount_currency:`USD`,response_code:`00`,authorization_number:t.chargeId||`NAKA-${Date.now()}`,reference_number:t.orderNumber||t.chargeId||``,billing_document_number:``,description:this.config.description||`Pago con Cripto (NAKA)`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:`NAKA_CRYPTO`,card_last_digits:`CRYPTO`,invoice_serie:null}};this.sendSuccess(e);return}}t.type===`payment-form:return-initial`&&(this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm())}},window.addEventListener(`message`,this.messageHandler),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}applyFixedAmountFromOrderTemplate(){if(!this.config.paymentRequestCode&&!this.config.paymentOrderCode)return;let{data:e}=this.orchestrator.getConfig();if(e.order_template_id==null&&e.order_id==null||typeof e.amount_cents!=`number`||e.amount_cents<=0)return;let t=zt(e.amount_cents/100,`USD`,`decimal`);this.config.description=e.description,this.config.totalAmount=Bt(t),this.currentAmount=Bt(t)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`)||r.includes(`naka`)||r.includes(`naka_crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...$t,country:{...$t.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:Qt,u=Qt,d=!!this.config.totalAmount,f=Fn(t,l,this.currentAmount,d),p=n?Fn(t,u,this.currentAmount,d):f,m=Fn(t,{...en,country:{...en.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=tn(this.config.i18n?.submitButton),g=i?sn(f):``,_=a?cn(p):``,v=o?ln(p,h):``,y=s?un(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?zt(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=bn(yn({headerHtml:nn({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:Nn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}postMessageToIframe(e){try{this.iframe?.contentWindow?.postMessage(e,this.origin)}catch{try{this.iframe?.contentWindow?.postMessage(e,`*`)}catch{}}}resetForm(){this.postMessageToIframe({type:`payment-form:reset`})}setSubmitLoading(e){this.postMessageToIframe({type:`payment-form:set-submit-loading`,disabled:e})}setToken(e){this.postMessageToIframe({type:`payment-form:set-token`,token:e})}sendAlert(e,t){this.postMessageToIframe({type:`payment-form:alert`,title:e,message:t})}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=Jt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??Bt(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.postMessageToIframe({type:`payment-form:success`,paymentIntent:e});let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=xn.getInstance(),n=this.config.totalAmount??this.currentAmount??Bt(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():`SV`),a={data:{branch_id:this.orchestrator.getConfig()?.data?.branch_id||this.config.branchCode,amount_cents:n,currency:`USD`,description:e.description||this.config.description||`Pago con Cripto`,billing_document_number:e.billingDocumentNumber||``,redirect_url:this.config.redirectUrl,kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,country:i,city:e.city||`San Salvador`,postal_code:e.postalCode||`1101`,address:e.address||`San Salvador`,phone_number:e.phone}}};try{let r=await t.createCharge(a);this.setSubmitLoading(!1),this.postMessageToIframe({type:`payment-form:naka-checkout`,redirectUrl:r.data.redirect_url,chargeId:r.data.charge_id}),this.startNakaPolling(r.data.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert(`¡Error al crear cobro con Cripto!`,`No se pudo conectar con el servicio de pagos NAKA.`),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en NAKA`)}}async handleNakaTerminalFailure(e,t,n){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm(),this.sendAlert(e,t),this.sendFailureEmitter(n,t)}startNakaPolling(e,t,n){this.stopNakaPolling();let r=xn.getInstance(),i=0,a=Date.now();this.nakaPollingInterval=setInterval(async()=>{try{if(Date.now()-a>=6e5){await this.handleNakaTerminalFailure(`¡Tiempo de espera agotado!`,`El tiempo para completar el pago con criptomonedas ha expirado.`,408);return}let o=await r.getChargeStatus(e);i=0;let s=o.data,c=s?.status;if(c===`SUCCESS`||c===`COMPLETED`||c===`PAID`||c===`OVERPAID`){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Cripto (NAKA)`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig().data.name,branch_name:this.orchestrator.getConfig().data.branch_name,card_network:`NAKA_CRYPTO`,card_last_digits:`CRYPTO`,invoice_serie:null}};this.sendSuccess(r);return}if(c===`CANCELED`||c===`CANCELLED`){await this.handleNakaTerminalFailure(`¡Pago cancelado!`,`El pago con criptomonedas fue cancelado.`,400);return}if(c===`EXPIRED`){await this.handleNakaTerminalFailure(`¡Cobro expirado!`,`El tiempo para completar el pago con criptomonedas ha finalizado.`,410);return}if(c===`FAILED`||c===`REJECTED`){await this.handleNakaTerminalFailure(`¡Pago fallido!`,`No se pudo procesar el pago con criptomonedas.`,422);return}if(c===`UNDERPAID`){await this.handleNakaTerminalFailure(`¡Monto insuficiente!`,`El monto pagado en criptomonedas es menor al requerido.`,422);return}if(c===`PENDING`||c===`IN_PROGRESS`||c===`OPEN`)return}catch(e){if(e?.status===422){let t=e?.data?.error||`No fue posible procesar el cobro con criptomonedas. Por favor, intenta con otro método.`;await this.handleNakaTerminalFailure(`¡Pago no disponible!`,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure(`¡Orden no encontrada!`,`El cobro no se encuentra disponible o fue cancelado.`,404);return}if(e?.status===401||e?.status===403){await this.handleNakaTerminalFailure(`¡Sesión expirada!`,`Tu sesión ha expirado. Por favor, intenta de nuevo.`,e.status);return}if(i++,i>=5){await this.handleNakaTerminalFailure(`¡Error de conexión!`,`No fue posible verificar el estado del pago con criptomonedas.`,500);return}}},3e3)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}},e})({});
package/dist/index.js CHANGED
@@ -11403,11 +11403,21 @@ var Bt = class e {
11403
11403
  sendServerValidationErrors(e, t) {
11404
11404
  if (typeof t == "string" || !e) return !1;
11405
11405
  let n = this.buildValidationResults(t);
11406
- for (let t of n) e.postMessage({
11407
- type: "payment-form:validation-result",
11408
- field: t.field,
11409
- error: t.error
11410
- }, this.origin);
11406
+ for (let t of n) try {
11407
+ e.postMessage({
11408
+ type: "payment-form:validation-result",
11409
+ field: t.field,
11410
+ error: t.error
11411
+ }, this.origin);
11412
+ } catch {
11413
+ try {
11414
+ e.postMessage({
11415
+ type: "payment-form:validation-result",
11416
+ field: t.field,
11417
+ error: t.error
11418
+ }, "*");
11419
+ } catch {}
11420
+ }
11411
11421
  return n.length > 0;
11412
11422
  }
11413
11423
  hasEncryptionPayloadErrors(e) {
@@ -11965,71 +11975,28 @@ function yn(e) {
11965
11975
  //#region src/request/naka.ts
11966
11976
  var bn = class e {
11967
11977
  static instance;
11968
- customBaseUrl;
11969
- token = null;
11970
- apiKey = "a2e9d688-686a-482f-a1ae-ab7741b3861d";
11971
- apiSecret = "JNYA8miN6TvEvvflIptPzXOOLp2dWMm3uMQHqVxBssnZRV3X";
11972
- get baseUrl() {
11973
- return this.customBaseUrl ? this.customBaseUrl : typeof window > "u" ? "https://api.staging.gocrypto.com" : `${window.location.pathname.startsWith("/paylink") ? "/paylink" : ""}/naka-api`;
11978
+ request;
11979
+ constructor() {
11980
+ this.request = _t.getInstance();
11974
11981
  }
11975
- constructor() {}
11976
11982
  static getInstance() {
11977
11983
  return e.instance ||= new e(), e.instance;
11978
11984
  }
11979
- setCredentials(e, t, n) {
11980
- this.apiKey = e, this.apiSecret = t, n && (this.customBaseUrl = n), this.token = null;
11981
- }
11982
- async getAuthToken() {
11983
- let e = await fetch(`${this.baseUrl}/api/v2/auth`, {
11984
- method: "POST",
11985
- headers: {
11986
- "Content-Type": "application/json",
11987
- "x-api-key": this.apiKey,
11988
- "x-secret": this.apiSecret
11989
- }
11990
- });
11991
- if (!e.ok) throw Error(`NAKA Auth failed with status ${e.status}: ${e.statusText}`);
11992
- let t = await e.json();
11993
- return this.token = t.access_token || t.token, this.token;
11994
- }
11995
11985
  async createCharge(e) {
11996
- let t = this.token ?? await this.getAuthToken(), n = await fetch(`${this.baseUrl}/api/v3/ecom/payments/charge`, {
11997
- method: "POST",
11998
- headers: {
11999
- "Content-Type": "application/json",
12000
- "access-token": t
12001
- },
12002
- body: JSON.stringify(e)
12003
- });
12004
- if (!n.ok) throw Error(`NAKA Create Charge failed with status ${n.status}: ${n.statusText}`);
12005
- let r = await n.json();
12006
- return {
12007
- charge_id: r.charge_id,
12008
- redirect_url: r.redirect_url
12009
- };
11986
+ let t = await this.request.post("external/online_payments/orders/crypto/charge", e);
11987
+ if (!t.ok) {
11988
+ let e = typeof t.json == "function" ? await t.json().catch(() => null) : null, n = e?.error || e?.message || (typeof e == "object" && e ? JSON.stringify(e) : null) || `Charge creation failed with status ${t.status}`, r = Error(n);
11989
+ throw r.status = t.status, r.data = e, r;
11990
+ }
11991
+ return await t.json();
12010
11992
  }
12011
11993
  async getChargeStatus(e) {
12012
- let t = this.token ?? await this.getAuthToken(), n = await fetch(`${this.baseUrl}/api/v3/ecom/payments/charge/${e}/status/all`, {
12013
- method: "GET",
12014
- headers: {
12015
- "Content-Type": "application/json",
12016
- "access-token": t
12017
- }
12018
- });
12019
- if (!n.ok) throw Error(`NAKA Get Charge Status failed with status ${n.status}: ${n.statusText}`);
12020
- let r = await n.json();
12021
- return Array.isArray(r) ? r : r.items ?? r.data ?? [r];
12022
- }
12023
- async getTransactionDetails(e) {
12024
- let t = this.token ?? await this.getAuthToken(), n = await fetch(`${this.baseUrl}/api/v3/ecom/payments/${e}/details`, {
12025
- method: "GET",
12026
- headers: {
12027
- "Content-Type": "application/json",
12028
- "access-token": t
12029
- }
12030
- });
12031
- if (!n.ok) throw Error(`NAKA Get Transaction Details failed with status ${n.status}: ${n.statusText}`);
12032
- return await n.json();
11994
+ let t = await this.request.get(`external/online_payments/orders/crypto/charge/${e}/status`);
11995
+ if (!t.ok) {
11996
+ let e = typeof t.json == "function" ? await t.json().catch(() => null) : null, n = e?.error || e?.message || (typeof e == "object" && e ? JSON.stringify(e) : null) || `Charge status failed with status ${t.status}`, r = Error(n);
11997
+ throw r.status = t.status, r.data = e, r;
11998
+ }
11999
+ return await t.json();
12033
12000
  }
12034
12001
  }, xn = "<svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n class=\"icon icon-tabler icons-tabler-outline icon-tabler-currency-dollar\"\n>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/>\n <path d=\"M16.7 8a3 3 0 0 0 -2.7 -2h-4a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6h-4a3 3 0 0 1 -2.7 -2\" />\n <path d=\"M12 3v3m0 12v3\" />\n</svg>", Sn = "<svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n class=\"icon icon-tabler icons-tabler-outline icon-tabler-credit-card\"\n>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/>\n <path d=\"M3 8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -8\" />\n <path d=\"M3 10l18 0\" />\n <path d=\"M7 15l.01 0\" />\n <path d=\"M11 15l2 0\" />\n</svg>", Cn = "<svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n class=\"icon icon-tabler icons-tabler-outline icon-tabler-calendar\"\n>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/>\n <path d=\"M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12\" />\n <path d=\"M16 3v4\" />\n <path d=\"M8 3v4\" />\n <path d=\"M4 11h16\" />\n <path d=\"M11 15h1\" />\n <path d=\"M12 15v3\" />\n</svg>", wn = "<svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n class=\"icon icon-tabler icons-tabler-outline icon-tabler-shield-lock\"\n>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/>\n <path d=\"M12 3a12 12 0 0 0 8.5 3a12 12 0 0 1 -8.5 15a12 12 0 0 1 -8.5 -15a12 12 0 0 0 8.5 -3\" />\n <path d=\"M11 11a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\" />\n <path d=\"M12 12l0 2.5\" />\n</svg>", Tn = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"icon icon-tabler icons-tabler-outline icon-tabler-mail\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10\" /><path d=\"M3 7l9 6l9 -6\" /></svg>", En = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"icon icon-tabler icons-tabler-outline icon-tabler-user\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0\" /><path d=\"M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2\" /></svg>", Dn = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"icon icon-tabler icons-tabler-outline icon-tabler-message-circle\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1\" /></svg>", On = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"icon icon-tabler icons-tabler-outline icon-tabler-id\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10\" /><path d=\"M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\" /><path d=\"M15 8l2 0\" /><path d=\"M15 12l2 0\" /><path d=\"M7 16l10 0\" /></svg>", kn = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"icon icon-tabler icons-tabler-outline icon-tabler-device-mobile\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14\" /><path d=\"M11 4h2\" /><path d=\"M12 17v.01\" /></svg>", An = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"icon icon-tabler icons-tabler-outline icon-tabler-map-pin\"><path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\"/><path d=\"M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\" /><path d=\"M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0\" /></svg>", jn = {
12035
12002
  "currency-dollar": xn,
@@ -12150,7 +12117,7 @@ var Nn = class e {
12150
12117
  return;
12151
12118
  }
12152
12119
  if (t.remove(), this.applyFixedAmountFromOrderTemplate(), await this.renderForm(), this.messageHandler = async (e) => {
12153
- if (e.source !== this.iframe?.contentWindow) return;
12120
+ if (e.source && e.source !== this.iframe?.contentWindow && e.source !== window) return;
12154
12121
  let t = e.data;
12155
12122
  if (t?.type) {
12156
12123
  if (t.type === "payment-form:states-loaded" && this.stateContent.setStates(t.states), t.type === "payment-form:sizing" && (this.iframe && (this.iframe.style.height = `${t.height}px`), this.sendSizingEmitter(t.width, t.height)), t.type === "payment-form:validate-amount") {
@@ -12255,6 +12222,35 @@ var Nn = class e {
12255
12222
  forms: { crypto: i }
12256
12223
  }, this.origin);
12257
12224
  }
12225
+ if (t.type === "payment-form:naka-callback") {
12226
+ if (t.status === "CANCELED" || t.status === "CANCELLED") {
12227
+ await this.handleNakaTerminalFailure("¡Pago cancelado!", "El pago con criptomonedas fue cancelado.", 400);
12228
+ return;
12229
+ }
12230
+ if (t.status === "SUCCESS" || t.status === "COMPLETED" || t.status === "PAID" || t.status === "OVERPAID") {
12231
+ this.stopNakaPolling();
12232
+ let e = { data: {
12233
+ id: t.chargeId || "",
12234
+ status: "success",
12235
+ amount_cents: this.config.totalAmount ?? this.currentAmount ?? 0,
12236
+ amount_currency: "USD",
12237
+ response_code: "00",
12238
+ authorization_number: t.chargeId || `NAKA-${Date.now()}`,
12239
+ reference_number: t.orderNumber || t.chargeId || "",
12240
+ billing_document_number: "",
12241
+ description: this.config.description || "Pago con Cripto (NAKA)",
12242
+ date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
12243
+ time: (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0],
12244
+ commerce_name: this.orchestrator.getConfig()?.data?.name || "",
12245
+ branch_name: this.orchestrator.getConfig()?.data?.branch_name || "",
12246
+ card_network: "NAKA_CRYPTO",
12247
+ card_last_digits: "CRYPTO",
12248
+ invoice_serie: null
12249
+ } };
12250
+ this.sendSuccess(e);
12251
+ return;
12252
+ }
12253
+ }
12258
12254
  t.type === "payment-form:return-initial" && (this.stopNakaPolling(), this.iframe &&= (this.iframe.remove(), null), await this.renderForm());
12259
12255
  }
12260
12256
  }, window.addEventListener("message", this.messageHandler), this.config.totalAmount && Number(this.config.totalAmount) > 0) try {
@@ -12350,27 +12346,36 @@ var Nn = class e {
12350
12346
  let e = this.countryContent.getCountriesLoadError();
12351
12347
  e && this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow, { country: [e] });
12352
12348
  }
12349
+ postMessageToIframe(e) {
12350
+ try {
12351
+ this.iframe?.contentWindow?.postMessage(e, this.origin);
12352
+ } catch {
12353
+ try {
12354
+ this.iframe?.contentWindow?.postMessage(e, "*");
12355
+ } catch {}
12356
+ }
12357
+ }
12353
12358
  resetForm() {
12354
- this.iframe?.contentWindow?.postMessage({ type: "payment-form:reset" }, this.origin);
12359
+ this.postMessageToIframe({ type: "payment-form:reset" });
12355
12360
  }
12356
12361
  setSubmitLoading(e) {
12357
- this.iframe?.contentWindow?.postMessage({
12362
+ this.postMessageToIframe({
12358
12363
  type: "payment-form:set-submit-loading",
12359
12364
  disabled: e
12360
- }, this.origin);
12365
+ });
12361
12366
  }
12362
12367
  setToken(e) {
12363
- this.iframe?.contentWindow?.postMessage({
12368
+ this.postMessageToIframe({
12364
12369
  type: "payment-form:set-token",
12365
12370
  token: e
12366
- }, this.origin);
12371
+ });
12367
12372
  }
12368
12373
  sendAlert(e, t) {
12369
- this.iframe?.contentWindow?.postMessage({
12374
+ this.postMessageToIframe({
12370
12375
  type: "payment-form:alert",
12371
12376
  title: e,
12372
12377
  message: t
12373
- }, this.origin);
12378
+ });
12374
12379
  }
12375
12380
  sendFailureEmitter(e, t) {
12376
12381
  for (let n of this.failureListeners) n({
@@ -12442,10 +12447,10 @@ var Nn = class e {
12442
12447
  });
12443
12448
  }
12444
12449
  sendSuccess(e) {
12445
- this.config.totalAmount && (e.data.amount_cents = this.config.totalAmount), this.iframe?.contentWindow?.postMessage({
12450
+ this.config.totalAmount && (e.data.amount_cents = this.config.totalAmount), this.postMessageToIframe({
12446
12451
  type: "payment-form:success",
12447
12452
  paymentIntent: e
12448
- }, this.origin);
12453
+ });
12449
12454
  let { id: t, status: n, amount_cents: r, response_code: i, authorization_number: a, reference_number: o } = e.data, s = {
12450
12455
  id: t,
12451
12456
  status: n,
@@ -12460,43 +12465,51 @@ var Nn = class e {
12460
12465
  this.setSubmitLoading(!0);
12461
12466
  let t = bn.getInstance(), n = this.config.totalAmount ?? this.currentAmount ?? zt(e.amount || "0");
12462
12467
  this.countryContent.getCountries().length === 0 && await this.countryContent.fetchCountries();
12463
- let r = e.country || "", i = this.countryContent.getCountries().find((e) => e.id === r || e.alpha2 === r || e.name === r)?.alpha2 || (r.length === 2 ? r.toUpperCase() : "SV"), a = {
12464
- shop_name: this.orchestrator.getConfig().data.name || "BIZZ Store",
12465
- order_number: `ORD-${Date.now()}`,
12466
- currency_code: "USD",
12467
- amount: n,
12468
- callback_endpoint: "https://bizz.sv/checkout/success",
12469
- webhook_endpoint: "https://bizz.sv/api/webhooks/naka",
12468
+ let r = e.country || "", i = this.countryContent.getCountries().find((e) => e.id === r || e.alpha2 === r || e.name === r)?.alpha2 || (r.length === 2 ? r.toUpperCase() : "SV"), a = { data: {
12469
+ branch_id: this.orchestrator.getConfig()?.data?.branch_id || this.config.branchCode,
12470
+ amount_cents: n,
12471
+ currency: "USD",
12472
+ description: e.description || this.config.description || "Pago con Cripto",
12473
+ billing_document_number: e.billingDocumentNumber || "",
12474
+ redirect_url: this.config.redirectUrl,
12470
12475
  kyc: {
12471
12476
  email: e.email || "",
12472
12477
  first_name: e.firstName || "",
12473
12478
  last_name: e.lastName || "",
12474
- nationality: i,
12475
12479
  country: i,
12476
12480
  city: e.city || "San Salvador",
12477
- zip_code: e.postalCode || "1101",
12481
+ postal_code: e.postalCode || "1101",
12478
12482
  address: e.address || "San Salvador",
12479
12483
  phone_number: e.phone
12480
12484
  }
12481
- };
12485
+ } };
12482
12486
  try {
12483
12487
  let r = await t.createCharge(a);
12484
- this.setSubmitLoading(!1), this.iframe?.contentWindow?.postMessage({
12488
+ this.setSubmitLoading(!1), this.postMessageToIframe({
12485
12489
  type: "payment-form:naka-checkout",
12486
- redirectUrl: r.redirect_url,
12487
- chargeId: r.charge_id
12488
- }, this.origin), this.startNakaPolling(r.charge_id, n, e);
12490
+ redirectUrl: r.data.redirect_url,
12491
+ chargeId: r.data.charge_id
12492
+ }), this.startNakaPolling(r.data.charge_id, n, e);
12489
12493
  } catch (e) {
12490
12494
  this.setSubmitLoading(!1), this.sendAlert("¡Error al crear cobro con Cripto!", "No se pudo conectar con el servicio de pagos NAKA."), this.sendFailureEmitter(500, e instanceof Error ? e.message : "Error en NAKA");
12491
12495
  }
12492
12496
  }
12497
+ async handleNakaTerminalFailure(e, t, n) {
12498
+ this.stopNakaPolling(), this.iframe &&= (this.iframe.remove(), null), await this.renderForm(), this.sendAlert(e, t), this.sendFailureEmitter(n, t);
12499
+ }
12493
12500
  startNakaPolling(e, t, n) {
12494
12501
  this.stopNakaPolling();
12495
- let r = bn.getInstance();
12502
+ let r = bn.getInstance(), i = 0, a = Date.now();
12496
12503
  this.nakaPollingInterval = setInterval(async () => {
12497
12504
  try {
12498
- let i = (await r.getChargeStatus(e)).find((e) => e.status === "SUCCESS" || e.status === "OVERPAID");
12499
- if (i) {
12505
+ if (Date.now() - a >= 6e5) {
12506
+ await this.handleNakaTerminalFailure("¡Tiempo de espera agotado!", "El tiempo para completar el pago con criptomonedas ha expirado.", 408);
12507
+ return;
12508
+ }
12509
+ let o = await r.getChargeStatus(e);
12510
+ i = 0;
12511
+ let s = o.data, c = s?.status;
12512
+ if (c === "SUCCESS" || c === "COMPLETED" || c === "PAID" || c === "OVERPAID") {
12500
12513
  this.stopNakaPolling();
12501
12514
  let r = { data: {
12502
12515
  id: e,
@@ -12504,8 +12517,8 @@ var Nn = class e {
12504
12517
  amount_cents: t,
12505
12518
  amount_currency: "USD",
12506
12519
  response_code: "00",
12507
- authorization_number: i.transaction_id || `NAKA-${Date.now()}`,
12508
- reference_number: i.order_number || e,
12520
+ authorization_number: s.authorization_number || s.transaction_id || `NAKA-${Date.now()}`,
12521
+ reference_number: s.reference_number || s.order_number || e,
12509
12522
  billing_document_number: n.billingDocumentNumber || "",
12510
12523
  description: n.description || this.config.description || "Pago con Cripto (NAKA)",
12511
12524
  date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
@@ -12517,8 +12530,44 @@ var Nn = class e {
12517
12530
  invoice_serie: null
12518
12531
  } };
12519
12532
  this.sendSuccess(r);
12533
+ return;
12520
12534
  }
12521
- } catch {}
12535
+ if (c === "CANCELED" || c === "CANCELLED") {
12536
+ await this.handleNakaTerminalFailure("¡Pago cancelado!", "El pago con criptomonedas fue cancelado.", 400);
12537
+ return;
12538
+ }
12539
+ if (c === "EXPIRED") {
12540
+ await this.handleNakaTerminalFailure("¡Cobro expirado!", "El tiempo para completar el pago con criptomonedas ha finalizado.", 410);
12541
+ return;
12542
+ }
12543
+ if (c === "FAILED" || c === "REJECTED") {
12544
+ await this.handleNakaTerminalFailure("¡Pago fallido!", "No se pudo procesar el pago con criptomonedas.", 422);
12545
+ return;
12546
+ }
12547
+ if (c === "UNDERPAID") {
12548
+ await this.handleNakaTerminalFailure("¡Monto insuficiente!", "El monto pagado en criptomonedas es menor al requerido.", 422);
12549
+ return;
12550
+ }
12551
+ if (c === "PENDING" || c === "IN_PROGRESS" || c === "OPEN") return;
12552
+ } catch (e) {
12553
+ if (e?.status === 422) {
12554
+ let t = e?.data?.error || "No fue posible procesar el cobro con criptomonedas. Por favor, intenta con otro método.";
12555
+ await this.handleNakaTerminalFailure("¡Pago no disponible!", t, 422);
12556
+ return;
12557
+ }
12558
+ if (e?.status === 404) {
12559
+ await this.handleNakaTerminalFailure("¡Orden no encontrada!", "El cobro no se encuentra disponible o fue cancelado.", 404);
12560
+ return;
12561
+ }
12562
+ if (e?.status === 401 || e?.status === 403) {
12563
+ await this.handleNakaTerminalFailure("¡Sesión expirada!", "Tu sesión ha expirado. Por favor, intenta de nuevo.", e.status);
12564
+ return;
12565
+ }
12566
+ if (i++, i >= 5) {
12567
+ await this.handleNakaTerminalFailure("¡Error de conexión!", "No fue posible verificar el estado del pago con criptomonedas.", 500);
12568
+ return;
12569
+ }
12570
+ }
12522
12571
  }, 3e3);
12523
12572
  }
12524
12573
  stopNakaPolling() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bizzsv/bizz-payment",
3
- "version": "1.4.2-dev",
3
+ "version": "1.5.0-dev",
4
4
  "description": "The Biz Payment SDK is designed to provide a secure, isolated form for payment integration.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",