@payconductor/react 1.0.5 → 1.0.6
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.js +3 -3
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +74 -74
- package/dist/index.es.js.map +1 -1
- package/dist/payconductor/iframe/types.d.ts +1 -3
- package/dist/payconductor/three-ds/handler.d.ts +1 -1
- package/dist/payconductor/three-ds/types.d.ts +2 -2
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var me=Object.defineProperty;var he=(e,n,t)=>n in e?me(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var p=(e,n,t)=>he(e,typeof n!="symbol"?n+"":n,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const R=require("react/jsx-runtime"),A=require("react"),H="https://iframe.payconductor.ai/v1",Y="http://localhost:5175/v1",fe=3e5,ye="600px";var G=(e=>(e.Pix="Pix",e.CreditCard="CreditCard",e.DebitCard="DebitCard",e.BankSlip="BankSlip",e.Crypto="Crypto",e.ApplePay="ApplePay",e.NuPay="NuPay",e.PicPay="PicPay",e.AmazonPay="AmazonPay",e.SepaDebit="SepaDebit",e.GooglePay="GooglePay",e))(G||{}),j=(e=>(e.Grid="grid",e.Vertical="vertical",e.Horizontal="horizontal",e))(j||{}),V=(e=>(e.Succeeded="succeeded",e.Pending="pending",e.Failed="failed",e))(V||{}),q=(e=>(e.ThreeDsAwaitingChallenge="ThreeDsAwaitingChallenge",e))(q||{}),$=(e=>(e.Authenticated="Authenticated",e.NotAuthenticated="NotAuthenticated",e.NeedChallenge="NeedChallenge",e))($||{}),W=(e=>(e.Pending="Pending",e.Authenticated="Authenticated",e.Failed="Failed",e.NotEnrolled="NotEnrolled",e))(W||{}),B=(e=>(e.Cpf="Cpf",e.Cnpj="Cnpj",e))(B||{}),M=(e=>(e.Asaas="Asaas",e.Sandbox="Sandbox",e.SandboxSplit="SandboxSplit",e.MercadoPago="MercadoPago",e.NuPay="NuPay",e.PicPay="PicPay",e.Woovi="Woovi",e.EfiBank="EfiBank",e.BrasPag="BrasPag",e.PagarMe="PagarMe",e.BancoDoBrasil="BancoDoBrasil",e.PagSeguro="PagSeguro",e.Ebanx="Ebanx",e.OnlyUp="OnlyUp",e.Barte="Barte",e.BarteSplit="BarteSplit",e.PagSmileA55="PagSmileA55",e.Avantti="Avantti",e.MonsterGateway="MonsterGateway",e.SAC="SAC",e))(M||{}),J=(e=>(e.Visa="Visa",e.Mastercard="Mastercard",e.AmericanExpress="AmericanExpress",e.DinersClub="DinersClub",e.Discover="Discover",e.JCB="JCB",e.UnionPay="UnionPay",e.Maestro="Maestro",e.Mir="Mir",e.Elo="Elo",e.Hiper="Hiper",e.Hipercard="Hipercard",e.Verve="Verve",e.Unknown="Unknown",e))(J||{}),D=(e=>(e.Production="Production",e.Sandbox="Sandbox",e))(D||{}),X=(e=>(e.USD="USD",e.EUR="EUR",e.BRL="BRL",e.ARS="ARS",e.CAD="CAD",e.COP="COP",e.GBP="GBP",e.JPY="JPY",e.MXN="MXN",e.MZN="MZN",e.CNY="CNY",e.SAR="SAR",e.ETH="ETH",e.BNB="BNB",e.BTC="BTC",e.USDT="USDT",e.USDC="USDC",e.DOGE="DOGE",e.SOL="SOL",e))(X||{}),Z=(e=>(e.Android="android",e.IOS="ios",e.Web="web",e))(Z||{}),Q=(e=>(e.Padding="padding",e.Radius="radius",e.Color="color",e.Background="background",e.Shadow="shadow",e))(Q||{}),I=(e=>(e.Init="Init",e.Config="Config",e.Update="Update",e.ConfirmPayment="ConfirmPayment",e.Validate="Validate",e.Reset="Reset",e))(I||{}),T=(e=>(e.Ready="Ready",e.Error="Error",e.PaymentComplete="PaymentComplete",e.PaymentFailed="PaymentFailed",e.PaymentPending="PaymentPending",e.ValidationError="ValidationError",e.PaymentMethodSelected="PaymentMethodSelected",e.Resize="Resize",e.ThreeDSChallenge="ThreeDSChallenge",e.ThreeDSComplete="ThreeDSComplete",e.ThreeDSFailed="ThreeDSFailed",e))(T||{}),ee=(e=>(e.InvalidClient="InvalidClient",e.InvalidToken="InvalidToken",e.NetworkError="NetworkError",e.IframeNotReady="IframeNotReady",e.PaymentDeclined="PaymentDeclined",e.ValidationError="ValidationError",e.Timeout="Timeout",e))(ee||{});const Ee={primaryColor:"#0066ff",secondaryColor:"#5a6b7c",backgroundColor:"transparent",surfaceColor:"#f8fafc",textColor:"#0f172a",textSecondaryColor:"#64748b",errorColor:"#ef4444",successColor:"#22c55e",warningColor:"#f59e0b",borderColor:"#e2e8f0",disabledColor:"#cbd5e1",fontFamily:'"Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,bold:600},lineHeight:"1.5",spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px"},borderRadius:"8px",borderWidth:"1px",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",boxShadowHover:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",inputBackground:"#ffffff",inputBorderColor:"#cbd5e1",inputBorderRadius:"8px",inputHeight:"44px",inputPadding:"12px 16px",buttonHeight:"48px",buttonPadding:"16px 24px",buttonBorderRadius:"8px",transitionDuration:"0.2s",transitionTimingFunction:"ease"},we=typeof window<"u"&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1")&&!window.location.search.includes("production"),te=we?Y:H,ne=[Y,H],U=ye,ae=fe,g={INIT:I.Init,CONFIG:I.Config,UPDATE:I.Update,CONFIRM_PAYMENT:I.ConfirmPayment,VALIDATE:I.Validate,RESET:I.Reset,READY:T.Ready,ERROR:T.Error,PAYMENT_COMPLETE:T.PaymentComplete,PAYMENT_FAILED:T.PaymentFailed,PAYMENT_PENDING:T.PaymentPending,VALIDATION_ERROR:T.ValidationError,PAYMENT_METHOD_SELECTED:T.PaymentMethodSelected,RESIZE:T.Resize},ge={INVALID_CLIENT:"InvalidClient",INVALID_TOKEN:"InvalidToken",NETWORK_ERROR:"NetworkError",IFRAME_NOT_READY:"IframeNotReady",PAYMENT_DECLINED:"PaymentDeclined",VALIDATION_ERROR:"ValidationError",TIMEOUT:"Timeout"},F="payconductor-skeleton-style",re=`
|
|
2
2
|
@keyframes payconductor-shimmer {
|
|
3
3
|
0% { background-position: -200% 0; }
|
|
4
4
|
100% { background-position: 200% 0; }
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
border-radius: 4px;
|
|
11
11
|
width: 100%;
|
|
12
12
|
}
|
|
13
|
-
`;function re(e){const n=new URLSearchParams({publicKey:e.publicKey});return`${te}?${n.toString()}`}function oe(){return crypto.randomUUID()}function se(e,n){return n.some(t=>{try{return new URL(t).origin===e}catch{return t===e}})}function K(){return new Map}function _(e,n,t,a){return new Promise((i,o)=>{if(!e||!("contentWindow"in e)){o(new Error("Iframe not defined"));return}if(!(e!=null&&e.contentWindow)){o(new Error("Iframe not ready"));return}if(!n){o(new Error("Pending requests not initialized"));return}const d=oe();n.set(d,{resolve:i,reject:o}),e.contentWindow.postMessage({type:t,data:a,requestId:d},"*"),setTimeout(()=>{n!=null&&n.has(d)&&(n.delete(d),o(new Error("Request timeout")))},ae)})}function Se(e,n,t){return _(e,n,g.CONFIRM_PAYMENT,t)}async function Pe(e,n,t){return await Se(e,n,{orderId:t.orderId})}function Ce(e,n,t){return _(e,n,g.VALIDATE,t)}function pe(e,n){return _(e,n,g.RESET)}function be(e,n,t){return _(e,n,g.CONFIG,t)}function Te(e,n,t){return _(e,n,g.INIT,t)}function ve(e,n,t,a,i,o,d,s,r,l,S,E){const m=e.data,{requestId:y,type:h,data:w,error:p}=m;if(h===g.READY){if(a==null||a(),y&&(n!=null&&n.has(y))){const{resolve:v}=n.get(y);n.delete(y),v(w)}return}if(se(e.origin,ne)){if(y&&n&&n.has(y)){const{resolve:v,reject:x}=n.get(y);n.delete(y),p?x(new Error(String(p.message))):v(w);return}if(h===g.ERROR){t((p==null?void 0:p.message)||"Unknown error"),i==null||i(new Error(String(p==null?void 0:p.message)));return}if(h===g.PAYMENT_COMPLETE){w&&typeof w=="object"&&"status"in w&&(o==null||o(w));return}if(h===g.PAYMENT_FAILED){w&&typeof w=="object"&&"status"in w&&(d==null||d(w));return}if(h===g.PAYMENT_PENDING){w&&typeof w=="object"&&"status"in w&&(s==null||s(w));return}if(h===g.PAYMENT_METHOD_SELECTED){w&&typeof w=="object"&&"paymentMethod"in w&&(r==null||r(w.paymentMethod));return}if(h!==g.RESIZE){if(h===T.ThreeDSChallenge){l==null||l();return}if(h===T.ThreeDSComplete){S==null||S();return}if(h===T.ThreeDSFailed){E==null||E();return}}}}function de(e){const[n,t]=A.useState(()=>!1),[a,i]=A.useState(()=>null),[o,d]=A.useState(()=>""),[s,r]=A.useState(()=>null);return A.useEffect(()=>{const l=(...u)=>{e.debug&&console.log("[PayConductor]",...u)},S=re({publicKey:e.publicKey});d(S),t(!0);const E=K();let m=!1;l("init",e.publicKey),l("iframeUrl",S);const y=()=>{var P,c;const u=(c=(P=window.PayConductor)==null?void 0:P.frame)==null?void 0:c.iframe;if(u){if(u instanceof HTMLIFrameElement)return u;if(typeof u=="object"&&u!==null){const f=u;if("current"in f&&f.current instanceof HTMLIFrameElement)return f.current;if("value"in f&&f.value instanceof HTMLIFrameElement)return f.value}return u}return document.querySelector(".payconductor-element iframe")??void 0},h={get iframe(){return document.querySelector(".payconductor-element iframe")??null},set iframe(u){},iframeUrl:S,error:null},w={publicKey:e.publicKey,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod},p={confirmPayment:u=>{var c;l("→ CONFIRM_PAYMENT",{orderId:u.orderId});const P=y();return P!=null&&P.contentWindow&&P.contentWindow.postMessage({type:g.CONFIG,data:{publicKey:e.publicKey,orderId:u.orderId,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig}},"*"),w.orderId=u.orderId,(c=window.PayConductor)!=null&&c.config&&(window.PayConductor.config.orderId=u.orderId),Pe(P,E,u)},validate:u=>(l("→ VALIDATE",u),Ce(y(),E,u)),reset:()=>(l("→ RESET"),pe(y(),E)),getSelectedPaymentMethod:()=>s};window.PayConductor={frame:h,config:w,api:p,selectedPaymentMethod:s},l("registered"),window.dispatchEvent(new CustomEvent("payconductor:registered",{detail:window.PayConductor}));const v=async()=>{if(!m){const u=y();if(!u){l("→ CONFIG skipped: iframe not found");return}m=!0,l("→ CONFIG",{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons}),be(u,E,{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig})}},x=u=>{var P;(P=u.data)!=null&&P.type&&l("←",u.data.type,u.data.data??""),ve(u,E,c=>{var f;i(c),h.error=c,(f=window.PayConductor)!=null&&f.frame&&(window.PayConductor.frame.error=c)},()=>{var c;(c=e.onReady)==null||c.call(e),v()},c=>{var f;(f=e.onError)==null||f.call(e,c)},c=>{var f;(f=e.onPaymentComplete)==null||f.call(e,c)},c=>{var f;(f=e.onPaymentFailed)==null||f.call(e,c)},c=>{var f;(f=e.onPaymentPending)==null||f.call(e,c)},c=>{var f;r(c),window.PayConductor&&(window.PayConductor.selectedPaymentMethod=c),(f=e.onPaymentMethodSelected)==null||f.call(e,c)},()=>{var c;(c=e.onThreeDSChallenge)==null||c.call(e)},()=>{var c;(c=e.onThreeDSComplete)==null||c.call(e)},()=>{var c;(c=e.onThreeDSFailed)==null||c.call(e)})};window.addEventListener("message",x);const ue=()=>{var P,c,f;const u=y();if(!u)return!1;try{if((((P=u.contentDocument)==null?void 0:P.readyState)??((f=(c=u.contentWindow)==null?void 0:c.document)==null?void 0:f.readyState))==="complete")return v(),!0}catch{}return!1},z=()=>{if(ue())return;const u=y();if(u){u.addEventListener("load",()=>v(),{once:!0});return}setTimeout(z,50)};z()},[]),R.jsx("div",{className:"payconductor",id:"payconductor",style:{display:"contents"},children:e.children})}function Ae(e){const n=A.useRef(null),[t,a]=A.useState(()=>""),[i,o]=A.useState(()=>!1),[d,s]=A.useState(()=>"");return A.useEffect(()=>{if(typeof document<"u"&&!document.getElementById(F)){const m=document.createElement("style");m.id=F,m.textContent=ie,document.head.appendChild(m)}const r=m=>{m!=null&&m.frame&&(a(m.frame.iframeUrl||""),o(!0),console.log("init",{PayConductor:window.PayConductor}))},l=typeof window<"u"?window.PayConductor:null;if(l)r(l);else{const m=y=>{r(y.detail),window.removeEventListener("payconductor:registered",m)};window.addEventListener("payconductor:registered",m)}let S=!1;const E=m=>{var y,h,w,p;if(((y=m.data)==null?void 0:y.type)===g.RESIZE&&((w=(h=m.data)==null?void 0:h.data)!=null&&w.height)&&s(m.data.data.height+"px"),((p=m.data)==null?void 0:p.type)===g.READY&&e.height&&!S){S=!0;const v=document.querySelector(".payconductor-element iframe");v!=null&&v.contentWindow&&v.contentWindow.postMessage({type:g.CONFIG,data:{height:e.height},requestId:"element-height"},"*")}};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]),R.jsxs("div",{className:"payconductor-element",style:{width:"100%"},children:[i?null:R.jsx("div",{className:"payconductor-skeleton",style:{height:e.height||U}}),i&&t?R.jsx("iframe",{allow:"payment",title:"PayConductor",ref:n,src:t,style:{width:"100%",height:e.height||d||U,border:"none"}}):null]})}function Me(e){const[n,t]=A.useState(()=>!1);return A.useEffect(()=>{const a=()=>{t(!0)},i=()=>{t(!1)};return window.addEventListener("payconductor:3ds:show",a),window.addEventListener("payconductor:3ds:hide",i),typeof window<"u"&&(window.PayConductor3DS={container:()=>document.getElementById("payconductor-3ds-container"),show:a,hide:i},window.dispatchEvent(new CustomEvent("payconductor:3ds:registered"))),()=>{window.removeEventListener("payconductor:3ds:show",a),window.removeEventListener("payconductor:3ds:hide",i),window.PayConductor3DS=null}},[]),R.jsx("div",{className:"payconductor-three-ds",id:"payconductor-3ds-container",style:{width:"100%",display:n?"block":"none",minHeight:n?e.height||"600px":"0"}})}function Ie(){const e=typeof window<"u"?window.PayConductor:null,n=e!=null&&e.config?{publicKey:e.config.publicKey,orderId:e.config.orderId,theme:e.config.theme,locale:e.config.locale}:{},t=e!=null&&e.frame?{iframe:e.frame.iframe,error:e.frame.error}:{iframe:null,error:null};return{...n,...t}}function O(e){var n;if((n=e==null?void 0:e.frame)!=null&&n.iframe){const t=e.frame.iframe;if(t instanceof HTMLIFrameElement)return t;if(t&&typeof t=="object"){if("current"in t){const a=t.current;if(a instanceof HTMLIFrameElement)return a}if("value"in t){const a=t.value;if(a instanceof HTMLIFrameElement)return a}}}return document.querySelector(".payconductor-element iframe")??null}function De(){const e=()=>typeof window<"u"?window.PayConductor:null,n=(t,a)=>{const i=e();if(!i)return;const o=O(i);o!=null&&o.contentWindow&&o.contentWindow.postMessage({type:t,data:a},"*")};return{init:async t=>{const a=O(e()),i=K();return Te(a||void 0,i,t)},confirmPayment:async t=>{if(!t.orderId)throw new Error("Order ID is required");const a=e();if(!(a!=null&&a.api))throw new Error("PayConductor not initialized");return a.api.confirmPayment(t)},validate:t=>{const a=e();return a?a.api.validate(t):Promise.resolve(!1)},reset:()=>{const t=e();return t?t.api.reset():Promise.resolve()},getSelectedPaymentMethod:()=>{var t;return((t=e())==null?void 0:t.selectedPaymentMethod)??null},updateConfig:t=>{var i;const a=(i=e())==null?void 0:i.config;n(g.CONFIG,{publicKey:a==null?void 0:a.publicKey,orderId:a==null?void 0:a.orderId,theme:t.theme??(a==null?void 0:a.theme),locale:t.locale??(a==null?void 0:a.locale),paymentMethods:t.paymentMethods??(a==null?void 0:a.paymentMethods)})},updateOrderId:t=>{var i;const a=(i=e())==null?void 0:i.config;n(g.CONFIG,{publicKey:a==null?void 0:a.publicKey,orderId:t,theme:a==null?void 0:a.theme,locale:a==null?void 0:a.locale,paymentMethods:a==null?void 0:a.paymentMethods})},update:t=>{n(g.UPDATE,t)},submit:async()=>{const t=O(e()),a=K();try{return await _(t||void 0,a,g.CONFIRM_PAYMENT,{}),{paymentMethod:void 0}}catch(i){return{error:{message:i instanceof Error?i.message:"Payment failed",code:"payment_error",type:"payment_error"}}}}}}var C=(e=>(e.Success="Success",e.Failed="Failed",e.Timeout="Timeout",e))(C||{});class k{constructor(n,t){b(this,"overlay",null);b(this,"modalContent",null);this.data=n,this.options=t}fail(n){var a,i;const t=new Error(n);return(i=(a=this.options).onError)==null||i.call(a,t),{status:"Failed",error:t}}showModal(){return this.injectStyles(),this.overlay=document.createElement("div"),this.overlay.id="payconductor-3ds-overlay",this.modalContent=document.createElement("div"),this.modalContent.id="payconductor-3ds-modal",this.overlay.appendChild(this.modalContent),document.body.appendChild(this.overlay),this.modalContent}closeModal(){this.overlay&&(this.overlay.remove(),this.overlay=null,this.modalContent=null)}resolveContainer(){return this.modalContent??this.showModal()}injectStyles(){if(document.getElementById("payconductor-3ds-styles"))return;const n=document.createElement("style");n.id="payconductor-3ds-styles",n.textContent=`
|
|
13
|
+
`;function ie(e){const n=new URLSearchParams({publicKey:e.publicKey});return`${te}?${n.toString()}`}function oe(){return crypto.randomUUID()}function se(e,n){return n.some(t=>{try{return new URL(t).origin===e}catch{return t===e}})}function K(){return new Map}function _(e,n,t,a){return new Promise((r,o)=>{if(!e||!("contentWindow"in e)){o(new Error("Iframe not defined"));return}if(!(e!=null&&e.contentWindow)){o(new Error("Iframe not ready"));return}if(!n){o(new Error("Pending requests not initialized"));return}const d=oe();n.set(d,{resolve:r,reject:o}),e.contentWindow.postMessage({type:t,data:a,requestId:d},"*"),setTimeout(()=>{n!=null&&n.has(d)&&(n.delete(d),o(new Error("Request timeout")))},ae)})}function Se(e,n,t){return _(e,n,g.CONFIRM_PAYMENT,t)}async function Pe(e,n,t){return await Se(e,n,{orderId:t.orderId})}function Ce(e,n,t){return _(e,n,g.VALIDATE,t)}function be(e,n){return _(e,n,g.RESET)}function pe(e,n,t){return _(e,n,g.CONFIG,t)}function Te(e,n,t){return _(e,n,g.INIT,t)}function ve(e,n,t,a,r,o,d,s,i,l,S,E){const h=e.data,{requestId:y,type:m,data:w,error:b}=h;if(m===g.READY){if(a==null||a(),y&&(n!=null&&n.has(y))){const{resolve:v}=n.get(y);n.delete(y),v(w)}return}if(se(e.origin,ne)){if(y&&n&&n.has(y)){const{resolve:v,reject:x}=n.get(y);n.delete(y),b?x(new Error(String(b.message))):v(w);return}if(m===g.ERROR){t((b==null?void 0:b.message)||"Unknown error"),r==null||r(new Error(String(b==null?void 0:b.message)));return}if(m===g.PAYMENT_COMPLETE){w&&typeof w=="object"&&"status"in w&&(o==null||o(w));return}if(m===g.PAYMENT_FAILED){w&&typeof w=="object"&&"status"in w&&(d==null||d(w));return}if(m===g.PAYMENT_PENDING){w&&typeof w=="object"&&"status"in w&&(s==null||s(w));return}if(m===g.PAYMENT_METHOD_SELECTED){w&&typeof w=="object"&&"paymentMethod"in w&&(i==null||i(w.paymentMethod));return}if(m!==g.RESIZE){if(m===T.ThreeDSChallenge){l==null||l();return}if(m===T.ThreeDSComplete){S==null||S();return}if(m===T.ThreeDSFailed){E==null||E();return}}}}function de(e){const[n,t]=A.useState(()=>!1),[a,r]=A.useState(()=>null),[o,d]=A.useState(()=>""),[s,i]=A.useState(()=>null);return A.useEffect(()=>{const l=(...u)=>{e.debug&&console.log("[PayConductor]",...u)},S=ie({publicKey:e.publicKey});d(S),t(!0);const E=K();let h=!1;l("init",e.publicKey),l("iframeUrl",S);const y=()=>{var P,c;const u=(c=(P=window.PayConductor)==null?void 0:P.frame)==null?void 0:c.iframe;if(u){if(u instanceof HTMLIFrameElement)return u;if(typeof u=="object"&&u!==null){const f=u;if("current"in f&&f.current instanceof HTMLIFrameElement)return f.current;if("value"in f&&f.value instanceof HTMLIFrameElement)return f.value}return u}return document.querySelector(".payconductor-element iframe")??void 0},m={get iframe(){return document.querySelector(".payconductor-element iframe")??null},set iframe(u){},iframeUrl:S,error:null},w={publicKey:e.publicKey,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod},b={confirmPayment:u=>{var c;l("→ CONFIRM_PAYMENT",{orderId:u.orderId});const P=y();return P!=null&&P.contentWindow&&P.contentWindow.postMessage({type:g.CONFIG,data:{publicKey:e.publicKey,orderId:u.orderId,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig}},"*"),w.orderId=u.orderId,(c=window.PayConductor)!=null&&c.config&&(window.PayConductor.config.orderId=u.orderId),Pe(P,E,u)},validate:u=>(l("→ VALIDATE",u),Ce(y(),E,u)),reset:()=>(l("→ RESET"),be(y(),E)),getSelectedPaymentMethod:()=>s};window.PayConductor={frame:m,config:w,api:b,selectedPaymentMethod:s},l("registered"),window.dispatchEvent(new CustomEvent("payconductor:registered",{detail:window.PayConductor}));const v=async()=>{if(!h){const u=y();if(!u){l("→ CONFIG skipped: iframe not found");return}h=!0,l("→ CONFIG",{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons}),pe(u,E,{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig})}},x=u=>{var P;(P=u.data)!=null&&P.type&&l("←",u.data.type,u.data.data??""),ve(u,E,c=>{var f;r(c),m.error=c,(f=window.PayConductor)!=null&&f.frame&&(window.PayConductor.frame.error=c)},()=>{var c;(c=e.onReady)==null||c.call(e),v()},c=>{var f;(f=e.onError)==null||f.call(e,c)},c=>{var f;(f=e.onPaymentComplete)==null||f.call(e,c)},c=>{var f;(f=e.onPaymentFailed)==null||f.call(e,c)},c=>{var f;(f=e.onPaymentPending)==null||f.call(e,c)},c=>{var f;i(c),window.PayConductor&&(window.PayConductor.selectedPaymentMethod=c),(f=e.onPaymentMethodSelected)==null||f.call(e,c)},()=>{var c;(c=e.onThreeDSChallenge)==null||c.call(e)},()=>{var c;(c=e.onThreeDSComplete)==null||c.call(e)},()=>{var c;(c=e.onThreeDSFailed)==null||c.call(e)})};window.addEventListener("message",x);const ue=()=>{var P,c,f;const u=y();if(!u)return!1;try{if((((P=u.contentDocument)==null?void 0:P.readyState)??((f=(c=u.contentWindow)==null?void 0:c.document)==null?void 0:f.readyState))==="complete")return v(),!0}catch{}return!1},z=()=>{if(ue())return;const u=y();if(u){u.addEventListener("load",()=>v(),{once:!0});return}setTimeout(z,50)};z()},[]),R.jsx("div",{className:"payconductor",id:"payconductor",style:{display:"contents"},children:e.children})}function Ae(e){const n=A.useRef(null),[t,a]=A.useState(()=>""),[r,o]=A.useState(()=>!1),[d,s]=A.useState(()=>"");return A.useEffect(()=>{if(typeof document<"u"&&!document.getElementById(F)){const h=document.createElement("style");h.id=F,h.textContent=re,document.head.appendChild(h)}const i=h=>{h!=null&&h.frame&&(a(h.frame.iframeUrl||""),o(!0),console.log("init",{PayConductor:window.PayConductor}))},l=typeof window<"u"?window.PayConductor:null;if(l)i(l);else{const h=y=>{i(y.detail),window.removeEventListener("payconductor:registered",h)};window.addEventListener("payconductor:registered",h)}let S=!1;const E=h=>{var y,m,w,b;if(((y=h.data)==null?void 0:y.type)===g.RESIZE&&((w=(m=h.data)==null?void 0:m.data)!=null&&w.height)&&s(h.data.data.height+"px"),((b=h.data)==null?void 0:b.type)===g.READY&&e.height&&!S){S=!0;const v=document.querySelector(".payconductor-element iframe");v!=null&&v.contentWindow&&v.contentWindow.postMessage({type:g.CONFIG,data:{height:e.height},requestId:"element-height"},"*")}};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]),R.jsxs("div",{className:"payconductor-element",style:{width:"100%"},children:[r?null:R.jsx("div",{className:"payconductor-skeleton",style:{height:e.height||U}}),r&&t?R.jsx("iframe",{allow:"payment",title:"PayConductor",ref:n,src:t,style:{width:"100%",height:e.height||d||U,border:"none"}}):null]})}function Ie(e){const[n,t]=A.useState(()=>!1);return A.useEffect(()=>{const a=()=>{t(!0)},r=()=>{t(!1)};return window.addEventListener("payconductor:3ds:show",a),window.addEventListener("payconductor:3ds:hide",r),typeof window<"u"&&(window.PayConductor3DS={container:()=>document.getElementById("payconductor-3ds-container"),show:a,hide:r},window.dispatchEvent(new CustomEvent("payconductor:3ds:registered"))),()=>{window.removeEventListener("payconductor:3ds:show",a),window.removeEventListener("payconductor:3ds:hide",r),window.PayConductor3DS=null}},[]),R.jsx("div",{className:"payconductor-three-ds",id:"payconductor-3ds-container",style:{width:"100%",display:n?"block":"none",minHeight:n?e.height||"600px":"0"}})}function Me(){const e=typeof window<"u"?window.PayConductor:null,n=e!=null&&e.config?{publicKey:e.config.publicKey,orderId:e.config.orderId,theme:e.config.theme,locale:e.config.locale}:{},t=e!=null&&e.frame?{iframe:e.frame.iframe,error:e.frame.error}:{iframe:null,error:null};return{...n,...t}}function O(e){var n;if((n=e==null?void 0:e.frame)!=null&&n.iframe){const t=e.frame.iframe;if(t instanceof HTMLIFrameElement)return t;if(t&&typeof t=="object"){if("current"in t){const a=t.current;if(a instanceof HTMLIFrameElement)return a}if("value"in t){const a=t.value;if(a instanceof HTMLIFrameElement)return a}}}return document.querySelector(".payconductor-element iframe")??null}function De(){const e=()=>typeof window<"u"?window.PayConductor:null,n=(t,a)=>{const r=e();if(!r)return;const o=O(r);o!=null&&o.contentWindow&&o.contentWindow.postMessage({type:t,data:a},"*")};return{init:async t=>{const a=O(e()),r=K();return Te(a||void 0,r,t)},confirmPayment:async t=>{if(!t.orderId)throw new Error("Order ID is required");const a=e();if(!(a!=null&&a.api))throw new Error("PayConductor not initialized");return a.api.confirmPayment(t)},validate:t=>{const a=e();return a?a.api.validate(t):Promise.resolve(!1)},reset:()=>{const t=e();return t?t.api.reset():Promise.resolve()},getSelectedPaymentMethod:()=>{var t;return((t=e())==null?void 0:t.selectedPaymentMethod)??null},updateConfig:t=>{var r;const a=(r=e())==null?void 0:r.config;n(g.CONFIG,{publicKey:a==null?void 0:a.publicKey,orderId:a==null?void 0:a.orderId,theme:t.theme??(a==null?void 0:a.theme),locale:t.locale??(a==null?void 0:a.locale),paymentMethods:t.paymentMethods??(a==null?void 0:a.paymentMethods)})},updateOrderId:t=>{var r;const a=(r=e())==null?void 0:r.config;n(g.CONFIG,{publicKey:a==null?void 0:a.publicKey,orderId:t,theme:a==null?void 0:a.theme,locale:a==null?void 0:a.locale,paymentMethods:a==null?void 0:a.paymentMethods})},update:t=>{n(g.UPDATE,t)},submit:async()=>{const t=O(e()),a=K();try{return await _(t||void 0,a,g.CONFIRM_PAYMENT,{}),{paymentMethod:void 0}}catch(r){return{error:{message:r instanceof Error?r.message:"Payment failed",code:"payment_error",type:"payment_error"}}}}}}var C=(e=>(e.Success="Success",e.Failed="Failed",e.Timeout="Timeout",e))(C||{});class k{constructor(n,t){p(this,"overlay",null);p(this,"modalContent",null);this.data=n,this.options=t}fail(n){var a,r;const t=new Error(n);return(r=(a=this.options).onError)==null||r.call(a,t),{status:"Failed",error:t}}showModal(){return this.injectStyles(),this.overlay=document.createElement("div"),this.overlay.id="payconductor-3ds-overlay",this.modalContent=document.createElement("div"),this.modalContent.id="payconductor-3ds-modal",this.overlay.appendChild(this.modalContent),document.body.appendChild(this.overlay),this.modalContent}closeModal(){this.overlay&&(this.overlay.remove(),this.overlay=null,this.modalContent=null)}resolveContainer(){return this.modalContent??this.showModal()}injectStyles(){if(document.getElementById("payconductor-3ds-styles"))return;const n=document.createElement("style");n.id="payconductor-3ds-styles",n.textContent=`
|
|
14
14
|
#payconductor-3ds-overlay {
|
|
15
15
|
position: fixed;
|
|
16
16
|
inset: 0;
|
|
@@ -45,5 +45,5 @@
|
|
|
45
45
|
height: 440px;
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
|
-
`,document.head.appendChild(n)}}const _e=5*60*1e3;class Re extends k{constructor(){super(...arguments);b(this,"iframe",null);b(this,"messageListener",null);b(this,"timeoutId",null)}async authenticate(){const{threeDsUrl:t,creq:a}=this.data;if(!t||!a)return this.fail("Missing threeDsUrl or creq");const i=this.resolveContainer();return new Promise(o=>{var l;this.iframe=document.createElement("iframe"),this.iframe.name="payconductor-3ds-challenge",this.iframe.id="payconductor-3ds-challenge",i.appendChild(this.iframe),this.messageListener=S=>{var E,m,y;((E=S.data)==null?void 0:E.status)==="COMPLETE"&&(this.cleanup(),(y=(m=this.options).onComplete)==null||y.call(m),o({status:C.Success}))},window.addEventListener("message",this.messageListener),this.timeoutId=setTimeout(()=>{var S,E;this.cleanup(),(E=(S=this.options).onTimeout)==null||E.call(S),o({status:C.Timeout})},this.options.timeoutMs??_e);const d=(l=this.iframe.contentWindow)==null?void 0:l.document;if(!d){this.cleanup(),o(this.fail("Cannot access iframe document"));return}const s=d.createElement("form");s.name="threeDsChallengeForm",s.setAttribute("target","payconductor-3ds-challenge"),s.setAttribute("method","post"),s.setAttribute("action",t);const r=d.createElement("input");r.setAttribute("type","hidden"),r.setAttribute("name","creq"),r.setAttribute("value",a),s.appendChild(r),this.iframe.appendChild(s),s.submit()})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe&&(this.iframe.remove(),this.iframe=null),this.closeModal()}}const L=new Map;function N(e){const n=L.get(e);if(n)return n;const t=new Promise((a,i)=>{if(document.querySelector(`script[src="${e}"]`)){a();return}const o=document.createElement("script");o.src=e,o.async=!0,o.onload=()=>a(),o.onerror=()=>{L.delete(e),i(new Error(`Failed to load script: ${e}`))},(document.head||document.body).appendChild(o)});return L.set(e,t),t}const Ne="https://static.payzen.lat/static/js/authenticate-client/V1.0/kr-authenticate.umd",ke=10*60*1e3;class xe extends k{constructor(){super(...arguments);b(this,"timeoutId",null)}async authenticate(){const{operationUrl:t,publicKey:a}=this.data;if(!t||!a)return this.fail("Missing operationUrl or publicKey");try{await N(Ne)}catch{return this.fail("Failed to load 3DS SDK")}const i=window.KrAuthenticate;return i?new Promise(o=>{this.timeoutId=setTimeout(()=>{var s,r;this.cleanup(),(r=(s=this.options).onTimeout)==null||r.call(s),o({status:C.Timeout})},this.options.timeoutMs??ke),new i(a).authenticate(t,()=>{var s,r;this.cleanup(),(r=(s=this.options).onComplete)==null||r.call(s),o({status:C.Success})})}):this.fail("KrAuthenticate not available")}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const Oe={[D.Production]:"https://3ds-nx-js.stone.com.br/live/v2/3ds2.min",[D.Sandbox]:"https://3ds-nx-js.stone.com.br/test/v2/3ds2.min"},Le=5*60*1e3;function Ue(){const e=window.innerWidth;return e<=480?"01":e<=768?"02":e<=1024?"03":"04"}class Fe extends k{constructor(){super(...arguments);b(this,"timeoutId",null);b(this,"methodContainer",null)}async authenticate(){const{authToken:t,card:a}=this.data;if(!t)return this.fail("Missing authToken for PagarMe 3DS");if(!a)return this.fail("Missing card data for PagarMe 3DS");const i=this.data.environment??D.Production;try{await N(Oe[i])}catch{return this.fail("Failed to load Stone 3DS SDK")}const o=window.TDS;if(!o)return this.fail("Stone TDS SDK not available");const d=this.resolveContainer();return this.methodContainer=document.createElement("div"),this.methodContainer.style.display="none",document.body.appendChild(this.methodContainer),new Promise(s=>{this.timeoutId=setTimeout(()=>{var r,l;this.cleanup(),(l=(r=this.options).onTimeout)==null||l.call(r),s({status:C.Timeout})},this.options.timeoutMs??Le),o.init({token:t,tds_method_container_element:this.methodContainer,challenge_container_element:d,use_default_challenge_iframe_style:!0,challenge_window_size:Ue()},this.buildOrderData()).then(r=>{var S,E;if(this.cleanup(),!(r!=null&&r.length)){s(this.fail("PagarMe 3DS returned no response"));return}const l=r[0];if(l.challenge_canceled){s(this.fail("3DS challenge canceled by user"));return}l.trans_status==="Y"||l.trans_status==="A"?((E=(S=this.options).onComplete)==null||E.call(S),s({status:C.Success,dsTransactionId:l.tds_server_trans_id})):s(this.fail(`3DS failed with status: ${l.trans_status}`))}).catch(r=>{this.cleanup(),s(this.fail(r instanceof Error?r.message:"PagarMe 3DS failed"))})})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.methodContainer&&(this.methodContainer.remove(),this.methodContainer=null),this.closeModal()}buildOrderData(){var d;const{card:t,customer:a,amount:i,billingAddress:o}=this.data;return{payments:[{payment_method:"credit_card",credit_card:{card:{number:t==null?void 0:t.number,holder_name:t==null?void 0:t.holderName,exp_month:Number(t==null?void 0:t.expMonth),exp_year:Number(t==null?void 0:t.expYear),billing_address:o?{country:o.country,state:o.state,city:o.city,zip_code:o.zipCode,line_1:`${o.number}, ${o.street}${o.district?`, ${o.district}`:""}`,line_2:o.complement??""}:void 0}},amount:i}],...a?{customer:{name:a.name,email:a.email,...a.document?{document:a.document}:{},...(d=a.phones)!=null&&d.length?{phones:Object.fromEntries(a.phones.map(s=>[s.type==="HOME"?"home_phone":"mobile_phone",{country_code:s.countryCode,area_code:s.areaCode,number:s.number}]))}:{}}}:{}}}}const Ke="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min";class Be extends k{async authenticate(){var E,m,y;const{authToken:n,card:t,customer:a,amount:i,currency:o,billingAddress:d}=this.data;if(!n)return this.fail("Missing authToken (session) for PagSeguro 3DS");if(!t)return this.fail("Missing card data for PagSeguro 3DS");if(!a)return this.fail("Missing customer data for PagSeguro 3DS");if(!i)return this.fail("Missing amount for PagSeguro 3DS");if(!d)return this.fail("Missing billingAddress for PagSeguro 3DS");const s=this.data.environment===D.Sandbox?"SANDBOX":"PROD";try{await N(Ke)}catch{return this.fail("Failed to load PagSeguro SDK")}const r=window.PagSeguro;if(!r)return this.fail("PagSeguro SDK not available");r.setUp({session:n,env:s});const l=((E=a.phones)==null?void 0:E.map(h=>({country:h.countryCode,area:h.areaCode,number:h.number,type:h.type??"MOBILE"})))??[{country:"55",area:"11",number:"999999999",type:"MOBILE"}];l.some(h=>h.type==="MOBILE")||(l[0].type="MOBILE");try{const h=await r.authenticate3DS({data:{customer:{name:a.name,email:a.email,phones:l},paymentMethod:{type:this.data.installments===0?"DEBIT_CARD":"CREDIT_CARD",installments:this.data.installments??1,card:{number:t.number,expMonth:t.expMonth,expYear:t.expYear,holder:{name:t.holderName}}},amount:{value:i,currency:o??"BRL"},billingAddress:{street:d.street,number:d.number,complement:d.complement,regionCode:d.state,country:d.country.length===2?this.toAlpha3(d.country):d.country,city:d.city,postalCode:d.zipCode.replace(/\D/g,"")},dataOnly:!1}});return h.status==="AUTH_FLOW_COMPLETED"||h.status==="AUTH_NOT_SUPPORTED"?((y=(m=this.options).onComplete)==null||y.call(m),{status:C.Success,dsTransactionId:h.id}):h.status==="CHANGE_PAYMENT_METHOD"?this.fail("PagSeguro requires a different payment method"):{status:C.Success,dsTransactionId:h.id}}catch(h){return this.fail(h instanceof Error?h.message:"PagSeguro 3DS failed")}}cleanup(){}toAlpha3(n){return{BR:"BRA",US:"USA",AR:"ARG",CL:"CHL",CO:"COL",MX:"MEX",PE:"PER",UY:"URY"}[n.toUpperCase()]??n}}const ze={[I.MercadoPago]:Re,PayConductor:xe,[I.PagarMe]:Fe,[I.PagSeguro]:Be};class He extends Error{constructor(n,t){super(n),this.title=t,this.name="PayConductorThreeDSApiError"}}class Ye{constructor(n){this.publicKey=n}async completeManualChallenge(n,t){const a=await fetch(`${this.baseUrl}/three-ds/complete/${n}`,{method:"POST",headers:this.headers,body:JSON.stringify({providerTransactionId:t})});a.ok||await this.parseResponseError("Failed to complete native 3DS challenge",a)}async parseResponseError(n,t){var i,o,d,s;let a="";try{const r=await t.json();r!=null&&r.message?a=r.message:(i=r==null?void 0:r.error)!=null&&i.message?a=r.error:(d=(o=r==null?void 0:r.error)==null?void 0:o.value)!=null&&d.message?a=r.error.value.message:(s=r==null?void 0:r.value)!=null&&s.message?a=r.value.message:a=JSON.stringify(r)}catch{}throw new He(a,n)}get baseUrl(){return typeof window<"u"&&window.location.href.includes("localhost")?"http://localhost:3000/api/v1/sdk":"https://payconductor.ai/api/v1/sdk"}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}const Ge=[I.PagSeguro];class ce{constructor(n){b(this,"data");b(this,"provider",null);this.data=n}get needsChallenge(){return this.data.status==="NeedChallenge"||this.data.statusDetail==="ThreeDsAwaitingChallenge"}get acquirer(){return this.data.acquirer}async authenticate(n){if(!this.needsChallenge)return{status:C.Success};const{acquirer:t}=this.data;if(!t)return{status:C.Failed,error:new Error("Missing 3DS acquirer")};const a=ze[t];if(!a)return{status:C.Failed,error:new Error(`Unsupported 3DS provider: ${t}`)};const i={...n,threeDSecure:this.data};this.provider=new a(this.data,i);const o=await this.provider.authenticate();return o.status===C.Success&&o.dsTransactionId&&Ge.includes(t)&&this.data.orderId&&this.data.publicKey&&await new Ye(this.data.publicKey).completeManualChallenge(this.data.orderId,o.dsTransactionId),o}destroy(){this.provider&&(this.provider.cleanup(),this.provider=null)}}function je(e){let n=null;return{handleChallenge:async i=>{var s;if(!(i.status==="NeedChallenge"||i.statusDetail==="ThreeDsAwaitingChallenge"))return{status:C.Success};(s=e==null?void 0:e.onChallenge)==null||s.call(e),n=new ce(i);const d=await n.authenticate({onComplete:e==null?void 0:e.onComplete,onError:e==null?void 0:e.onError,onTimeout:e==null?void 0:e.onTimeout});return n.destroy(),n=null,d},destroy:()=>{n==null||n.destroy(),n=null}}}class Ve extends Error{constructor(n,t){super(n),this.title=t,this.name="PayConductorTokenizeApiError"}}class qe{constructor(n){this.publicKey=n}async getSettings(){const n=await fetch(`${this.baseUrl}/card-tokenization/settings`,{method:"GET",headers:this.headers});return n.ok||await this.parseResponseError("Failed to fetch settings",n),await n.json()}async createToken(n){const t=await fetch(`${this.baseUrl}/card-tokenization/tokenize`,{method:"POST",headers:this.headers,body:JSON.stringify(n)});return t.ok||await this.parseResponseError("Failed to generate token",t),await t.json()}async saveTokens(n,t,a){const i=await fetch(`${this.baseUrl}/card-tokenization/save-tokens/${t}/${a}`,{method:"POST",headers:this.headers,body:JSON.stringify(n)});i.ok||await this.parseResponseError("Failed to save tokens",i)}async parseResponseError(n,t){var i,o,d,s;let a="";try{const r=await t.json();r!=null&&r.message?a=r.message:(i=r==null?void 0:r.error)!=null&&i.message?a=r.error:(d=(o=r==null?void 0:r.error)==null?void 0:o.value)!=null&&d.message?a=r.error.value.message:(s=r==null?void 0:r.value)!=null&&s.message?a=r.value.message:a=JSON.stringify(r)}catch{}throw new Ve(a,n)}get baseUrl(){return typeof window<"u"&&window.location.href.includes("localhost")?"http://localhost:3000/api/v1/sdk":"https://payconductor.ai/api/v1/sdk"}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}class $e{constructor(n){this.input=n}}class We extends $e{constructor(){super(...arguments);b(this,"scriptUrl","https://sdk.mercadopago.com/js/v2")}async tokenize(){if(!("publicKey"in this.input.setting))throw new Error("MercadoPago public key is missing in settings");if(!this.input.customer.documentNumber)throw new Error("Customer document number is required for tokenization");const t=window.MercadoPago;if(!t)throw new Error("MercadoPago SDK not available");const a=new t(this.input.setting.publicKey),{expiration:i,cvv:o,number:d,holderName:s}=this.input.card;return(await a.createCardToken({cardExpirationMonth:String(i.month),cardExpirationYear:String(i.year),cardholderName:s,cardNumber:d,securityCode:o,identificationType:this.input.customer.documentType===B.Cpf?"CPF":"CNPJ",identificationNumber:this.input.customer.documentNumber})).id}}const Je={[I.MercadoPago]:We};class le{constructor(n){b(this,"api");this.publicKey=n,this.api=new qe(this.publicKey)}async tokenizeCard(n){this.validateCard(n);const{customerId:t,token:a}=await this.api.createToken({card:n.card,customer:n.customer,saveCard:!1}),{settings:i}=await this.api.getSettings(),d=(await Promise.all(i.map(async s=>{const r=Je[s.key];if(!r)return null;const l=new r({...n,setting:s.settings});return await N(l.scriptUrl),{token:await l.tokenize(),integrationId:s.integrationId,providerKey:s.key}}))).filter(s=>s!==null);return d.length>0&&await this.api.saveTokens(d,t,a),a}validateCard(n){const{number:t,cvv:a,expiration:i,holderName:o}=n.card;if(!t||!a||!(i!=null&&i.month)||!(i!=null&&i.year)||!o)throw new Error("Invalid card data")}}function Xe(e){const n=new le(e.publicKey);return{tokenizeCard:async a=>{var i,o;try{const d=await n.tokenizeCard(a);return(i=e.onSuccess)==null||i.call(e,d),d}catch(d){const s=d instanceof Error?d:new Error("Tokenization failed");return(o=e.onError)==null||o.call(e,s),null}}}}exports.ALLOWED_ORIGINS=ne;exports.CardBrand=J;exports.CurrencyType=X;exports.DeviceType=Z;exports.DocumentType=B;exports.ERROR_CODES=ge;exports.ErrorCode=ee;exports.IFRAME_BASE_URL=te;exports.IFRAME_DEFAULT_HEIGHT_VALUE=U;exports.IncomingMessage=T;exports.InputStyleKey=Q;exports.IntegrationProvider=I;exports.OrganizationEnvironment=D;exports.OutgoingMessage=M;exports.POST_MESSAGES=g;exports.PayConductor=de;exports.PayConductor3DSSDK=ce;exports.PayConductorCheckoutElement=Ae;exports.PayConductorThreeDSElement=Me;exports.PayConductorTokenizeSDK=le;exports.PaymentMethod=G;exports.PaymentMethodLayout=j;exports.PaymentStatus=V;exports.REQUEST_TIMEOUT=ae;exports.SKELETON_CSS=ie;exports.SKELETON_STYLE_ID=F;exports.StatusDetail=q;exports.ThreeDSResultStatus=W;exports.ThreeDsAuthenticationStatus=$;exports.buildIframeUrl=re;exports.default=de;exports.defaultTheme=Ee;exports.generateRequestId=oe;exports.isValidOrigin=se;exports.loadScript=N;exports.usePayConductor=Ie;exports.usePayconductorElement=De;exports.useThreeDS=je;exports.useTokenize=Xe;
|
|
48
|
+
`,document.head.appendChild(n)}}const _e=5*60*1e3;class Re extends k{constructor(){super(...arguments);p(this,"iframe",null);p(this,"messageListener",null);p(this,"timeoutId",null)}async authenticate(){const{threeDsUrl:t,creq:a}=this.data;if(!t||!a)return this.fail("Missing threeDsUrl or creq");const r=this.resolveContainer();return new Promise(o=>{var l;this.iframe=document.createElement("iframe"),this.iframe.name="payconductor-3ds-challenge",this.iframe.id="payconductor-3ds-challenge",r.appendChild(this.iframe),this.messageListener=S=>{var E,h,y;((E=S.data)==null?void 0:E.status)==="COMPLETE"&&(this.cleanup(),(y=(h=this.options).onComplete)==null||y.call(h),o({status:C.Success}))},window.addEventListener("message",this.messageListener),this.timeoutId=setTimeout(()=>{var S,E;this.cleanup(),(E=(S=this.options).onTimeout)==null||E.call(S),o({status:C.Timeout})},this.options.timeoutMs??_e);const d=(l=this.iframe.contentWindow)==null?void 0:l.document;if(!d){this.cleanup(),o(this.fail("Cannot access iframe document"));return}const s=d.createElement("form");s.name="threeDsChallengeForm",s.setAttribute("target","payconductor-3ds-challenge"),s.setAttribute("method","post"),s.setAttribute("action",t);const i=d.createElement("input");i.setAttribute("type","hidden"),i.setAttribute("name","creq"),i.setAttribute("value",a),s.appendChild(i),this.iframe.appendChild(s),s.submit()})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe&&(this.iframe.remove(),this.iframe=null),this.closeModal()}}const L=new Map;function N(e){const n=L.get(e);if(n)return n;const t=new Promise((a,r)=>{if(document.querySelector(`script[src="${e}"]`)){a();return}const o=document.createElement("script");o.src=e,o.async=!0,o.onload=()=>a(),o.onerror=()=>{L.delete(e),r(new Error(`Failed to load script: ${e}`))},(document.head||document.body).appendChild(o)});return L.set(e,t),t}const Ne="https://static.payzen.lat/static/js/authenticate-client/V1.0/kr-authenticate.umd",ke=10*60*1e3;class xe extends k{constructor(){super(...arguments);p(this,"timeoutId",null)}async authenticate(){const{operationUrl:t,publicKey:a}=this.data;if(!t||!a)return this.fail("Missing operationUrl or publicKey");try{await N(Ne)}catch{return this.fail("Failed to load 3DS SDK")}const r=window.KrAuthenticate;return r?new Promise(o=>{this.timeoutId=setTimeout(()=>{var s,i;this.cleanup(),(i=(s=this.options).onTimeout)==null||i.call(s),o({status:C.Timeout})},this.options.timeoutMs??ke),new r(a).authenticate(t,()=>{var s,i;this.cleanup(),(i=(s=this.options).onComplete)==null||i.call(s),o({status:C.Success})})}):this.fail("KrAuthenticate not available")}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const Oe={[D.Production]:"https://3ds-nx-js.stone.com.br/live/v2/3ds2.min",[D.Sandbox]:"https://3ds-nx-js.stone.com.br/test/v2/3ds2.min"},Le=5*60*1e3;function Ue(){const e=window.innerWidth;return e<=480?"01":e<=768?"02":e<=1024?"03":"04"}class Fe extends k{constructor(){super(...arguments);p(this,"timeoutId",null);p(this,"methodContainer",null)}async authenticate(){const{authToken:t,card:a}=this.data;if(!t)return this.fail("Missing authToken for PagarMe 3DS");if(!a)return this.fail("Missing card data for PagarMe 3DS");const r=this.data.environment??D.Production;try{await N(Oe[r])}catch{return this.fail("Failed to load Stone 3DS SDK")}const o=window.TDS;if(!o)return this.fail("Stone TDS SDK not available");const d=this.resolveContainer();return this.methodContainer=document.createElement("div"),this.methodContainer.style.display="none",document.body.appendChild(this.methodContainer),new Promise(s=>{this.timeoutId=setTimeout(()=>{var i,l;this.cleanup(),(l=(i=this.options).onTimeout)==null||l.call(i),s({status:C.Timeout})},this.options.timeoutMs??Le),o.init({token:t,tds_method_container_element:this.methodContainer,challenge_container_element:d,use_default_challenge_iframe_style:!0,challenge_window_size:Ue()},this.buildOrderData()).then(i=>{var S,E;if(this.cleanup(),!(i!=null&&i.length)){s(this.fail("PagarMe 3DS returned no response"));return}const l=i[0];if(l.challenge_canceled){s(this.fail("3DS challenge canceled by user"));return}l.trans_status==="Y"||l.trans_status==="A"?((E=(S=this.options).onComplete)==null||E.call(S),s({status:C.Success,dsTransactionId:l.tds_server_trans_id})):s(this.fail(`3DS failed with status: ${l.trans_status}`))}).catch(i=>{this.cleanup(),s(this.fail(i instanceof Error?i.message:"PagarMe 3DS failed"))})})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.methodContainer&&(this.methodContainer.remove(),this.methodContainer=null),this.closeModal()}buildOrderData(){var d;const{card:t,customer:a,amount:r,billingAddress:o}=this.data;return{payments:[{payment_method:"credit_card",credit_card:{card:{number:t==null?void 0:t.number,holder_name:t==null?void 0:t.holderName,exp_month:Number(t==null?void 0:t.expMonth),exp_year:Number(t==null?void 0:t.expYear),billing_address:o?{country:o.country,state:o.state,city:o.city,zip_code:o.zipCode,line_1:`${o.number}, ${o.street}${o.district?`, ${o.district}`:""}`,line_2:o.complement??""}:void 0}},amount:r}],...a?{customer:{name:a.name,email:a.email,...a.document?{document:a.document}:{},...(d=a.phones)!=null&&d.length?{phones:Object.fromEntries(a.phones.map(s=>[s.type==="HOME"?"home_phone":"mobile_phone",{country_code:s.countryCode,area_code:s.areaCode,number:s.number}]))}:{}}}:{}}}}const Ke="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min";class Be extends k{async authenticate(){var E,h,y;const{authToken:n,card:t,customer:a,amount:r,currency:o,billingAddress:d}=this.data;if(!n)return this.fail("Missing authToken (session) for PagSeguro 3DS");if(!t)return this.fail("Missing card data for PagSeguro 3DS");if(!a)return this.fail("Missing customer data for PagSeguro 3DS");if(!r)return this.fail("Missing amount for PagSeguro 3DS");if(!d)return this.fail("Missing billingAddress for PagSeguro 3DS");const s=this.data.environment===D.Sandbox?"SANDBOX":"PROD";try{await N(Ke)}catch{return this.fail("Failed to load PagSeguro SDK")}const i=window.PagSeguro;if(!i)return this.fail("PagSeguro SDK not available");i.setUp({session:n,env:s});const l=((E=a.phones)==null?void 0:E.map(m=>({country:m.countryCode,area:m.areaCode,number:m.number,type:m.type??"MOBILE"})))??[{country:"55",area:"11",number:"999999999",type:"MOBILE"}];l.some(m=>m.type==="MOBILE")||(l[0].type="MOBILE");try{const m=await i.authenticate3DS({data:{customer:{name:a.name,email:a.email,phones:l},paymentMethod:{type:this.data.installments===0?"DEBIT_CARD":"CREDIT_CARD",installments:this.data.installments??1,card:{number:t.number,expMonth:t.expMonth,expYear:t.expYear,holder:{name:t.holderName}}},amount:{value:r,currency:o??"BRL"},billingAddress:{street:d.street,number:d.number,complement:d.complement,regionCode:d.state,country:d.country.length===2?this.toAlpha3(d.country):d.country,city:d.city,postalCode:d.zipCode.replace(/\D/g,"")},dataOnly:!1}});return m.status==="AUTH_FLOW_COMPLETED"||m.status==="AUTH_NOT_SUPPORTED"?((y=(h=this.options).onComplete)==null||y.call(h),{status:C.Success,dsTransactionId:m.id}):m.status==="CHANGE_PAYMENT_METHOD"?this.fail("PagSeguro requires a different payment method"):{status:C.Success,dsTransactionId:m.id}}catch(m){return this.fail(m instanceof Error?m.message:"PagSeguro 3DS failed")}}cleanup(){}toAlpha3(n){return{BR:"BRA",US:"USA",AR:"ARG",CL:"CHL",CO:"COL",MX:"MEX",PE:"PER",UY:"URY"}[n.toUpperCase()]??n}}const ze={[M.MercadoPago]:Re,PayConductor:xe,[M.PagarMe]:Fe,[M.PagSeguro]:Be};class He extends Error{constructor(n,t){super(n),this.title=t,this.name="PayConductorThreeDSApiError"}}class Ye{constructor(n){this.publicKey=n}async completeManualChallenge(n,t){const a=await fetch(`${this.baseUrl}/three-ds/complete/${n}`,{method:"POST",headers:this.headers,body:JSON.stringify({providerTransactionId:t})});a.ok||await this.parseResponseError("Failed to complete native 3DS challenge",a)}async parseResponseError(n,t){var r,o,d,s;let a="";try{const i=await t.json();i!=null&&i.message?a=i.message:(r=i==null?void 0:i.error)!=null&&r.message?a=i.error:(d=(o=i==null?void 0:i.error)==null?void 0:o.value)!=null&&d.message?a=i.error.value.message:(s=i==null?void 0:i.value)!=null&&s.message?a=i.value.message:a=JSON.stringify(i)}catch{}throw new He(a,n)}get baseUrl(){return typeof window<"u"&&window.location.href.includes("localhost")?"http://localhost:3000/api/v1/sdk":"https://payconductor.ai/api/v1/sdk"}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}const Ge=[M.PagSeguro];class ce{constructor(n){p(this,"data");p(this,"provider",null);this.data=n}get needsChallenge(){return this.data.status==="NeedChallenge"||this.data.statusDetail==="ThreeDsAwaitingChallenge"}get acquirer(){return this.data.acquirer}async authenticate(n){if(!this.needsChallenge)return{status:C.Success};const{acquirer:t}=this.data;if(!t)return{status:C.Failed,error:new Error("Missing 3DS acquirer")};const a=ze[t];if(!a)return{status:C.Failed,error:new Error(`Unsupported 3DS provider: ${t}`)};const r={...n,threeDSecure:this.data};this.provider=new a(this.data,r);const o=await this.provider.authenticate();return o.status===C.Success&&o.dsTransactionId&&Ge.includes(t)&&this.data.orderId&&this.data.publicKey&&await new Ye(this.data.publicKey).completeManualChallenge(this.data.orderId,o.dsTransactionId),o}destroy(){this.provider&&(this.provider.cleanup(),this.provider=null)}}function je(e){let n=null;return{handleChallenge:async r=>{var s;if(!(r.status==="NeedChallenge"||r.statusDetail==="ThreeDsAwaitingChallenge"))return{status:C.Success};(s=e==null?void 0:e.onChallenge)==null||s.call(e),n=new ce(r);const d=await n.authenticate({onComplete:e==null?void 0:e.onComplete,onError:e==null?void 0:e.onError,onTimeout:e==null?void 0:e.onTimeout});return n.destroy(),n=null,d},destroy:()=>{n==null||n.destroy(),n=null}}}class Ve extends Error{constructor(n,t){super(n),this.title=t,this.name="PayConductorTokenizeApiError"}}class qe{constructor(n){this.publicKey=n}async getSettings(){const n=await fetch(`${this.baseUrl}/card-tokenization/settings`,{method:"GET",headers:this.headers});return n.ok||await this.parseResponseError("Failed to fetch settings",n),await n.json()}async createToken(n){const t=await fetch(`${this.baseUrl}/card-tokenization/tokenize`,{method:"POST",headers:this.headers,body:JSON.stringify(n)});return t.ok||await this.parseResponseError("Failed to generate token",t),await t.json()}async saveTokens(n,t,a){const r=await fetch(`${this.baseUrl}/card-tokenization/save-tokens/${t}/${a}`,{method:"POST",headers:this.headers,body:JSON.stringify(n)});r.ok||await this.parseResponseError("Failed to save tokens",r)}async parseResponseError(n,t){var r,o,d,s;let a="";try{const i=await t.json();i!=null&&i.message?a=i.message:(r=i==null?void 0:i.error)!=null&&r.message?a=i.error:(d=(o=i==null?void 0:i.error)==null?void 0:o.value)!=null&&d.message?a=i.error.value.message:(s=i==null?void 0:i.value)!=null&&s.message?a=i.value.message:a=JSON.stringify(i)}catch{}throw new Ve(a,n)}get baseUrl(){return typeof window<"u"&&window.location.href.includes("localhost")?"http://localhost:3000/api/v1/sdk":"https://payconductor.ai/api/v1/sdk"}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}class $e{constructor(n){this.input=n}}class We extends $e{constructor(){super(...arguments);p(this,"scriptUrl","https://sdk.mercadopago.com/js/v2")}async tokenize(){if(!("publicKey"in this.input.setting))throw new Error("MercadoPago public key is missing in settings");if(!this.input.customer.documentNumber)throw new Error("Customer document number is required for tokenization");const t=window.MercadoPago;if(!t)throw new Error("MercadoPago SDK not available");const a=new t(this.input.setting.publicKey),{expiration:r,cvv:o,number:d,holderName:s}=this.input.card;return(await a.createCardToken({cardExpirationMonth:String(r.month),cardExpirationYear:String(r.year),cardholderName:s,cardNumber:d,securityCode:o,identificationType:this.input.customer.documentType===B.Cpf?"CPF":"CNPJ",identificationNumber:this.input.customer.documentNumber})).id}}const Je={[M.MercadoPago]:We};class le{constructor(n){p(this,"api");this.publicKey=n,this.api=new qe(this.publicKey)}async tokenizeCard(n){this.validateCard(n);const{customerId:t,token:a}=await this.api.createToken({card:n.card,customer:n.customer,saveCard:!1}),{settings:r}=await this.api.getSettings(),d=(await Promise.all(r.map(async s=>{const i=Je[s.key];if(!i)return null;const l=new i({...n,setting:s.settings});return await N(l.scriptUrl),{token:await l.tokenize(),integrationId:s.integrationId,providerKey:s.key}}))).filter(s=>s!==null);return d.length>0&&await this.api.saveTokens(d,t,a),a}validateCard(n){const{number:t,cvv:a,expiration:r,holderName:o}=n.card;if(!t||!a||!(r!=null&&r.month)||!(r!=null&&r.year)||!o)throw new Error("Invalid card data")}}function Xe(e){const n=new le(e.publicKey);return{tokenizeCard:async a=>{var r,o;try{const d=await n.tokenizeCard(a);return(r=e.onSuccess)==null||r.call(e,d),d}catch(d){const s=d instanceof Error?d:new Error("Tokenization failed");return(o=e.onError)==null||o.call(e,s),null}}}}exports.ALLOWED_ORIGINS=ne;exports.CardBrand=J;exports.CurrencyType=X;exports.DeviceType=Z;exports.DocumentType=B;exports.ERROR_CODES=ge;exports.ErrorCode=ee;exports.IFRAME_BASE_URL=te;exports.IFRAME_DEFAULT_HEIGHT_VALUE=U;exports.IncomingMessage=T;exports.InputStyleKey=Q;exports.IntegrationProvider=M;exports.OrganizationEnvironment=D;exports.OutgoingMessage=I;exports.POST_MESSAGES=g;exports.PayConductor=de;exports.PayConductor3DSSDK=ce;exports.PayConductorCheckoutElement=Ae;exports.PayConductorThreeDSElement=Ie;exports.PayConductorTokenizeSDK=le;exports.PaymentMethod=G;exports.PaymentMethodLayout=j;exports.PaymentStatus=V;exports.REQUEST_TIMEOUT=ae;exports.SKELETON_CSS=re;exports.SKELETON_STYLE_ID=F;exports.StatusDetail=q;exports.ThreeDSResultStatus=W;exports.ThreeDsAuthenticationStatus=$;exports.buildIframeUrl=ie;exports.default=de;exports.defaultTheme=Ee;exports.generateRequestId=oe;exports.isValidOrigin=se;exports.loadScript=N;exports.usePayConductor=Me;exports.usePayconductorElement=De;exports.useThreeDS=je;exports.useTokenize=Xe;
|
|
49
49
|
//# sourceMappingURL=index.cjs.js.map
|