@payconductor/react 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/three-ds.d.ts +1 -1
- package/dist/esm/tokenizer.d.ts +1 -1
- package/dist/index.cjs.js +49 -49
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +12 -12
- package/dist/index.es.js +1401 -1318
- package/dist/index.es.js.map +1 -1
- package/dist/payconductor/constants.d.ts +32 -31
- package/dist/payconductor/hooks/index.d.ts +7 -7
- package/dist/payconductor/hooks/use-element.d.ts +30 -30
- package/dist/payconductor/hooks/use-payconductor.d.ts +6 -6
- package/dist/payconductor/hooks/use-three-ds.d.ts +13 -13
- package/dist/payconductor/hooks/use-tokenizer.d.ts +11 -11
- package/dist/payconductor/iframe/constants.d.ts +7 -8
- package/dist/payconductor/iframe/types.d.ts +464 -464
- package/dist/payconductor/internal.d.ts +11 -11
- package/dist/payconductor/loader.d.ts +1 -1
- package/dist/payconductor/payconductor-element.d.ts +5 -5
- package/dist/payconductor/payconductor-three-ds.d.ts +5 -5
- package/dist/payconductor/payconductor.d.ts +17 -17
- package/dist/payconductor/three-ds/api.d.ts +14 -12
- package/dist/payconductor/three-ds/browser.d.ts +13 -13
- package/dist/payconductor/three-ds/handler.d.ts +12 -11
- package/dist/payconductor/three-ds/index.d.ts +3 -3
- package/dist/payconductor/three-ds/providers/index.d.ts +6 -6
- package/dist/payconductor/three-ds/providers/mercado-pago.d.ts +9 -9
- package/dist/payconductor/three-ds/providers/pagarme.d.ts +9 -9
- package/dist/payconductor/three-ds/providers/pagseguro.d.ts +7 -7
- package/dist/payconductor/three-ds/providers/payconductor.d.ts +7 -7
- package/dist/payconductor/three-ds/providers/sandbox.d.ts +9 -0
- package/dist/payconductor/three-ds/types.d.ts +100 -93
- package/dist/payconductor/tokenizer/api.d.ts +25 -26
- package/dist/payconductor/tokenizer/handler.d.ts +9 -9
- package/dist/payconductor/tokenizer/index.d.ts +1 -1
- package/dist/payconductor/tokenizer/providers/index.d.ts +6 -6
- package/dist/payconductor/tokenizer/providers/mercado-pago.d.ts +7 -6
- package/dist/payconductor/tokenizer/types.d.ts +50 -50
- package/dist/payconductor/types.d.ts +42 -42
- package/dist/payconductor/utils.d.ts +6 -6
- package/package.json +1 -1
package/dist/esm/three-ds.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export {};
|
package/dist/esm/tokenizer.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export {};
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
@keyframes payconductor-shimmer {
|
|
3
|
-
0% { background-position: -200% 0; }
|
|
4
|
-
100% { background-position: 200% 0; }
|
|
5
|
-
}
|
|
6
|
-
.payconductor-skeleton {
|
|
7
|
-
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
|
|
8
|
-
background-size: 200% 100%;
|
|
9
|
-
animation: payconductor-shimmer 1.5s infinite linear;
|
|
10
|
-
border-radius: 4px;
|
|
11
|
-
width: 100%;
|
|
12
|
-
}
|
|
13
|
-
`;function oe(e){const n=new URLSearchParams({publicKey:e.publicKey});return`${ne}?${n.toString()}`}function se(){return crypto.randomUUID()}function de(e,n){return n.some(t=>{try{return new URL(t).origin===e}catch{return t===e}})}function B(){return new Map}function D(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=se();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")))},re)})}function Pe(e,n,t){return D(e,n,S.CONFIRM_PAYMENT,t)}async function Ce(e,n,t){return await Pe(e,n,{orderId:t.orderId})}function be(e,n,t){return D(e,n,S.VALIDATE,t)}function pe(e,n){return D(e,n,S.RESET)}function Te(e,n,t){return D(e,n,S.CONFIG,t)}function ve(e,n,t){return D(e,n,S.INIT,t)}function Ae(e,n,t,a,r,o,d,s,i,c,g,E){const m=e.data,{requestId:f,type:u,data:w,error:b}=m;if(u===S.READY){if(a==null||a(),f&&(n!=null&&n.has(f))){const{resolve:v}=n.get(f);n.delete(f),v(w)}return}if(de(e.origin,ae)){if(f&&n&&n.has(f)){const{resolve:v,reject:O}=n.get(f);n.delete(f),b?O(new Error(String(b.message))):v(w);return}if(u===S.ERROR){t((b==null?void 0:b.message)||"Unknown error"),r==null||r(new Error(String(b==null?void 0:b.message)));return}if(u===S.PAYMENT_COMPLETE){w&&typeof w=="object"&&"status"in w&&(o==null||o(w));return}if(u===S.PAYMENT_FAILED){w&&typeof w=="object"&&"status"in w&&(d==null||d(w));return}if(u===S.PAYMENT_PENDING){w&&typeof w=="object"&&"status"in w&&(s==null||s(w));return}if(u===S.PAYMENT_METHOD_SELECTED){w&&typeof w=="object"&&"paymentMethod"in w&&(i==null||i(w.paymentMethod));return}if(u!==S.RESIZE){if(u===T.ThreeDSChallenge){c==null||c();return}if(u===T.ThreeDSComplete){g==null||g();return}if(u===T.ThreeDSFailed){E==null||E();return}}}}function ce(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 c=(...h)=>{e.debug&&console.log("[PayConductor]",...h)},g=oe({publicKey:e.publicKey});d(g),t(!0);const E=B();let m=!1;c("init",e.publicKey),c("iframeUrl",g);const f=()=>{var C,l;const h=(l=(C=window.PayConductor)==null?void 0:C.frame)==null?void 0:l.iframe;if(h){if(h instanceof HTMLIFrameElement)return h;if(typeof h=="object"&&h!==null){const y=h;if("current"in y&&y.current instanceof HTMLIFrameElement)return y.current;if("value"in y&&y.value instanceof HTMLIFrameElement)return y.value}return h}return document.querySelector(".payconductor-element iframe")??void 0},u={get iframe(){return document.querySelector(".payconductor-element iframe")??null},set iframe(h){},iframeUrl:g,error:null},w={publicKey:e.publicKey,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod},b={confirmPayment:h=>{var l;c("→ CONFIRM_PAYMENT",{orderId:h.orderId});const C=f();return C!=null&&C.contentWindow&&C.contentWindow.postMessage({type:S.CONFIG,data:{publicKey:e.publicKey,orderId:h.orderId,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig}},"*"),w.orderId=h.orderId,(l=window.PayConductor)!=null&&l.config&&(window.PayConductor.config.orderId=h.orderId),Ce(C,E,h)},validate:h=>(c("→ VALIDATE",h),be(f(),E,h)),reset:()=>(c("→ RESET"),pe(f(),E)),getSelectedPaymentMethod:()=>s};window.PayConductor={frame:u,config:w,api:b,selectedPaymentMethod:s},c("registered"),window.dispatchEvent(new CustomEvent("payconductor:registered",{detail:window.PayConductor}));const v=async()=>{if(!m){const h=f();if(!h){c("→ CONFIG skipped: iframe not found");return}m=!0,c("→ CONFIG",{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons}),Te(h,E,{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig})}},O=h=>{var C;(C=h.data)!=null&&C.type&&c("←",h.data.type,h.data.data??""),Ae(h,E,l=>{var y;r(l),u.error=l,(y=window.PayConductor)!=null&&y.frame&&(window.PayConductor.frame.error=l)},()=>{var l;(l=e.onReady)==null||l.call(e),v()},l=>{var y;(y=e.onError)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentComplete)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentFailed)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentPending)==null||y.call(e,l)},l=>{var y;i(l),window.PayConductor&&(window.PayConductor.selectedPaymentMethod=l),(y=e.onPaymentMethodSelected)==null||y.call(e,l)},()=>{var l;(l=e.onThreeDSChallenge)==null||l.call(e)},()=>{var l;(l=e.onThreeDSComplete)==null||l.call(e)},()=>{var l;(l=e.onThreeDSFailed)==null||l.call(e)})};window.addEventListener("message",O);const he=()=>{var C,l,y;const h=f();if(!h)return!1;try{if((((C=h.contentDocument)==null?void 0:C.readyState)??((y=(l=h.contentWindow)==null?void 0:l.document)==null?void 0:y.readyState))==="complete")return v(),!0}catch{}return!1},H=()=>{if(he())return;const h=f();if(h){h.addEventListener("load",()=>v(),{once:!0});return}setTimeout(H,50)};H()},[]),R.jsx("div",{className:"payconductor",id:"payconductor",style:{display:"contents"},children:e.children})}function Ie(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(K)){const m=document.createElement("style");m.id=K,m.textContent=ie,document.head.appendChild(m)}const i=m=>{m!=null&&m.frame&&(a(m.frame.iframeUrl||""),o(!0),console.log("init",{PayConductor:window.PayConductor}))},c=typeof window<"u"?window.PayConductor:null;if(c)i(c);else{const m=f=>{i(f.detail),window.removeEventListener("payconductor:registered",m)};window.addEventListener("payconductor:registered",m)}let g=!1;const E=m=>{var f,u,w,b;if(((f=m.data)==null?void 0:f.type)===S.RESIZE&&((w=(u=m.data)==null?void 0:u.data)!=null&&w.height)&&s(m.data.data.height+"px"),((b=m.data)==null?void 0:b.type)===S.READY&&e.height&&!g){g=!0;const v=document.querySelector(".payconductor-element iframe");v!=null&&v.contentWindow&&v.contentWindow.postMessage({type:S.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||F}}),r&&t?R.jsx("iframe",{allow:"payment",title:"PayConductor",ref:n,src:t,style:{width:"100%",height:e.height||d||F,border:"none"}}):null]})}function Me(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 _e(){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 U(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=U(r);o!=null&&o.contentWindow&&o.contentWindow.postMessage({type:t,data:a},"*")};return{init:async t=>{const a=U(e()),r=B();return ve(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(S.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(S.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(S.UPDATE,t)},submit:async()=>{const t=U(e()),a=B();try{return await D(t||void 0,a,S.CONFIRM_PAYMENT,{}),{paymentMethod:void 0}}catch(r){return{error:{message:r instanceof Error?r.message:"Payment failed",code:"payment_error",type:"payment_error"}}}}}}var P=(e=>(e.Success="Success",e.Failed="Failed",e.Timeout="Timeout",e))(P||{}),N=(e=>(e.Authenticated="Y",e.Attempted="A",e.ChallengeRequired="C",e.NotAuthenticated="N",e.Unavailable="U",e.Rejected="R",e.InformationOnly="I",e))(N||{});class L{constructor(n,t){p(this,"overlay",null);p(this,"modalContent",null);this.data=n,this.options=t}get amountInCents(){return this.data.amount===void 0?void 0:Math.round(this.data.amount*100)}fail(n,t={}){var r,o;const a=new Error(n);return(o=(r=this.options).onError)==null||o.call(r,a),{...t,status:"Failed",error:a}}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
|
-
#payconductor-3ds-overlay {
|
|
15
|
-
position: fixed;
|
|
16
|
-
inset: 0;
|
|
17
|
-
z-index: 99999;
|
|
18
|
-
display: flex;
|
|
19
|
-
align-items: center;
|
|
20
|
-
justify-content: center;
|
|
21
|
-
background: rgba(0, 0, 0, 0.6);
|
|
22
|
-
}
|
|
23
|
-
#payconductor-3ds-modal {
|
|
24
|
-
width: 500px;
|
|
25
|
-
max-width: 95vw;
|
|
26
|
-
min-height: 600px;
|
|
27
|
-
border-radius: 8px;
|
|
28
|
-
overflow: hidden;
|
|
29
|
-
background: #fff;
|
|
30
|
-
}
|
|
31
|
-
#payconductor-3ds-modal iframe {
|
|
32
|
-
width: 100%;
|
|
33
|
-
height: 600px;
|
|
34
|
-
border: none;
|
|
35
|
-
display: block;
|
|
36
|
-
}
|
|
37
|
-
@media only screen and (max-width: 600px) {
|
|
38
|
-
#payconductor-3ds-modal {
|
|
39
|
-
width: 100vw;
|
|
40
|
-
max-width: 100vw;
|
|
41
|
-
min-height: 440px;
|
|
42
|
-
border-radius: 0;
|
|
43
|
-
}
|
|
44
|
-
#payconductor-3ds-modal iframe {
|
|
45
|
-
height: 440px;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
`,document.head.appendChild(n)}}const Re=5*60*1e3;class Ne extends L{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 c;this.iframe=document.createElement("iframe"),this.iframe.name="payconductor-3ds-challenge",this.iframe.id="payconductor-3ds-challenge",r.appendChild(this.iframe),this.messageListener=g=>{var E,m,f;((E=g.data)==null?void 0:E.status)==="COMPLETE"&&(this.cleanup(),(f=(m=this.options).onComplete)==null||f.call(m),o({status:P.Success}))},window.addEventListener("message",this.messageListener),this.timeoutId=setTimeout(()=>{var g,E;this.cleanup(),(E=(g=this.options).onTimeout)==null||E.call(g),o({status:P.Timeout})},this.options.timeoutMs??Re);const d=(c=this.iframe.contentWindow)==null?void 0:c.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 x=new Map;function k(e){const n=x.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=()=>{x.delete(e),r(new Error(`Failed to load script: ${e}`))},(document.head||document.body).appendChild(o)});return x.set(e,t),t}const ke="https://static.payzen.lat/static/js/authenticate-client/V1.0/kr-authenticate.umd.js",Le=10*60*1e3;class Oe extends L{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 k(ke)}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:P.Timeout})},this.options.timeoutMs??Le),new r(a).authenticate(t,()=>{var s,i;this.cleanup(),(i=(s=this.options).onComplete)==null||i.call(s),o({status:P.Success})})}):this.fail("KrAuthenticate not available")}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const Ue={[_.Production]:"https://3ds-nx-js.stone.com.br/live/v2/3ds2.min.js",[_.Sandbox]:"https://3ds-nx-js.stone.com.br/test/v2/3ds2.min.js"},xe=5*60*1e3;function Fe(){const e=window.innerWidth;return e<=480?"01":e<=768?"02":e<=1024?"03":"04"}class Ke extends L{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??_.Production;try{await k(Ue[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,c;this.cleanup(),(c=(i=this.options).onTimeout)==null||c.call(i),s({status:P.Timeout})},this.options.timeoutMs??xe),o.init({token:t,tds_method_container_element:this.methodContainer,challenge_container_element:d,use_default_challenge_iframe_style:!0,challenge_window_size:Fe()},this.buildOrderData()).then(i=>{var m,f;if(this.cleanup(),!(i!=null&&i.length)){s(this.fail("PagarMe 3DS returned no response"));return}const c=i[0],g=Object.values(N).find(u=>u===c.trans_status),E={transStatus:g,providerTransactionId:c.tds_server_trans_id,challengeCanceled:c.challenge_canceled};if(c.challenge_canceled){s(this.fail("3DS challenge canceled by user",E));return}g===N.Authenticated||g===N.Attempted?((f=(m=this.options).onComplete)==null||f.call(m),s({...E,status:P.Success,dsTransactionId:c.tds_server_trans_id})):s(this.fail(`3DS failed with status: ${c.trans_status}`,E))}).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 o;const{card:t,customer:a,billingAddress:r}=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:r?{country:r.country,state:r.state,city:r.city,zip_code:r.zipCode,line_1:`${r.number}, ${r.street}${r.district?`, ${r.district}`:""}`,line_2:r.complement??""}:void 0}},amount:this.amountInCents}],...a?{customer:{name:a.name,email:a.email,...a.document?{document:a.document}:{},...(o=a.phones)!=null&&o.length?{phones:Object.fromEntries(a.phones.map(d=>[d.type==="HOME"?"home_phone":"mobile_phone",{country_code:d.countryCode,area_code:d.areaCode,number:d.number}]))}:{}}}:{}}}}const Be="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js";class ze extends L{async authenticate(){var E,m,f;const{authToken:n,card:t,customer:a,currency:r,billingAddress:o}=this.data,d=this.amountInCents;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(!d)return this.fail("Missing amount for PagSeguro 3DS");if(!o)return this.fail("Missing billingAddress for PagSeguro 3DS");const s=this.data.environment===_.Sandbox?"SANDBOX":"PROD";try{await k(Be)}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 c=((E=a.phones)==null?void 0:E.map(u=>({country:u.countryCode,area:u.areaCode,number:u.number,type:u.type??"MOBILE"})))??[{country:"55",area:"11",number:"999999999",type:"MOBILE"}];c.some(u=>u.type==="MOBILE")||(c[0].type="MOBILE");try{const u=await i.authenticate3DS({data:{customer:{name:a.name,email:a.email,phones:c},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:d,currency:r??"BRL"},billingAddress:{street:o.street,number:o.number,complement:o.complement,regionCode:o.state,country:o.country.length===2?this.toAlpha3(o.country):o.country,city:o.city,postalCode:o.zipCode.replace(/\D/g,"")},dataOnly:!1}});return u.status==="AUTH_FLOW_COMPLETED"||u.status==="AUTH_NOT_SUPPORTED"?((f=(m=this.options).onComplete)==null||f.call(m),{status:P.Success,dsTransactionId:u.id}):u.status==="CHANGE_PAYMENT_METHOD"?this.fail("PagSeguro requires a different payment method"):{status:P.Success,dsTransactionId:u.id}}catch(u){return this.fail(u instanceof Error?u.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 He={[M.Lyra]:Oe,[M.MercadoPago]:Ne,[M.PagarMe]:Ke,[M.PagSeguro]:ze};class je 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 je(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 le{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:P.Success};const{acquirer:t}=this.data;if(!t)return{status:P.Failed,error:new Error("Missing 3DS acquirer")};const a=He[t];if(!a)return{status:P.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===P.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 Ve(e){let n=null;return{handleChallenge:async r=>{var s;if(!(r.status==="NeedChallenge"||r.statusDetail==="ThreeDsAwaitingChallenge"))return{status:P.Success};(s=e==null?void 0:e.onChallenge)==null||s.call(e),n=new le(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 qe extends Error{constructor(n,t){super(n),this.title=t,this.name="PayConductorTokenizerApiError"}}class $e{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 qe(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 We{constructor(n){this.input=n}}class Je extends We{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===z.Cpf?"CPF":"CNPJ",identificationNumber:this.input.customer.documentNumber})).id}}const Xe={[M.MercadoPago]:Je};class ue{constructor(n){p(this,"api");this.publicKey=n,this.api=new $e(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=Xe[s.key];if(!i)return null;const c=new i({...n,setting:s.settings});return await k(c.scriptUrl),{token:await c.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 Ze(e){const n=new ue(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=ae;exports.CardBrand=X;exports.ChargeStatusDetail=$;exports.CurrencyType=Z;exports.DeviceType=Q;exports.DocumentType=z;exports.ERROR_CODES=Se;exports.ErrorCode=te;exports.IFRAME_BASE_URL=ne;exports.IFRAME_DEFAULT_HEIGHT_VALUE=F;exports.IncomingMessage=T;exports.InputStyleKey=ee;exports.IntegrationProvider=M;exports.OrganizationEnvironment=_;exports.OutgoingMessage=I;exports.POST_MESSAGES=S;exports.PayConductor=ce;exports.PayConductor3DSSDK=le;exports.PayConductorCheckoutElement=Ie;exports.PayConductorThreeDSElement=Me;exports.PayConductorTokenizerSDK=ue;exports.PaymentMethod=G;exports.PaymentMethodLayout=V;exports.PaymentStatus=q;exports.REQUEST_TIMEOUT=re;exports.SKELETON_CSS=ie;exports.SKELETON_STYLE_ID=K;exports.ThreeDSResultStatus=J;exports.ThreeDSTransStatus=N;exports.ThreeDSecureResultStatus=P;exports.ThreeDsAuthenticationStatus=W;exports.buildIframeUrl=oe;exports.default=ce;exports.defaultTheme=we;exports.generateRequestId=se;exports.isValidOrigin=de;exports.loadScript=k;exports.usePayConductor=_e;exports.usePayconductorElement=De;exports.useThreeDS=Ve;exports.useTokenizer=Ze;
|
|
49
|
-
//# sourceMappingURL=index.cjs.js.map
|
|
1
|
+
"use strict";var ge=Object.defineProperty;var we=(e,a,t)=>a in e?ge(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t;var P=(e,a,t)=>we(e,typeof a!="symbol"?a+"":a,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("react/jsx-runtime"),I=require("react"),Se="https://app.payconductor.ai",pe="http://localhost:3000",V="https://iframe.payconductor.ai/v1",$="http://localhost:5175/v1",Pe=3e5,Ce="600px";var q=(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))(q||{}),W=(e=>(e.Grid="grid",e.Vertical="vertical",e.Horizontal="horizontal",e))(W||{}),J=(e=>(e.Succeeded="succeeded",e.Pending="pending",e.Failed="failed",e))(J||{}),X=(e=>(e.ThreeDsAwaitingChallenge="ThreeDsAwaitingChallenge",e))(X||{}),Z=(e=>(e.Authenticated="Authenticated",e.NotAuthenticated="NotAuthenticated",e.NeedChallenge="NeedChallenge",e))(Z||{}),Q=(e=>(e.Pending="Pending",e.Authenticated="Authenticated",e.Failed="Failed",e.NotEnrolled="NotEnrolled",e))(Q||{}),j=(e=>(e.Cpf="Cpf",e.Cnpj="Cnpj",e))(j||{}),v=(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.Lyra="Lyra",e))(v||{}),ee=(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))(ee||{}),x=(e=>(e.Production="Production",e.Sandbox="Sandbox",e))(x||{}),te=(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))(te||{}),ne=(e=>(e.Android="android",e.IOS="ios",e.Web="web",e.Chrome="chrome",e.Safari="safari",e))(ne||{}),ae=(e=>(e.Padding="padding",e.Radius="radius",e.Color="color",e.Background="background",e.Shadow="shadow",e))(ae||{}),M=(e=>(e.Init="Init",e.Config="Config",e.Update="Update",e.ConfirmPayment="ConfirmPayment",e.Validate="Validate",e.Reset="Reset",e))(M||{}),T=(e=>(e.Ready="Ready",e.Error="Error",e.CheckoutSessionCreated="CheckoutSessionCreated",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||{}),ie=(e=>(e.InvalidClient="InvalidClient",e.InvalidToken="InvalidToken",e.NetworkError="NetworkError",e.IframeNotReady="IframeNotReady",e.PaymentDeclined="PaymentDeclined",e.ValidationError="ValidationError",e.Timeout="Timeout",e))(ie||{});const be={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"},re=typeof window<"u"&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1")&&!window.location.search.includes("production"),oe=re?$:V,_=`${re?pe:Se}/api/v1/sdk`,se=[$,V],B=Ce,de=Pe,S={INIT:M.Init,CONFIG:M.Config,UPDATE:M.Update,CONFIRM_PAYMENT:M.ConfirmPayment,VALIDATE:M.Validate,RESET:M.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},Te={INVALID_CLIENT:"InvalidClient",INVALID_TOKEN:"InvalidToken",NETWORK_ERROR:"NetworkError",IFRAME_NOT_READY:"IframeNotReady",PAYMENT_DECLINED:"PaymentDeclined",VALIDATION_ERROR:"ValidationError",TIMEOUT:"Timeout"},K="payconductor-skeleton-style",ce=`
|
|
2
|
+
@keyframes payconductor-shimmer {
|
|
3
|
+
0% { background-position: -200% 0; }
|
|
4
|
+
100% { background-position: 200% 0; }
|
|
5
|
+
}
|
|
6
|
+
.payconductor-skeleton {
|
|
7
|
+
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
|
|
8
|
+
background-size: 200% 100%;
|
|
9
|
+
animation: payconductor-shimmer 1.5s infinite linear;
|
|
10
|
+
border-radius: 4px;
|
|
11
|
+
width: 100%;
|
|
12
|
+
}
|
|
13
|
+
`;function le(e){const a=new URLSearchParams({publicKey:e.publicKey});return`${oe}?${a.toString()}`}function ue(){return crypto.randomUUID()}function he(e,a){return a.some(t=>{try{return new URL(t).origin===e}catch{return t===e}})}function z(){return new Map}function R(e,a,t,n){return new Promise((i,r)=>{if(!e||!("contentWindow"in e)){r(new Error("Iframe not defined"));return}if(!(e!=null&&e.contentWindow)){r(new Error("Iframe not ready"));return}if(!a){r(new Error("Pending requests not initialized"));return}const s=ue();a.set(s,{resolve:i,reject:r}),e.contentWindow.postMessage({type:t,data:n,requestId:s},"*"),setTimeout(()=>{a!=null&&a.has(s)&&(a.delete(s),r(new Error("Request timeout")))},de)})}function Ae(e,a,t){return R(e,a,S.CONFIRM_PAYMENT,t)}async function Ie(e,a,t){return await Ae(e,a,{orderId:t.orderId})}function ve(e,a,t){return R(e,a,S.VALIDATE,t)}function Me(e,a){return R(e,a,S.RESET)}function _e(e,a,t){return R(e,a,S.CONFIG,t)}function De(e,a,t){return R(e,a,S.INIT,t)}function xe(e,a,t,n,i,r,s,d,o,c,w,E){const m=e.data,{requestId:f,type:u,data:g,error:b}=m;if(u===S.READY){if(n==null||n(),f&&(a!=null&&a.has(f))){const{resolve:A}=a.get(f);a.delete(f),A(g)}return}if(he(e.origin,se)){if(f&&a&&a.has(f)){const{resolve:A,reject:O}=a.get(f);a.delete(f),b?O(new Error(String(b.message))):A(g);return}if(u===S.ERROR){t((b==null?void 0:b.message)||"Unknown error"),i==null||i(new Error(String(b==null?void 0:b.message)));return}if(u===S.PAYMENT_COMPLETE){g&&typeof g=="object"&&"status"in g&&(r==null||r(g));return}if(u===S.PAYMENT_FAILED){g&&typeof g=="object"&&"status"in g&&(s==null||s(g));return}if(u===S.PAYMENT_PENDING){g&&typeof g=="object"&&"status"in g&&(d==null||d(g));return}if(u===S.PAYMENT_METHOD_SELECTED){g&&typeof g=="object"&&"paymentMethod"in g&&(o==null||o(g.paymentMethod));return}if(u!==S.RESIZE){if(u===T.ThreeDSChallenge){c==null||c();return}if(u===T.ThreeDSComplete){w==null||w();return}if(u===T.ThreeDSFailed){E==null||E();return}}}}function me(e){const[a,t]=I.useState(()=>!1),[n,i]=I.useState(()=>null),[r,s]=I.useState(()=>""),[d,o]=I.useState(()=>null);return I.useEffect(()=>{const c=(...h)=>{e.debug&&console.log("[PayConductor]",...h)},w=le({publicKey:e.publicKey});s(w),t(!0);const E=z();let m=!1;c("init",e.publicKey),c("iframeUrl",w);const f=()=>{var C,l;const h=(l=(C=window.PayConductor)==null?void 0:C.frame)==null?void 0:l.iframe;if(h){if(h instanceof HTMLIFrameElement)return h;if(typeof h=="object"&&h!==null){const y=h;if("current"in y&&y.current instanceof HTMLIFrameElement)return y.current;if("value"in y&&y.value instanceof HTMLIFrameElement)return y.value}return h}return document.querySelector(".payconductor-element iframe")??void 0},u={get iframe(){return document.querySelector(".payconductor-element iframe")??null},set iframe(h){},iframeUrl:w,error:null},g={publicKey:e.publicKey,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod},b={confirmPayment:h=>{var l;c("→ CONFIRM_PAYMENT",{orderId:h.orderId});const C=f();return C!=null&&C.contentWindow&&C.contentWindow.postMessage({type:S.CONFIG,data:{publicKey:e.publicKey,orderId:h.orderId,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig}},"*"),g.orderId=h.orderId,(l=window.PayConductor)!=null&&l.config&&(window.PayConductor.config.orderId=h.orderId),Ie(C,E,h)},validate:h=>(c("→ VALIDATE",h),ve(f(),E,h)),reset:()=>(c("→ RESET"),Me(f(),E)),getSelectedPaymentMethod:()=>d};window.PayConductor={frame:u,config:g,api:b,selectedPaymentMethod:d},c("registered"),window.dispatchEvent(new CustomEvent("payconductor:registered",{detail:window.PayConductor}));const A=async()=>{if(!m){const h=f();if(!h){c("→ CONFIG skipped: iframe not found");return}m=!0,c("→ CONFIG",{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons}),_e(h,E,{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig})}},O=h=>{var C;(C=h.data)!=null&&C.type&&c("←",h.data.type,h.data.data??""),xe(h,E,l=>{var y;i(l),u.error=l,(y=window.PayConductor)!=null&&y.frame&&(window.PayConductor.frame.error=l)},()=>{var l;(l=e.onReady)==null||l.call(e),A()},l=>{var y;(y=e.onError)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentComplete)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentFailed)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentPending)==null||y.call(e,l)},l=>{var y;o(l),window.PayConductor&&(window.PayConductor.selectedPaymentMethod=l),(y=e.onPaymentMethodSelected)==null||y.call(e,l)},()=>{var l;(l=e.onThreeDSChallenge)==null||l.call(e)},()=>{var l;(l=e.onThreeDSComplete)==null||l.call(e)},()=>{var l;(l=e.onThreeDSFailed)==null||l.call(e)})};window.addEventListener("message",O);const Ee=()=>{var C,l,y;const h=f();if(!h)return!1;try{if((((C=h.contentDocument)==null?void 0:C.readyState)??((y=(l=h.contentWindow)==null?void 0:l.document)==null?void 0:y.readyState))==="complete")return A(),!0}catch{}return!1},H=()=>{if(Ee())return;const h=f();if(h){h.addEventListener("load",()=>A(),{once:!0});return}setTimeout(H,50)};H()},[]),k.jsx("div",{className:"payconductor",id:"payconductor",style:{display:"contents"},children:e.children})}function Re(e){const a=I.useRef(null),[t,n]=I.useState(()=>""),[i,r]=I.useState(()=>!1),[s,d]=I.useState(()=>"");return I.useEffect(()=>{if(typeof document<"u"&&!document.getElementById(K)){const m=document.createElement("style");m.id=K,m.textContent=ce,document.head.appendChild(m)}const o=m=>{m!=null&&m.frame&&(n(m.frame.iframeUrl||""),r(!0),console.log("init",{PayConductor:window.PayConductor}))},c=typeof window<"u"?window.PayConductor:null;if(c)o(c);else{const m=f=>{o(f.detail),window.removeEventListener("payconductor:registered",m)};window.addEventListener("payconductor:registered",m)}let w=!1;const E=m=>{var f,u,g,b;if(((f=m.data)==null?void 0:f.type)===S.RESIZE&&((g=(u=m.data)==null?void 0:u.data)!=null&&g.height)&&d(m.data.data.height+"px"),((b=m.data)==null?void 0:b.type)===S.READY&&e.height&&!w){w=!0;const A=document.querySelector(".payconductor-element iframe");A!=null&&A.contentWindow&&A.contentWindow.postMessage({type:S.CONFIG,data:{height:e.height},requestId:"element-height"},"*")}};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]),k.jsxs("div",{className:"payconductor-element",style:{width:"100%"},children:[i?null:k.jsx("div",{className:"payconductor-skeleton",style:{height:e.height||B}}),i&&t?k.jsx("iframe",{allow:"payment",title:"PayConductor",ref:a,src:t,style:{width:"100%",height:e.height||s||B,border:"none"}}):null]})}function ke(e){const[a,t]=I.useState(()=>!1);return I.useEffect(()=>{const n=()=>{t(!0)},i=()=>{t(!1)};return window.addEventListener("payconductor:3ds:show",n),window.addEventListener("payconductor:3ds:hide",i),typeof window<"u"&&(window.PayConductor3DS={container:()=>document.getElementById("payconductor-3ds-container"),show:n,hide:i},window.dispatchEvent(new CustomEvent("payconductor:3ds:registered"))),()=>{window.removeEventListener("payconductor:3ds:show",n),window.removeEventListener("payconductor:3ds:hide",i),window.PayConductor3DS=null}},[]),k.jsx("div",{className:"payconductor-three-ds",id:"payconductor-3ds-container",style:{width:"100%",display:a?"block":"none",minHeight:a?e.height||"600px":"0"}})}function Ne(){const e=typeof window<"u"?window.PayConductor:null,a=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{...a,...t}}function U(e){var a;if((a=e==null?void 0:e.frame)!=null&&a.iframe){const t=e.frame.iframe;if(t instanceof HTMLIFrameElement)return t;if(t&&typeof t=="object"){if("current"in t){const n=t.current;if(n instanceof HTMLIFrameElement)return n}if("value"in t){const n=t.value;if(n instanceof HTMLIFrameElement)return n}}}return document.querySelector(".payconductor-element iframe")??null}function Le(){const e=()=>typeof window<"u"?window.PayConductor:null,a=(t,n)=>{const i=e();if(!i)return;const r=U(i);r!=null&&r.contentWindow&&r.contentWindow.postMessage({type:t,data:n},"*")};return{init:async t=>{const n=U(e()),i=z();return De(n||void 0,i,t)},confirmPayment:async t=>{if(!t.orderId)throw new Error("Order ID is required");const n=e();if(!(n!=null&&n.api))throw new Error("PayConductor not initialized");return n.api.confirmPayment(t)},validate:t=>{const n=e();return n?n.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 n=(i=e())==null?void 0:i.config;a(S.CONFIG,{publicKey:n==null?void 0:n.publicKey,orderId:n==null?void 0:n.orderId,theme:t.theme??(n==null?void 0:n.theme),locale:t.locale??(n==null?void 0:n.locale),paymentMethods:t.paymentMethods??(n==null?void 0:n.paymentMethods)})},updateOrderId:t=>{var i;const n=(i=e())==null?void 0:i.config;a(S.CONFIG,{publicKey:n==null?void 0:n.publicKey,orderId:t,theme:n==null?void 0:n.theme,locale:n==null?void 0:n.locale,paymentMethods:n==null?void 0:n.paymentMethods})},update:t=>{a(S.UPDATE,t)},submit:async()=>{const t=U(e()),n=z();try{return await R(t||void 0,n,S.CONFIRM_PAYMENT,{}),{paymentMethod:void 0}}catch(i){return{error:{message:i instanceof Error?i.message:"Payment failed",code:"payment_error",type:"payment_error"}}}}}}var p=(e=>(e.Success="Success",e.Failed="Failed",e.Timeout="Timeout",e))(p||{}),D=(e=>(e.Authenticated="Y",e.Attempted="A",e.ChallengeRequired="C",e.NotAuthenticated="N",e.Unavailable="U",e.Rejected="R",e.InformationOnly="I",e))(D||{});class N{constructor(a,t){P(this,"overlay",null);P(this,"modalContent",null);this.data=a,this.options=t}get amountInCents(){return this.data.amount===void 0?void 0:Math.round(this.data.amount*100)}fail(a,t={}){var i,r;const n=new Error(a);return(r=(i=this.options).onError)==null||r.call(i,n),{...t,status:"Failed",error:n}}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 a=document.createElement("style");a.id="payconductor-3ds-styles",a.textContent=`
|
|
14
|
+
#payconductor-3ds-overlay {
|
|
15
|
+
position: fixed;
|
|
16
|
+
inset: 0;
|
|
17
|
+
z-index: 99999;
|
|
18
|
+
display: flex;
|
|
19
|
+
align-items: center;
|
|
20
|
+
justify-content: center;
|
|
21
|
+
background: rgba(0, 0, 0, 0.6);
|
|
22
|
+
}
|
|
23
|
+
#payconductor-3ds-modal {
|
|
24
|
+
width: 500px;
|
|
25
|
+
max-width: 95vw;
|
|
26
|
+
min-height: 600px;
|
|
27
|
+
border-radius: 8px;
|
|
28
|
+
overflow: hidden;
|
|
29
|
+
background: #fff;
|
|
30
|
+
}
|
|
31
|
+
#payconductor-3ds-modal iframe {
|
|
32
|
+
width: 100%;
|
|
33
|
+
height: 600px;
|
|
34
|
+
border: none;
|
|
35
|
+
display: block;
|
|
36
|
+
}
|
|
37
|
+
@media only screen and (max-width: 600px) {
|
|
38
|
+
#payconductor-3ds-modal {
|
|
39
|
+
width: 100vw;
|
|
40
|
+
max-width: 100vw;
|
|
41
|
+
min-height: 440px;
|
|
42
|
+
border-radius: 0;
|
|
43
|
+
}
|
|
44
|
+
#payconductor-3ds-modal iframe {
|
|
45
|
+
height: 440px;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
`,document.head.appendChild(a)}}const Oe=5*60*1e3;class Ue extends N{constructor(){super(...arguments);P(this,"iframe",null);P(this,"messageListener",null);P(this,"timeoutId",null)}async authenticate(){const{threeDsUrl:t,creq:n}=this.data;if(!t||!n)return this.fail("Missing threeDsUrl or creq");const i=this.resolveContainer();return new Promise(r=>{var c;this.iframe=document.createElement("iframe"),this.iframe.name="payconductor-3ds-challenge",this.iframe.id="payconductor-3ds-challenge",i.appendChild(this.iframe),this.messageListener=w=>{var E,m,f;((E=w.data)==null?void 0:E.status)==="COMPLETE"&&(this.cleanup(),(f=(m=this.options).onComplete)==null||f.call(m),r({status:p.Success}))},window.addEventListener("message",this.messageListener),this.timeoutId=setTimeout(()=>{var w,E;this.cleanup(),(E=(w=this.options).onTimeout)==null||E.call(w),r({status:p.Timeout})},this.options.timeoutMs??Oe);const s=(c=this.iframe.contentWindow)==null?void 0:c.document;if(!s){this.cleanup(),r(this.fail("Cannot access iframe document"));return}const d=s.createElement("form");d.name="threeDsChallengeForm",d.setAttribute("target","payconductor-3ds-challenge"),d.setAttribute("method","post"),d.setAttribute("action",t);const o=s.createElement("input");o.setAttribute("type","hidden"),o.setAttribute("name","creq"),o.setAttribute("value",n),d.appendChild(o),this.iframe.appendChild(d),d.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 F=new Map;function L(e){const a=F.get(e);if(a)return a;const t=new Promise((n,i)=>{if(document.querySelector(`script[src="${e}"]`)){n();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>n(),r.onerror=()=>{F.delete(e),i(new Error(`Failed to load script: ${e}`))},(document.head||document.body).appendChild(r)});return F.set(e,t),t}const Fe="https://static.payzen.lat/static/js/authenticate-client/V1.0/kr-authenticate.umd.js",Be=10*60*1e3;class Ke extends N{constructor(){super(...arguments);P(this,"timeoutId",null)}async authenticate(){const{operationUrl:t,publicKey:n}=this.data;if(!t||!n)return this.fail("Missing operationUrl or publicKey");try{await L(Fe)}catch{return this.fail("Failed to load 3DS SDK")}const i=window.KrAuthenticate;return i?new Promise(r=>{this.timeoutId=setTimeout(()=>{var d,o;this.cleanup(),(o=(d=this.options).onTimeout)==null||o.call(d),r({status:p.Timeout})},this.options.timeoutMs??Be),new i(n).authenticate(t,()=>{var d,o;this.cleanup(),(o=(d=this.options).onComplete)==null||o.call(d),r({status:p.Success})})}):this.fail("KrAuthenticate not available")}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const ze={[x.Production]:"https://3ds-nx-js.stone.com.br/live/v2/3ds2.min.js",[x.Sandbox]:"https://3ds-nx-js.stone.com.br/test/v2/3ds2.min.js"},je=5*60*1e3;function He(){const e=window.innerWidth;return e<=480?"01":e<=768?"02":e<=1024?"03":"04"}class Ye extends N{constructor(){super(...arguments);P(this,"timeoutId",null);P(this,"methodContainer",null)}async authenticate(){const{authToken:t,card:n}=this.data;if(!t)return this.fail("Missing authToken for PagarMe 3DS");if(!n)return this.fail("Missing card data for PagarMe 3DS");const i=this.data.environment??x.Production;try{await L(ze[i])}catch{return this.fail("Failed to load Stone 3DS SDK")}const r=window.TDS;if(!r)return this.fail("Stone TDS SDK not available");const s=this.resolveContainer();return this.methodContainer=document.createElement("div"),this.methodContainer.style.display="none",document.body.appendChild(this.methodContainer),new Promise(d=>{this.timeoutId=setTimeout(()=>{var o,c;this.cleanup(),(c=(o=this.options).onTimeout)==null||c.call(o),d({status:p.Timeout})},this.options.timeoutMs??je),r.init({token:t,tds_method_container_element:this.methodContainer,challenge_container_element:s,use_default_challenge_iframe_style:!0,challenge_window_size:He()},this.buildOrderData()).then(o=>{var m,f;if(this.cleanup(),!(o!=null&&o.length)){d(this.fail("PagarMe 3DS returned no response"));return}const c=o[0],w=Object.values(D).find(u=>u===c.trans_status),E={transStatus:w,providerTransactionId:c.tds_server_trans_id,challengeCanceled:c.challenge_canceled};if(c.challenge_canceled){d(this.fail("3DS challenge canceled by user",E));return}w===D.Authenticated||w===D.Attempted?((f=(m=this.options).onComplete)==null||f.call(m),d({...E,status:p.Success,dsTransactionId:c.tds_server_trans_id})):d(this.fail(`3DS failed with status: ${c.trans_status}`,E))}).catch(o=>{this.cleanup(),d(this.fail(o instanceof Error?o.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 r;const{card:t,customer:n,billingAddress:i}=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:i?{country:i.country,state:i.state,city:i.city,zip_code:i.zipCode,line_1:`${i.number}, ${i.street}${i.district?`, ${i.district}`:""}`,line_2:i.complement??""}:void 0}},amount:this.amountInCents}],...n?{customer:{name:n.name,email:n.email,...n.document?{document:n.document}:{},...(r=n.phones)!=null&&r.length?{phones:Object.fromEntries(n.phones.map(s=>[s.type==="HOME"?"home_phone":"mobile_phone",{country_code:s.countryCode,area_code:s.areaCode,number:s.number}]))}:{}}}:{}}}}const Ge="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js";class Ve extends N{async authenticate(){var E,m,f;const{authToken:a,card:t,customer:n,currency:i,billingAddress:r}=this.data,s=this.amountInCents;if(!a)return this.fail("Missing authToken (session) for PagSeguro 3DS");if(!t)return this.fail("Missing card data for PagSeguro 3DS");if(!n)return this.fail("Missing customer data for PagSeguro 3DS");if(!s)return this.fail("Missing amount for PagSeguro 3DS");if(!r)return this.fail("Missing billingAddress for PagSeguro 3DS");const d=this.data.environment===x.Sandbox?"SANDBOX":"PROD";try{await L(Ge)}catch{return this.fail("Failed to load PagSeguro SDK")}const o=window.PagSeguro;if(!o)return this.fail("PagSeguro SDK not available");o.setUp({session:a,env:d});const c=((E=n.phones)==null?void 0:E.map(u=>({country:u.countryCode,area:u.areaCode,number:u.number,type:u.type??"MOBILE"})))??[{country:"55",area:"11",number:"999999999",type:"MOBILE"}];c.some(u=>u.type==="MOBILE")||(c[0].type="MOBILE");try{const u=await o.authenticate3DS({data:{customer:{name:n.name,email:n.email,phones:c},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:s,currency:i??"BRL"},billingAddress:{street:r.street,number:r.number,complement:r.complement,regionCode:r.state,country:r.country.length===2?this.toAlpha3(r.country):r.country,city:r.city,postalCode:r.zipCode.replace(/\D/g,"")},dataOnly:!1}});return u.status==="AUTH_FLOW_COMPLETED"||u.status==="AUTH_NOT_SUPPORTED"?((f=(m=this.options).onComplete)==null||f.call(m),{status:p.Success,dsTransactionId:u.id}):u.status==="CHANGE_PAYMENT_METHOD"?this.fail("PagSeguro requires a different payment method"):{status:p.Success,dsTransactionId:u.id}}catch(u){return this.fail(u instanceof Error?u.message:"PagSeguro 3DS failed")}}cleanup(){}toAlpha3(a){return{BR:"BRA",US:"USA",AR:"ARG",CL:"CHL",CO:"COL",MX:"MEX",PE:"PER",UY:"URY"}[a.toUpperCase()]??a}}const $e=5*60*1e3,Y="payconductor-3ds-sandbox-title";class G extends N{constructor(){super(...arguments);P(this,"timeoutId",null)}async authenticate(){const{authToken:t}=this.data;if(!t)return this.fail("Missing authToken for 3DS challenge");const n=this.resolveContainer();return new Promise(i=>{this.timeoutId=setTimeout(()=>{var r,s;this.cleanup(),(s=(r=this.options).onTimeout)==null||s.call(r),i({status:p.Timeout})},this.options.timeoutMs??$e),this.renderChallenge(n,{onConfirm:()=>{var r,s;this.cleanup(),(s=(r=this.options).onComplete)==null||s.call(r),i({status:p.Success,transStatus:D.Authenticated,providerTransactionId:t})},onCancel:()=>{this.cleanup(),i(this.fail("3DS challenge canceled by user",{challengeCanceled:!0}))}})})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.closeModal()}renderChallenge(t,n){const i=document.createElement("div");i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-labelledby",Y),i.style.cssText="min-height:inherit;box-sizing:border-box;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:32px;font-family:system-ui,-apple-system,sans-serif;text-align:center;color:#111827";const r=document.createElement("h2");r.id=Y,r.textContent="Autenticação 3DS (sandbox)",r.style.cssText="margin:0;font-size:20px";const s=document.createElement("p");s.textContent="Simulação do desafio do banco emissor. Confirme para aprovar a autenticação ou cancele para simular a desistência do comprador.",s.style.cssText="margin:0 0 8px;max-width:360px;font-size:14px;line-height:1.5;color:#4b5563";const d=this.createButton("Confirmar autenticação","background:#111827;color:#fff;border-color:#111827",n.onConfirm),o=this.createButton("Cancelar","background:#fff;color:#111827;border-color:#d1d5db",n.onCancel);i.append(r,s,d,o),t.appendChild(i),d.focus()}createButton(t,n,i){const r=document.createElement("button");return r.type="button",r.textContent=t,r.style.cssText=`width:100%;max-width:320px;padding:12px 16px;border:1px solid;border-radius:6px;font:inherit;font-size:14px;font-weight:600;cursor:pointer;${n}`,r.addEventListener("click",i),r}}const qe={[v.Lyra]:Ke,[v.MercadoPago]:Ue,[v.PagarMe]:Ye,[v.PagSeguro]:Ve,[v.Sandbox]:G,[v.SandboxSplit]:G};class We extends Error{constructor(a,t){super(a),this.title=t,this.name="PayConductorThreeDSApiError"}}class Je{constructor(a){this.publicKey=a}async completeManualChallenge(a,t){const n=await fetch(`${_}/three-ds/complete/${a}`,{method:"POST",headers:this.headers,body:JSON.stringify({providerTransactionId:t})});n.ok||await this.parseResponseError("Failed to complete native 3DS challenge",n)}async getThreeDSecureData(a){const t=await fetch(`${_}/three-ds/challenge/${a}`,{method:"GET",headers:this.headers});t.ok||await this.parseResponseError("Failed to fetch 3DS data",t);const n=await t.json();return Object.fromEntries(Object.entries(n).filter(([,i])=>i!=null))}async parseResponseError(a,t){var i,r,s,d;let n="";try{const o=await t.json();o!=null&&o.message?n=o.message:(i=o==null?void 0:o.error)!=null&&i.message?n=o.error:(s=(r=o==null?void 0:o.error)==null?void 0:r.value)!=null&&s.message?n=o.error.value.message:(d=o==null?void 0:o.value)!=null&&d.message?n=o.value.message:n=JSON.stringify(o)}catch{}throw new We(n,a)}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}const Xe=[v.PagSeguro];class fe{constructor(a){P(this,"data");P(this,"provider",null);P(this,"api");this.data=a,this.api=new Je(this.data.publicKey)}get needsChallenge(){return this.data.status==="NeedChallenge"||this.data.statusDetail==="ThreeDsAwaitingChallenge"}get acquirer(){return this.data.acquirer}async authenticate(a){var d;const t=await this.api.getThreeDSecureData(this.data.orderId);if(this.data={...this.data,...t},!this.needsChallenge)return{status:p.Success};const{acquirer:n}=this.data;if(!n)return{status:p.Failed,error:new Error("Missing 3DS acquirer")};const i=qe[n];if(!i)return{status:p.Failed,error:new Error(`Unsupported 3DS provider: ${n}`)};(d=a==null?void 0:a.onChallenge)==null||d.call(a);const r={...a,threeDSecure:this.data};this.provider=new i(this.data,r);const s=await this.provider.authenticate();return s.status===p.Success&&s.dsTransactionId&&Xe.includes(n)&&await this.api.completeManualChallenge(this.data.orderId,s.dsTransactionId),s}destroy(){this.provider&&(this.provider.cleanup(),this.provider=null)}}function Ze(e){let a=null;return{handleChallenge:async i=>{const r=new fe(i);a=r;try{return await r.authenticate({onChallenge:e==null?void 0:e.onChallenge,onComplete:e==null?void 0:e.onComplete,onError:e==null?void 0:e.onError,onTimeout:e==null?void 0:e.onTimeout})}finally{r.destroy(),a=null}},destroy:()=>{a==null||a.destroy(),a=null}}}class Qe extends Error{constructor(a,t){super(a),this.title=t,this.name="PayConductorTokenizerApiError"}}class et{constructor(a){this.publicKey=a}async getSettings(){const a=await fetch(`${_}/card-tokenization/settings`,{method:"GET",headers:this.headers});return a.ok||await this.parseResponseError("Failed to fetch settings",a),await a.json()}async createToken(a){const t=await fetch(`${_}/card-tokenization/tokenize`,{method:"POST",headers:this.headers,body:JSON.stringify(a)});return t.ok||await this.parseResponseError("Failed to generate token",t),await t.json()}async saveTokens(a,t,n){const i=await fetch(`${_}/card-tokenization/save-tokens/${t}/${n}`,{method:"POST",headers:this.headers,body:JSON.stringify(a)});i.ok||await this.parseResponseError("Failed to save tokens",i)}async parseResponseError(a,t){var i,r,s,d;let n="";try{const o=await t.json();o!=null&&o.message?n=o.message:(i=o==null?void 0:o.error)!=null&&i.message?n=o.error:(s=(r=o==null?void 0:o.error)==null?void 0:r.value)!=null&&s.message?n=o.error.value.message:(d=o==null?void 0:o.value)!=null&&d.message?n=o.value.message:n=JSON.stringify(o)}catch{}throw new Qe(n,a)}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}class tt{constructor(a){this.input=a}}class nt extends tt{constructor(){super(...arguments);P(this,"scriptUrl","https://sdk.mercadopago.com/js/v2")}async tokenize(){const{publicKey:t}=this.input.setting;if(typeof t!="string"||!t.trim())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 n=window.MercadoPago;if(!n)throw new Error("MercadoPago SDK not available");const i=new n(t.trim()),{expiration:r,cvv:s,number:d,holderName:o}=this.input.card,c=await i.createCardToken({cardExpirationMonth:String(r.month).padStart(2,"0"),cardExpirationYear:String(r.year),cardholderName:o,cardNumber:d,securityCode:s,identificationType:this.input.customer.documentType===j.Cpf?"CPF":"CNPJ",identificationNumber:this.input.customer.documentNumber}).catch(w=>{throw new Error(this.describeMercadoPagoError(w))});if("id"in c&&c.id)return c.id;throw new Error(this.describeMercadoPagoError(c))}describeMercadoPagoError(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.describeMercadoPagoError(n)).join("; ");if(typeof t=="object"&&t!==null){if("cause"in t&&Array.isArray(t.cause)&&t.cause.length>0)return this.describeMercadoPagoError(t.cause);if("message"in t&&typeof t.message=="string")return t.message;if("description"in t&&typeof t.description=="string")return t.description}return"Failed to tokenize card"}}const at={[v.MercadoPago]:nt};class ye{constructor(a){P(this,"api");this.publicKey=a,this.api=new et(this.publicKey)}async tokenizeCard(a){this.validateCard(a);const{customerId:t,token:n}=await this.api.createToken({card:a.card,customer:a.customer,saveCard:!1}),{settings:i}=await this.api.getSettings(),s=(await Promise.all(i.map(async d=>{const o=at[d.key];if(!o)return null;const c=new o({...a,setting:d.settings});return await L(c.scriptUrl),{token:await c.tokenize(),integrationId:d.integrationId,providerKey:d.key}}))).filter(d=>d!==null);return s.length>0&&await this.api.saveTokens(s,t,n),n}validateCard(a){const{number:t,cvv:n,expiration:i,holderName:r}=a.card;if(!t||!n||!(i!=null&&i.month)||!(i!=null&&i.year)||!r)throw new Error("Invalid card data")}}function it(e){const a=new ye(e.publicKey);return{tokenizeCard:async n=>{var i,r;try{const s=await a.tokenizeCard(n);return(i=e.onSuccess)==null||i.call(e,s),s}catch(s){const d=s instanceof Error?s:new Error("Tokenization failed");return(r=e.onError)==null||r.call(e,d),null}}}}exports.ALLOWED_ORIGINS=se;exports.CardBrand=ee;exports.ChargeStatusDetail=X;exports.CurrencyType=te;exports.DeviceType=ne;exports.DocumentType=j;exports.ERROR_CODES=Te;exports.ErrorCode=ie;exports.IFRAME_BASE_URL=oe;exports.IFRAME_DEFAULT_HEIGHT_VALUE=B;exports.IncomingMessage=T;exports.InputStyleKey=ae;exports.IntegrationProvider=v;exports.OrganizationEnvironment=x;exports.OutgoingMessage=M;exports.POST_MESSAGES=S;exports.PayConductor=me;exports.PayConductor3DSSDK=fe;exports.PayConductorCheckoutElement=Re;exports.PayConductorThreeDSElement=ke;exports.PayConductorTokenizerSDK=ye;exports.PaymentMethod=q;exports.PaymentMethodLayout=W;exports.PaymentStatus=J;exports.REQUEST_TIMEOUT=de;exports.SDK_API_BASE_URL=_;exports.SKELETON_CSS=ce;exports.SKELETON_STYLE_ID=K;exports.ThreeDSResultStatus=Q;exports.ThreeDSTransStatus=D;exports.ThreeDSecureResultStatus=p;exports.ThreeDsAuthenticationStatus=Z;exports.buildIframeUrl=le;exports.default=me;exports.defaultTheme=be;exports.generateRequestId=ue;exports.isValidOrigin=he;exports.loadScript=L;exports.usePayConductor=Ne;exports.usePayconductorElement=Le;exports.useThreeDS=Ze;exports.useTokenizer=it;
|
|
49
|
+
//# sourceMappingURL=index.cjs.js.map
|