@payconductor/react 1.2.4 → 1.2.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 +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +22 -22
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -45,5 +45,5 @@
|
|
|
45
45
|
height: 440px;
|
|
46
46
|
}
|
|
47
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;
|
|
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.threeDSecure).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
49
|
//# sourceMappingURL=index.cjs.js.map
|