@paypercut/checkout-js 1.2.9 → 1.2.11
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.
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var PaypercutCheckout=function(){"use strict";class e{constructor(){this.handlers=new Map}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}once(e,t){const i=(...n)=>{t(...n),this.off(e,i)};return this.on(e,i)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,...t){this.handlers.get(e)?.forEach(i=>{try{i(...t)}catch(t){console.error(`[Emitter] Error in ${e} handler:`,t)}})}hasListeners(e){const t=this.handlers.get(e);return!!t&&t.size>0}clear(){this.handlers.clear()}}const t={version:"1.2.9",defaultCheckoutOrigin:"https://buy.paypercut.io",defaultApiOrigin:"https://api.paypercut.io",defaultVaultApiUrl:"https://api.basistheory.com",allowedOrigins:["https://buy.paypercut.io"]};function i(e){return t.allowedOrigins.includes(e)}function n(e){return t.defaultCheckoutOrigin}function a(e){return t.defaultApiOrigin}function s(){return t.defaultVaultApiUrl}function o(){const e="undefined"!=typeof window?window.visualViewport:void 0,t="undefined"!=typeof document?document.documentElement:void 0;return{width:e?.width||window.innerWidth||t?.clientWidth||window.screen?.width||460,height:e?.height||window.innerHeight||t?.clientHeight||window.screen?.height||680}}function r(e,t,i){const n=Math.min(t,i);return Math.min(Math.max(e,n),i)}class l{constructor(e){this.options=e,this.modal=null,this.shell=null,this.iframe=null,this.frameSize={},this.resizeHandler=null,this.pendingData=null}show(e){this.close(),this.modal=function(e){const t=document.createElement("div"),i=o();return t.id=e,Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:`${i.width}px`,height:`${i.height}px`,minHeight:`${i.height}px`,display:"flex",alignItems:"center",justifyContent:"center",zIndex:"999999",background:"rgba(0, 0, 0, 0.56)",padding:"16px",boxSizing:"border-box",overflow:"hidden"}),t}(this.options.modalId),this.shell=function(e){const t=document.createElement("div");Object.assign(t.style,{position:"relative",borderRadius:"6px",background:"transparent",boxShadow:"0 24px 64px rgba(0, 0, 0, 0.36), 0 2px 10px rgba(0, 0, 0, 0.18)",overflow:"visible"});const i=document.createElement("iframe");i.allow="payment *",i.setAttribute("frameborder","0"),Object.assign(i.style,{border:"none",borderRadius:"6px",display:"block",background:"transparent",maxWidth:"100%",maxHeight:"100%"});const n=document.createElement("button");n.type="button",n.textContent="Cancel",n.setAttribute("aria-label","Cancel 3D Secure authentication"),Object.assign(n.style,{position:"absolute",top:"-40px",right:"0",zIndex:"2",height:"28px",padding:"0 10px",border:"0",borderRadius:"999px",background:"rgba(17, 24, 39, 0.56)",color:"#ffffff",font:'600 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',letterSpacing:"0.04em",textTransform:"uppercase",cursor:"pointer",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.24)",transform:"translateY(0) scale(1)",transition:window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"none":"transform 300ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow 300ms cubic-bezier(0.22, 1, 0.36, 1), background 300ms cubic-bezier(0.22, 1, 0.36, 1)",willChange:"transform"});const a=()=>{n.style.background="rgba(17, 24, 39, 0.56)",n.style.boxShadow="0 4px 16px rgba(0, 0, 0, 0.24)",n.style.transform="translateY(0) scale(1)"},s=()=>{n.style.background="rgba(17, 24, 39, 0.68)",n.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.26)",n.style.transform="translateY(-1px) scale(1.025)"};return n.addEventListener("mouseenter",s),n.addEventListener("focus",s),n.addEventListener("mouseleave",a),n.addEventListener("blur",a),n.addEventListener("mouseup",s),n.addEventListener("mousedown",()=>{n.style.background="rgba(17, 24, 39, 0.72)",n.style.boxShadow="0 3px 12px rgba(0, 0, 0, 0.22)",n.style.transform="translateY(0) scale(0.985)"}),n.addEventListener("click",e),t.appendChild(i),t.appendChild(n),{shell:t,iframe:i,cancelButton:n}}(()=>this.options.onCancel()),this.iframe=this.shell.iframe,this.iframe.src=this.options.buildUrl(e),this.frameSize={},this.applySize(),this.modal.appendChild(this.shell.shell),document.body.appendChild(this.modal),this.resizeHandler=()=>this.applySize(),window.addEventListener("resize",this.resizeHandler),window.addEventListener("orientationchange",this.resizeHandler),window.visualViewport?.addEventListener("resize",this.resizeHandler),this.pendingData=e}handleFrameResize(e,t){if(!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow)return;const i=function(e){if(!e||"object"!=typeof e)return null;const t=e,i={};return"number"==typeof t.width&&Number.isFinite(t.width)&&t.width>0&&(i.width=t.width),"number"==typeof t.height&&Number.isFinite(t.height)&&t.height>0&&(i.height=t.height),i.width||i.height?i:null}(t);i&&(this.frameSize={...this.frameSize,...i},this.applySize())}handleReady(){return!(!this.pendingData||!this.iframe?.contentWindow)&&(this.options.onReady(this.iframe,this.pendingData),!0)}close(){this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),window.removeEventListener("orientationchange",this.resizeHandler),window.visualViewport?.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),this.modal&&(this.modal.remove(),this.modal=null),this.shell=null,this.iframe=null,this.frameSize={},this.pendingData=null}applySize(){!function(e,t,i={},n){if(!e||!t)return i;const a=o(),s=Math.min(860,Math.max(0,a.width-32)),l=Math.min(860,Math.max(0,a.height-112)),p=i.width??460,h=i.height??680,d=r(p,320,s),c=r(h,300,l);e.style.width=`${a.width}px`,e.style.height=`${a.height}px`,e.style.minHeight=`${a.height}px`,t.style.width=`${Math.round(d)}px`,t.style.height=`${Math.round(c)}px`,n&&(n.style.width=`${Math.round(d)}px`,n.style.height=`${Math.round(c)}px`)}(this.modal,this.iframe,this.frameSize,this.shell?.shell)}}const p=new Set(["bg","bg-BG","en","en-GB","el","el-GR","ro","ro-RO","hr","hr-HR","pl","pl-PL","cs","cs-CZ","sl","sl-SI","sk","sk-SK","hu","hu-HU"]);function h(e){return e&&"auto"!==e?p.has(e)?e:(console.warn(`[PaypercutCheckout] Locale "${e}" is not supported. Falling back to "en".`),"en"):"en"}var d,c,u,y;function m(e){return Object.values(c).includes(e)}function g(e){return Object.values(u).includes(e)}function P(e){var t;if(e)return t=e,Object.values(d).includes(t)?e:void console.warn(`[PaypercutCheckout] Invalid ui_mode: "${e}". Valid options: ${Object.values(d).join(", ")}`)}!function(e){e.EMBEDDED="embedded"}(d||(d={})),function(e){e.CARD="card"}(c||(c={})),function(e){e.APPLE_PAY="apple_pay",e.GOOGLE_PAY="google_pay"}(u||(u={})),function(e){e.Loaded="loaded",e.Processing="processing",e.Success="success",e.Error="error",e.Expired="expired",e.Resize="resize",e.ThreeDSComplete="threeds_complete",e.ThreeDSError="threeds_error",e.ThreeDSCanceled="threeds_canceled",e.ThreeDSStarted="threeds_started",e.Cancel="cancel",e.FormValidation="form_validation"}(y||(y={}));const f="APPLE_PAY_START",S="APPLE_PAY_VALIDATE_MERCHANT",C="APPLE_PAY_MERCHANT_SESSION",b="APPLE_PAY_MERCHANT_ERROR",w="APPLE_PAY_PAYMENT_DATA",E="APPLE_PAY_PAYMENT_RESULT",A="APPLE_PAY_CANCELLED",v="APPLE_PAY_SESSION_ERROR",I=new Set(["ar","bg","ca","cs","da","de","el","en","es","et","fi","fr","hr","id","it","ja","ko","ms","nl","no","pl","pt","ru","sk","sl","sr","sv","th","tr","uk","zh"]);function k(e){return e||"en"}function T(e){const t=e.split("-")[0].toLowerCase();return I.has(t)?t:"en"}var D;function _(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function x(e){return e.startsWith("pk_live_")}!function(e){e.Ready="ready",e.Click="click",e.SessionStart="session_start",e.ShippingOptionsRequired="shipping_options_required",e.ShippingAddressChange="shipping_address_change",e.ShippingOptionChange="shipping_option_change",e.PaymentMethodCreated="payment_method_created",e.PaymentMethodFailed="payment_method_failed",e.Cancel="cancel",e.Error="error"}(D||(D={}));let R=null;function O(){return R||(R=new Promise(e=>{if("undefined"==typeof window)return void e();if(customElements?.get("apple-pay-button"))return void e();const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.async=!0,t.onload=()=>e(),t.onerror=()=>e(),document.head.appendChild(t)}),R)}let M=null;function L(){return M||(M=new Promise((e,t)=>{if("undefined"==typeof window)return void t(new Error("No window"));if(globalThis.google?.payments?.api?.PaymentsClient)return void e();const i=document.createElement("script");i.src="https://pay.google.com/gp/p/js/pay.js",i.async=!0,i.onload=()=>e(),i.onerror=()=>t(new Error("Failed to load Google Pay script")),document.head.appendChild(i)}),M)}function G(e,t,i="DE"){const n={};return void 0!==e.amount&&(n.newTransactionInfo={totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:(e.amount/100).toFixed(2),currencyCode:t,countryCode:i}),e.shippingOptions?.length&&(n.newShippingOptionParameters={defaultSelectedOptionId:e.shippingOptions[0].id,shippingOptions:e.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${t}`}))}),"invalid_shipping_address"===e.status?n.error={reason:"SHIPPING_ADDRESS_UNSERVICEABLE",message:"Cannot ship to this address.",intent:"SHIPPING_ADDRESS"}:"invalid_shipping_option"===e.status&&(n.error={reason:"SHIPPING_OPTION_INVALID",message:"This shipping option is not available.",intent:"SHIPPING_OPTION"}),n}function z(e){return"checkout"===e?"check-out":e}class U{constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.sessionActive=!1,this.tokenizeIframe=null,this.wrapper=null,this.applePayContainer=null,this.applePayButtonEl=null,this.gpayContainer=null,this.gpayClient=null,this.gpayPaymentRequest=null,this.gpayCurrentAmount=0,this.preferredLayout="row",this.layoutResizeObserver=null,this.instanceId=_(),this.idempotencyKey=_(),this.pending3DSAfterGpay=null,this.applePaySession=null,this.applePayCurrentAmount=0,this.currentLineItems=[],this.applePayCurrentShippingOptions=[],this.applePayPendingShippingOption=null,this.applePayPendingCallback=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.expressConfig=null,this.pendingGpayResolve=null,this.pendingGpayReject=null,this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,this.currentShippingOptions=t.shippingOptions??[],this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-express-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler)}buildTokenizeSrc(){const e=n(this.options.hostedCheckoutUrl),t=new URL("/express/tokenize",e);return t.searchParams.set("instanceId",this.instanceId),t.searchParams.set("liveMode",String(x(this.options.publishableKey))),t.toString()}async fetchExpressConfig(){const e=a(this.options.apiUrl),t=new URL("/v1/elements/sessions",e),{amount:i}=this.options;t.searchParams.set("type","deferred_intent"),t.searchParams.set("key",this.options.publishableKey),t.searchParams.set("deferred_intent[mode]","payment"),t.searchParams.set("deferred_intent[currency]",this.options.currency),null!=i&&t.searchParams.set("deferred_intent[amount]",`${i}`),t.searchParams.set("referrer_host",window.location.hostname);try{const e=await fetch(t.toString(),{cache:"no-store"});if(!e.ok)throw new Error(`Config fetch failed: HTTP ${e.status}`);const i=await e.json(),n=x(this.options.publishableKey),a="BCR2DN5T735375Y7",o=i.payment_domain?.wallets?.google_pay?.merchant_ref??"",r=i.payment_domain?.wallets?.google_pay?.status??"inactive";this.expressConfig={tenantId:i.payment_domain?.wallet_provider?.tenant_id??"",publicKey:i.payment_domain?.wallet_provider?.public_key??"",vaultApiUrl:s(),googlePayMerchantId:n?"active"===r?o:a:o||a,googlePayStatus:r,applePayStatus:i.payment_domain?.wallets?.apple_pay?.status??"inactive",displayName:i.merchant?.name??"",merchantMid:i.merchant?.mid??"",merchantMcc:i.merchant?.mcc??"",merchantCountry:i.merchant?.country??"",merchantUrl:i.merchant?.business_url??""}}catch(e){console.error("[PaypercutExpressCheckout] Failed to fetch express config:",e)}}onMessage(e){if(!i(e.origin))return void(e.origin.includes("localhost")&&console.warn("[PaypercutExpressCheckout] Message blocked — origin not allowed:",e.origin));const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.instanceId||t.instanceId===this.instanceId))switch(t.type){case"TOKENIZE_RESPONSE":if("apple_pay"===t.wallet)t.success?this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"apple_pay"}).then(e=>{this.completeApplePaySession(!0),this.emitter.emit(D.PaymentMethodCreated,{paymentMethodId:e,wallet:"apple_pay",billingDetails:this.applePayPendingBillingDetails??void 0,shippingDetails:this.applePayPendingShippingDetails??void 0,selectedShippingOption:this.applePayPendingShippingOption??void 0}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}).catch(e=>{this.completeApplePaySession(!1),this.emitter.emit(D.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(D.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}):(this.completeApplePaySession(!1),this.emitter.emit(D.Error,new Error(t.error??"Apple Pay payment failed")),this.emitter.emit(D.PaymentMethodFailed,{error:t.error??"Apple Pay payment failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null);else if(t.success)this.pendingGpayResolve?(this.pendingGpayResolve(t),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"google_pay"}).then(e=>{this.emitter.emit(D.PaymentMethodCreated,{paymentMethodId:e,wallet:"google_pay",billingDetails:this.pendingGpayBillingDetails??void 0,shippingDetails:this.pendingGpayShippingDetails??void 0,selectedShippingOption:this.pendingGpayShippingOption})}).catch(e=>{this.emitter.emit(D.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(D.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"})}).finally(()=>{this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0});else if(this.pendingGpayReject)this.pendingGpayReject(new Error(t.error??"Tokenization failed")),this.pendingGpayResolve=null,this.pendingGpayReject=null;else{const e=t.error??"Google Pay payment failed";e.toLowerCase().includes("cancel")?this.emitter.emit(D.Cancel):(this.emitter.emit(D.Error,new Error(e)),this.emitter.emit(D.PaymentMethodFailed,{error:e})),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0}break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.pendingGpayResolve?(this.pending3DSAfterGpay=t,this.pendingGpayResolve({__closeSheet:!0}),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.threeDSModal.show(t);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":case"THREEDS_CANCELED":case"THREEDS_ERROR":this.postToTokenizeIframe(t),this.threeDSModal.close()}}mount(e){if(this.mounted)return void console.warn("[PaypercutExpressCheckout] mount() called but already mounted — ignoring");const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error(`[PaypercutExpressCheckout] Container not found: ${e}`);const i=this.options.walletOptions?.length?this.options.walletOptions:[u.APPLE_PAY,u.GOOGLE_PAY],n=i.includes(u.APPLE_PAY),a=i.includes(u.GOOGLE_PAY),s=this.options.layout??"auto";this.preferredLayout="auto"===s?"row":s;const o=document.createElement("div");this.wrapper=o,Object.assign(o.style,{display:"flex",flexDirection:"row"===this.preferredLayout?"row":"column",gap:"8px",width:"100%"}),a&&(this.gpayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.gpayContainer),o.appendChild(this.gpayContainer),L().catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)})),n&&(this.applePayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.applePayContainer),o.appendChild(this.applePayContainer),O()),t.appendChild(o),"auto"===s&&"undefined"!=typeof ResizeObserver&&(this.layoutResizeObserver=new ResizeObserver(e=>{const i=e[0]?.contentRect.width??t.offsetWidth;this.applyLayout(i<=540?"column":"row")}),this.layoutResizeObserver.observe(t));const r=this.buildTokenizeSrc();this.tokenizeIframe=document.createElement("iframe"),this.tokenizeIframe.id="paypercut-express-tokenize-iframe",this.tokenizeIframe.src=r,this.tokenizeIframe.setAttribute("frameborder","0"),this.tokenizeIframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin"),Object.assign(this.tokenizeIframe.style,{position:"absolute",top:"-9999px",left:"-9999px",width:"1px",height:"1px",border:"none",visibility:"hidden"}),document.body.appendChild(this.tokenizeIframe),this.mounted=!0,this.fetchExpressConfig().then(async()=>{if(this.destroyed)return;const e=this.expressConfig;n&&this.applePayContainer&&"active"===e?.applePayStatus?await this.mountApplePayButton(this.applePayContainer):this.applePayContainer&&this.removeApplePayContainer(),a&&e&&this.mountGooglePayFromConfig(),this.emitter.emit(D.Ready)})}applyLayoutToContainers(e,...t){for(const i of t)i&&(i.style.flex="row"===e?"1":"",i.style.minWidth="row"===e?"0":"",i.style.width="row"===e?"":"100%")}applyLayout(e){this.wrapper&&(this.wrapper.style.flexDirection="row"===e?"row":"column",this.applyLayoutToContainers(e,this.applePayContainer,this.gpayContainer))}setLayout(e){this.preferredLayout=e,this.applyLayout(e)}setLocale(e){this.options.locale=e,this.applePayButtonEl&&this.applePayButtonEl.setAttribute("locale",k(e)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest&&this.setButtonOptions({})}setButtonOptions(e){this.options.buttonOptions={...this.options.buttonOptions,...e};const t=this.options.buttonOptions;if(this.applePayButtonEl&&(void 0!==e.applePayStyle&&this.applePayButtonEl.setAttribute("buttonstyle",e.applePayStyle),void 0!==e.type&&this.applePayButtonEl.setAttribute("type",z(e.type)),void 0!==e.borderRadius&&this.applePayButtonEl.style.setProperty("--apple-pay-button-border-radius",e.borderRadius)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest){this.gpayContainer.innerHTML="";const e=this.gpayClient.createButton({onClick:()=>this.startGooglePay(this.gpayPaymentRequest),buttonSizeMode:"fill",buttonType:t?.type??"plain",buttonColor:t?.googlePayColor??"default",...this.options.locale&&{buttonLocale:T(this.options.locale)}}),i=t?.borderRadius??"0.5rem";e.style.width="100%",this.injectGpayInnerStyles(e,i),this.gpayContainer.appendChild(e)}}async mountApplePayButton(e){await O();const t=window.ApplePaySession;if(!t)return void console.log("[PaypercutExpressCheckout] ApplePaySession not available");if(!t.canMakePayments?.())return void console.log("[PaypercutExpressCheckout] ApplePaySession.canMakePayments() returned false — hiding Apple Pay button");const i=this.options.locale?k(this.options.locale):"en",n=this.options.buttonOptions,a=document.createElement("apple-pay-button");a.setAttribute("buttonstyle",n?.applePayStyle??"black"),a.setAttribute("type",z(n?.type??"plain")),a.setAttribute("locale",i),a.style.setProperty("--apple-pay-button-width","100%"),a.style.setProperty("--apple-pay-button-height","48px"),a.style.setProperty("--apple-pay-button-border-radius",n?.borderRadius??"0.5rem"),a.style.display="block",a.style.cursor="pointer",a.addEventListener("click",()=>this.startApplePay());const s=()=>{this.applePayButtonEl=a,e.appendChild(a);const t=a.shadowRoot;if(t){const e=document.createElement("style");e.textContent="span svg { height: 75% !important; width: auto !important; }",t.appendChild(e)}};customElements?.get("apple-pay-button")?s():customElements?.whenDefined("apple-pay-button").then(s).catch(()=>s())}async startApplePay(){if(this.sessionActive)return;if("undefined"==typeof window)return;const e=window.ApplePaySession;if(!e)return void console.error("[PaypercutExpressCheckout] ApplePaySession not available");this.idempotencyKey=_(),this.setSessionActive(!0),this.emitter.emit(D.Click);const t=await new Promise(e=>{if(!this.emitter.hasListeners(D.SessionStart))return void e(null);const t=setTimeout(()=>e(null),3e3);this.emitter.emit(D.SessionStart,{wallet:"apple_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return console.error("[PaypercutExpressCheckout] Apple Pay: no session_start response — aborting"),this.setSessionActive(!1),void this.emitter.emit(D.ShippingOptionsRequired,{wallet:"apple_pay"});"number"==typeof t.amount?this.applePayCurrentAmount=t.amount:this.applePayCurrentAmount=this.options.amount,Array.isArray(t.lineItems)?this.currentLineItems=t.lineItems:this.currentLineItems=this.options.lineItems??[],Array.isArray(t.shippingOptions)?this.applePayCurrentShippingOptions=t.shippingOptions:this.applePayCurrentShippingOptions=this.currentShippingOptions,this.applePayPendingShippingOption=null;const i=this.expressConfig?.displayName||"Checkout",n=(this.applePayCurrentAmount/100).toFixed(2),a=this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})),o={countryCode:this.options.countryCode??"DE",currencyCode:this.options.currency,merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],lineItems:a,total:{label:i,amount:n,type:"final"},requiredBillingContactFields:["postalAddress","name","email"],requiredShippingContactFields:["postalAddress","name","email"]};this.applePayCurrentShippingOptions.length&&(o.shippingMethods=this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:(e.amount/100).toFixed(2),identifier:e.id}))),o.shippingType="shipping",this.abortApplePaySession();const r=e.supportsVersion?.(14)?14:3;try{const t=new e(r,o);this.applePaySession=t,t.onvalidatemerchant=async e=>{const n=this.expressConfig?.vaultApiUrl??s(),a=this.expressConfig?.publicKey??"";try{const s={"Content-Type":"application/json","BT-API-KEY":a};this.idempotencyKey&&(s["Idempotency-Key"]=this.idempotencyKey);const o=await fetch(`${n}/apple-pay/session`,{method:"POST",headers:s,body:JSON.stringify({display_name:i,domain:window.location.host,validation_url:e.validationURL})});if(!o.ok){const e=await o.json().catch(()=>({}));throw new Error(e?.message??`Merchant validation failed: HTTP ${o.status}`)}const r=await o.json();t.completeMerchantValidation(r)}catch(e){console.error("[PaypercutExpressCheckout] Apple Pay merchant validation failed"),this.abortApplePaySession(),this.emitter.emit(D.Error,new Error(e?.message??"Apple Pay merchant validation failed")),this.emitter.emit(D.Cancel)}},t.onshippingcontactselected=async n=>{const a=n.shippingContact,s=await new Promise(e=>{this.applePayPendingCallback={type:"contact",resolve:e},this.emitter.emit(D.ShippingAddressChange,{address:{country:a.countryCode??"",state:a.administrativeArea,city:a.locality,postalCode:a.postalCode},updateWith:e=>this.update(e)}),setTimeout(()=>e({}),3e4)});this.applePayPendingCallback=null,"number"==typeof s.amount&&(this.applePayCurrentAmount=s.amount),Array.isArray(s.lineItems)&&(this.currentLineItems=s.lineItems),Array.isArray(s.shippingOptions)&&(this.applePayCurrentShippingOptions=s.shippingOptions);const o="invalid_shipping_address"===s.status?e.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS:e.STATUS_SUCCESS;try{t.completeShippingContactSelection(o,this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:(e.amount/100).toFixed(2),identifier:e.id})),{label:i,amount:(this.applePayCurrentAmount/100).toFixed(2),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingContactSelection failed",e)}},t.onshippingmethodselected=async n=>{const a=n.shippingMethod,s={id:a.identifier,label:a.label,detail:a.detail,amount:Math.round(100*parseFloat(a.amount))};this.applePayPendingShippingOption=s;const o=await new Promise(e=>{this.applePayPendingCallback={type:"method",resolve:e},this.emitter.emit(D.ShippingOptionChange,{shippingOption:s,updateWith:e=>this.update(e)}),setTimeout(()=>e({}),3e4)});this.applePayPendingCallback=null,"number"==typeof o.amount&&(this.applePayCurrentAmount=o.amount),Array.isArray(o.lineItems)&&(this.currentLineItems=o.lineItems);try{t.completeShippingMethodSelection(e.STATUS_SUCCESS,{label:i,amount:(this.applePayCurrentAmount/100).toFixed(2),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingMethodSelection failed",e)}},t.onpaymentauthorized=e=>{const t=e.payment?.billingContact,i=e.payment?.shippingContact;this.applePayPendingBillingDetails=t?{name:[t.givenName,t.familyName].filter(Boolean).join(" ")||void 0,email:t.emailAddress,address:{line1:t.addressLines?.[0],line2:t.addressLines?.[1],city:t.locality,state:t.administrativeArea,postalCode:t.postalCode,country:t.countryCode}}:null,this.applePayPendingShippingDetails=i?{name:[i.givenName,i.familyName].filter(Boolean).join(" ")||void 0,address:{line1:i.addressLines?.[0],line2:i.addressLines?.[1],city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode}}:null,this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"apple_pay",applePaymentData:e.payment.token,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:this.applePayPendingBillingDetails,amount:this.applePayCurrentAmount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})},t.oncancel=()=>{this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.emitter.emit(D.Cancel)},t.begin()}catch(e){this.applePaySession=null,console.error("[PaypercutExpressCheckout] Failed to create ApplePaySession",{name:e?.name,message:e?.message,hint:"SecurityError"===e?.name?"Page is not HTTPS or merchant domain is not registered for Apple Pay":"Check isSecureContext and that ApplePaySession.canMakePayments() returns true"})}}removeGpayContainer(){this.gpayContainer?.remove(),this.gpayContainer=null}removeApplePayContainer(){this.applePayContainer?.remove(),this.applePayContainer=null,this.applePayButtonEl=null}mountGooglePayFromConfig(){const e=this.expressConfig;if(!e)return;const t=x(this.options.publishableKey),i=e.tenantId,n=e.googlePayMerchantId,a=e.displayName||"Checkout";return i?n?(console.log({liveMode:t}),!t||e.merchantMcc&&e.merchantUrl?void L().then(()=>{this.mountGooglePayButton(i,n,a,t)}).catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)}):(console.warn("[PaypercutExpressCheckout] Google Pay disabled!"),void this.removeGpayContainer())):(console.warn("[PaypercutExpressCheckout] googlePayMerchantId is empty — Google Pay will not be mounted (merchant may not have Google Pay active)."),void this.removeGpayContainer()):(console.error("[PaypercutExpressCheckout] tenantId is empty — Google Pay cannot be mounted without a valid gatewayMerchantId."),void this.removeGpayContainer())}mountGooglePayButton(e,t,i,n){if(!this.gpayContainer)return void console.error("[PaypercutExpressCheckout] gpayContainer is null");const a=globalThis.google;if(!a?.payments?.api?.PaymentsClient)return void console.error("[PaypercutExpressCheckout] google.payments.api.PaymentsClient not available");const s=n?"PRODUCTION":"TEST",o=this.options.countryCode;o||console.warn('[PaypercutExpressCheckout] countryCode is not set. This is required for Google Pay in production. Pass it via options.countryCode (e.g. "DE").');const r={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS","PAN_ONLY"],allowedCardNetworks:["MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!1}},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"basistheory",gatewayMerchantId:e}}}],merchantInfo:{merchantId:t,merchantName:i},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:(this.options.amount/100).toFixed(2),currencyCode:this.options.currency,countryCode:o},callbackIntents:["PAYMENT_AUTHORIZATION","SHIPPING_ADDRESS","SHIPPING_OPTION"],shippingAddressRequired:!0,shippingOptionRequired:!0};this.options.allowedCountries?.length&&(r.shippingAddressParameters={allowedCountryCodes:this.options.allowedCountries,phoneNumberRequired:!1}),this.options.shippingOptions?.length&&(r.shippingOptionParameters={defaultSelectedOptionId:this.options.shippingOptions[0].id,shippingOptions:this.options.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${this.options.currency}`}))}),this.gpayPaymentRequest=r,this.gpayClient=new a.payments.api.PaymentsClient({environment:s,paymentDataCallbacks:{onPaymentAuthorized:e=>this.handleGooglePayAuthorized(e),onPaymentDataChanged:e=>this.handleGooglePayDataChanged(e)}});const l=this.options.buttonOptions,p=this.gpayClient.createButton({onClick:()=>this.startGooglePay(r),buttonSizeMode:"fill",buttonType:l?.type??"plain",buttonColor:l?.googlePayColor??"default",...this.options.locale&&{buttonLocale:T(this.options.locale)}}),h=l?.borderRadius??"0.5rem";p.style.width="100%",this.injectGpayInnerStyles(p,h),this.gpayContainer.appendChild(p)}injectGpayInnerStyles(e,t){const i=document.createElement("style");i.textContent=`.gpay-button { height: 48px !important; border-radius: ${t} !important; background-size: auto 60% !important; } .gpay-card-info-container { border-radius: ${t} !important; } .gpay-card-info-container-fill, .gpay-card-info-container-fill > .gpay-card-info-container { height: 48px !important; }`,e.prepend(i)}async startGooglePay(e){if(this.gpayClient&&!this.sessionActive){if(this.idempotencyKey=_(),this.setSessionActive(!0),this.emitter.emit(D.Click),this.emitter.hasListeners(D.SessionStart)){const t=await new Promise(e=>{const t=setTimeout(()=>e(null),3e3);this.emitter.emit(D.SessionStart,{wallet:"google_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return this.setSessionActive(!1),void this.emitter.emit(D.ShippingOptionsRequired,{wallet:"google_pay"});t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions,e.shippingOptionParameters={defaultSelectedOptionId:t.shippingOptions[0]?.id,shippingOptions:t.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${this.options.currency}`}))}),null!=t.amount&&(this.gpayCurrentAmount=t.amount,e.transactionInfo={...e.transactionInfo,totalPrice:(t.amount/100).toFixed(2)})}this.gpayCurrentAmount||(this.gpayCurrentAmount=this.options.amount);try{if(await this.gpayClient.loadPaymentData(e),this.pending3DSAfterGpay){const e=this.pending3DSAfterGpay;this.pending3DSAfterGpay=null,this.threeDSModal.show(e)}}catch(e){"CANCELED"===e?.statusCode||e?.message?.toLowerCase?.().includes("cancel")?this.emitter.emit(D.Cancel):this.emitter.emit(D.Error,new Error(e?.message??"Google Pay failed"))}finally{this.setSessionActive(!1)}}}async handleGooglePayAuthorized(e){try{const t=e.paymentMethodData.tokenizationData.token,i=e.paymentMethodData?.info?.cardNetwork??"",n=e.paymentMethodData?.info?.billingAddress,a=e.shippingAddress,s=e.shippingOptionData,o=n?{name:n.name,address:{line1:n.address1,city:n.locality,state:n.administrativeArea,postalCode:n.postalCode,country:n.countryCode}}:null,r=a?{name:a.name||void 0,address:{line1:a.address1,city:a.locality,state:a.administrativeArea,postalCode:a.postalCode,country:a.countryCode}}:void 0,l=s?this.currentShippingOptions.find(e=>e.id===s.id)??{id:s.id,label:s.label??s.id,amount:0}:void 0;this.pendingGpayBillingDetails=o,this.pendingGpayShippingDetails=r,this.pendingGpayShippingOption=l;const p=await new Promise((e,n)=>{const a=setTimeout(()=>{this.pendingGpayResolve=null,this.pendingGpayReject=null,n(new Error("Tokenization timed out"))},3e4);this.pendingGpayResolve=t=>{clearTimeout(a),e(t)},this.pendingGpayReject=e=>{clearTimeout(a),n(e)},this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"google_pay",encryptedToken:t,cardNetwork:i,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:o,amount:this.options.amount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})});if(p.__closeSheet)return{transactionState:"SUCCESS"};if(!p.success){const e=p.error??"Tokenization failed";return this.emitter.emit(D.Error,new Error(e)),this.emitter.emit(D.PaymentMethodFailed,{error:e}),{transactionState:"ERROR"}}const h=await this.createPaymentMethod({btTokenId:p.btTokenId,cardPayload:p.cardPayload,billingDetails:p.billingDetails,csessId:p.csessId,walletType:"google_pay"});return this.emitter.emit(D.PaymentMethodCreated,{paymentMethodId:h,wallet:"google_pay",billingDetails:o??void 0,shippingDetails:r,selectedShippingOption:l}),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,{transactionState:"SUCCESS"}}catch(e){return console.error("[PaypercutExpressCheckout] handleGooglePayAuthorized error:",e?.message??e),this.emitter.emit(D.Error,new Error(e?.message??"Google Pay authorization failed")),this.emitter.emit(D.PaymentMethodFailed,{error:e?.message??"Google Pay authorization failed"}),{transactionState:"ERROR"}}}async handleGooglePayDataChanged(e){const{callbackTrigger:t,shippingAddress:i,shippingOptionData:n}=e;if("INITIALIZE"===t)return G({amount:this.gpayCurrentAmount||this.options.amount,shippingOptions:this.currentShippingOptions},this.options.currency,this.options.countryCode);if("SHIPPING_ADDRESS"===t){return G(await new Promise(e=>{this.emitter.emit(D.ShippingAddressChange,{address:{country:i?.countryCode??"",state:i?.administrativeArea,city:i?.locality,postalCode:i?.postalCode},updateWith:t=>{t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions),null!=t.amount&&(this.gpayCurrentAmount=t.amount),e(t)}})}),this.options.currency,this.options.countryCode)}if("SHIPPING_OPTION"===t){const e=n?.id,t=this.currentShippingOptions.find(t=>t.id===e);return G(await new Promise(i=>{this.emitter.emit(D.ShippingOptionChange,{shippingOption:{id:e??"",label:t?.label??e??"",detail:t?.detail,amount:t?.amount??0},updateWith:e=>{null!=e.amount&&(this.gpayCurrentAmount=e.amount),i(e)}})}),this.options.currency,this.options.countryCode)}return{}}update(e){this.mounted?this.applePayPendingCallback&&this.applePayPendingCallback.resolve(e):console.warn("[PaypercutExpressCheckout] Cannot update: not mounted")}on(e,t){return this.emitter.on(e,t)}destroy(){if(!this.destroyed){if(this.tokenizeIframe){try{this.tokenizeIframe.remove()}catch{}this.tokenizeIframe=null}if(this.gpayContainer){try{this.gpayContainer.remove()}catch{}this.gpayContainer=null}if(this.applePayContainer)try{this.removeApplePayContainer()}catch{}this.gpayPaymentRequest=null,this.layoutResizeObserver&&(this.layoutResizeObserver.disconnect(),this.layoutResizeObserver=null),this.threeDSModal.close(),this.abortApplePaySession(),this.sessionActive=!1,this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}setSessionActive(e){this.sessionActive=e;const t=e?"0.5":"",i=e?"none":"";this.applePayContainer&&(this.applePayContainer.style.opacity=t,this.applePayContainer.style.pointerEvents=i),this.gpayContainer&&(this.gpayContainer.style.opacity=t,this.gpayContainer.style.pointerEvents=i)}completeApplePaySession(e){try{if(this.applePaySession){const t=window.ApplePaySession,i=e?t.STATUS_SUCCESS:t.STATUS_FAILURE;this.applePaySession.completePayment(i)}}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}abortApplePaySession(){try{this.applePaySession?.abort()}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}async createPaymentMethod(e){const{btTokenId:t,cardPayload:i,billingDetails:n,csessId:s,walletType:o}=e;if(!i||!t)throw new Error("[createPaymentMethod] Missing required tokenization data.");const r=new URL("/v1/payment_methods",a(this.options.apiUrl)),l={type:"card",key:this.options.publishableKey,card:{token:s??"",brand:i.brand??"",exp_month:i.exp_month??1,exp_year:i.exp_year??1,funding:i.funding??"",last4:i.last4??"",iin:i.bin??"",issuer:i.issuer??null,fingerprint:i.fingerprint??null,segment:i.segment??"",wallet:{type:o,dynamic_last4:null},three_d_secure_usage:{supported:!0}},billing_details:{name:n?.name??null,email:n?.email??null,phone:n?.phone??null,address:{city:n?.address?.city??null,country:n?.address?.country??null,line1:n?.address?.line1??null,line2:n?.address?.line2??null,postal_code:n?.address?.postalCode??null,state:n?.address?.state??null}},confirmation_token:{token_id:t}},p=await fetch(r.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),cache:"no-store"});if(!p.ok){const e=await p.text().catch(()=>`HTTP ${p.status}`);throw new Error(`Payment method creation failed (${p.status}): ${e}`)}return(await p.json()).id}postToTokenizeIframe(e){if(!this.tokenizeIframe?.contentWindow)return;const t=n(this.options.hostedCheckoutUrl);this.tokenizeIframe.contentWindow.postMessage(e,t)}buildThreeDSUrl(e){const t=n(this.options.hostedCheckoutUrl),i=new URL("/express/threeds",t);return i.searchParams.set("instanceId",this.instanceId),i.searchParams.set("sessionId",e.sessionId),i.searchParams.set("step",e.step),e.challengeUrl&&i.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&i.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&i.searchParams.set("threeDSVersion",e.threeDSVersion),i.searchParams.set("liveMode",String(e.liveMode??!1)),i.toString()}handle3DSShellCancel(){this.postToTokenizeIframe({type:"THREEDS_CANCELED",instanceId:this.instanceId,error:"User canceled 3DS authentication"}),this.threeDSModal.close(),this.emitter.emit(D.Cancel)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutExpressCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=n(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",instanceId:this.instanceId},t)}}const N=function(e){return new U(e)};let H=!1;const F=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,B=/^(0|(\d+(\.\d+)?(px|rem|em)))$/;function j(e){e&&(void 0===e.brandColor||F.test(e.brandColor)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.brandColor: "${e.brandColor}". Expected a hex color (#RGB or #RRGGBB). Value ignored.`),void 0===e.fontFamily||e.fontFamily.trim()||console.warn("[PaypercutCheckout] Invalid appearance.variables.fontFamily: value is empty. Value ignored."),void 0===e.logoUrl||/^https:\/\//.test(e.logoUrl)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.logoUrl: "${e.logoUrl}". Must start with https://. Value ignored.`),void 0===e.borderRadius||B.test(e.borderRadius.trim())||console.warn(`[PaypercutCheckout] Invalid appearance.variables.borderRadius: "${e.borderRadius}". Expected a CSS length like "8px", "0.5rem", or "0". Value ignored.`))}class ${constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.iframe=null,this.applePaySession=null,this.applePayBridgeTimeout=null,this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler),P(t.ui_mode??d.EMBEDDED)===d.EMBEDDED&&function(){if("undefined"==typeof window)return;if(window.ApplePaySession)return;if(H)return;H=!0;const e=document.createElement("script");e.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",e.crossOrigin="anonymous",e.async=!0,document.head.appendChild(e)}()}buildSrc(){const e=n(this.options.hostedCheckoutUrl),t=new URL(`/c/${this.options.id}`,e);if(this.options.locale){const e=h(this.options.locale);t.searchParams.set("locale",e)}if(this.options.lang){const e=h(this.options.lang);t.searchParams.set("lang",e)}{const e=P(this.options.ui_mode??d.EMBEDDED);e&&t.searchParams.set("ui_mode",e)}if(this.options.payment_methods&&this.options.payment_methods.length>0){(function(e){const t=[];for(const i of e)m(i)?t.push(i):console.warn(`[PaypercutCheckout] Invalid payment method: "${i}". Skipping.`);return 0===t.length&&(console.warn('[PaypercutCheckout] No valid payment methods provided. Defaulting to "card".'),t.push(c.CARD)),t})(this.options.payment_methods).forEach(e=>{t.searchParams.append("payment_methods",e)})}if(void 0!==this.options.wallet_options)if(0===this.options.wallet_options.length)t.searchParams.set("wallet_options",null);else{(function(e){const t=[];for(const i of e)g(i)?t.push(i):console.warn(`[PaypercutCheckout] Invalid wallet option: "${i}". Skipping.`);return t})(this.options.wallet_options).forEach(e=>{t.searchParams.append("wallet_options",e)})}return this.options.appearance?.preset&&t.searchParams.set("preset",this.options.appearance.preset),this.options.appearance?.theme&&t.searchParams.set("theme",this.options.appearance.theme),this.options.appearance?.variables&&Object.keys(this.options.appearance.variables).length>0&&(j(this.options.appearance.variables),t.searchParams.set("appearance_vars",JSON.stringify(this.options.appearance.variables))),void 0!==this.options.form_only&&t.searchParams.set("form_only",String(this.options.form_only)),void 0!==this.options.validate_form&&t.searchParams.set("validate_form",String(this.options.validate_form)),t.toString()}getContainer(){const e="string"==typeof this.options.containerId?document.querySelector(this.options.containerId):this.options.containerId;if(!e)throw new Error(`Container not found: ${this.options.containerId}`);return e}onMessage(e){if(!i(e.origin))return;const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.checkoutId||t.checkoutId===this.options.id))switch(t.type){case"CHECKOUT_LOADED":this.emitter.emit(y.Loaded);break;case"CHECKOUT_PROCESSING":this.emitter.emit(y.Processing,{checkoutId:t.checkoutId});break;case"CHECKOUT_SUCCESS":const{payment_method:i={},payment:n=null}=t;this.emitter.emit(y.Success,{payment_method:i,payment:n});break;case"CHECKOUT_ERROR":this.emitter.emit(y.Error,(t&&t.error)??t);break;case"CHECKOUT_CANCEL":this.emitter.emit(y.Cancel,{checkoutId:t.checkoutId,wallet:t.wallet});break;case"CHECKOUT_EXPIRED":this.emitter.emit(y.Expired);break;case"CHECKOUT_RESIZE":this.emitter.emit(y.Resize,t.height),this.handleResize(t.height);break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.threeDSModal.show(t),this.emitter.emit(y.ThreeDSStarted);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSComplete);break;case"THREEDS_CANCELED":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSCanceled);break;case"THREEDS_ERROR":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSError,t.error);break;case"FORM_VALIDATION":this.emitter.emit(y.FormValidation,{checkoutId:t.checkoutId,wallet:t.wallet});break;case f:this.handleApplePayStart(t);break;case C:this.handleApplePayMerchantSession(t.merchantSession);break;case b:this.abortApplePaySession();break;case E:this.handleApplePayPaymentResult(!0===t.success)}}render(){if(!this.mounted)try{const e=this.getContainer();this.iframe=document.createElement("iframe"),this.iframe.id="paypercut-checkout-iframe",this.iframe.src=this.buildSrc(),this.iframe.allow="payment *; clipboard-write",this.iframe.setAttribute("frameborder","0"),this.iframe.setAttribute("allowpaymentrequest","true"),this.iframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox"),Object.assign(this.iframe.style,{width:"100%",height:"100%",border:"none",display:"block"}),e.appendChild(this.iframe),this.mounted=!0}catch(e){throw console.error("[PaypercutCheckout] Failed to render:",e),e}}submit(){if(this.mounted)try{this.postToIframe({type:"START_PROCESSING",checkoutId:this.options.id})}catch(e){throw console.error("[PaypercutCheckout] Failed to submit payment:",e),e}}postToIframe(e){if(!this.iframe?.contentWindow)return void console.error("[PaypercutCheckout] Cannot post message: iframe not mounted");const t=n(this.options.hostedCheckoutUrl);this.iframe.contentWindow.postMessage(e,t)}handleResize(e){!this.iframe||"number"!=typeof e||e<=0||(this.iframe.style.height=`${e}px`)}buildThreeDSUrl(e){const t=n(this.options.hostedCheckoutUrl),i=new URL(`/c/${this.options.id}/threeds`,t);return i.searchParams.set("sessionId",e.sessionId),i.searchParams.set("step",e.step),e.challengeUrl&&i.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&i.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&i.searchParams.set("threeDSVersion",e.threeDSVersion),i.searchParams.set("liveMode",String(e.liveMode??!1)),i.toString()}handle3DSShellCancel(){this.postToIframe({type:"THREEDS_CANCELED",checkoutId:this.options.id,reason:"sdk_shell_cancel"}),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSCanceled)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=n(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",checkoutId:this.options.id},t)}handleApplePayStart(e){this.abortApplePaySession();const t=window.ApplePaySession;if(!t)return void this.postToIframe({type:v,checkoutId:this.options.id});const i=t.supportsVersion?.(14)?14:3;let n;try{n=new t(i,e.request)}catch(e){return console.error("SecurityError"===e?.name?'[PaypercutCheckout] Apple Pay blocked — parent page missing allow="payment" on iframe':"[PaypercutCheckout] Failed to create ApplePaySession",e),void this.postToIframe({type:v,checkoutId:this.options.id})}this.applePaySession=n,n.onvalidatemerchant=e=>{this.applePayBridgeTimeout=setTimeout(()=>this.abortApplePaySession(),15e3),this.postToIframe({type:S,checkoutId:this.options.id,validationURL:e.validationURL})},n.onpaymentauthorized=e=>{this.postToIframe({type:w,checkoutId:this.options.id,payment:e.payment})},n.oncancel=()=>{this.applePaySession=null,this.postToIframe({type:A,checkoutId:this.options.id})},n.begin()}handleApplePayMerchantSession(e){if(this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null),this.applePaySession)try{this.applePaySession.completeMerchantValidation(e)}catch(e){console.error("[PaypercutCheckout] completeMerchantValidation failed",e),this.abortApplePaySession(),this.postToIframe({type:v,checkoutId:this.options.id})}}handleApplePayPaymentResult(e){if(!this.applePaySession)return;const t=window.ApplePaySession;try{this.applePaySession.completePayment(e?t.STATUS_SUCCESS:t.STATUS_FAILURE)}catch(e){console.error("[PaypercutCheckout] completePayment failed",e)}this.applePaySession=null}abortApplePaySession(){this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null);try{this.applePaySession?.abort()}catch{}this.applePaySession=null}destroy(){if(!this.destroyed){if(this.iframe)try{this.iframe.remove(),this.iframe=null}catch(e){console.error("[PaypercutCheckout] Error removing iframe:",e)}this.threeDSModal.close(),this.abortApplePaySession(),this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}isMounted(){return this.mounted}completeFormValidation(e){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"success"}):console.warn("[PaypercutCheckout] Cannot complete form validation: not mounted")}updateAppearance(e){this.mounted?(j(e.variables),this.postToIframe({type:"UPDATE_APPEARANCE",checkoutId:this.options.id,appearance:e})):console.warn("[PaypercutCheckout] Cannot update appearance: not mounted")}failFormValidation(e,t){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"failed",errors:t}):console.warn("[PaypercutCheckout] Cannot fail form validation: not mounted")}}const V=function(e){return new $(e)};return V.version=t.version,"undefined"!=typeof window&&(window.PaypercutExpressCheckout=N),V}();
|
|
1
|
+
var PaypercutCheckout=function(){"use strict";class e{constructor(){this.handlers=new Map}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}once(e,t){const i=(...n)=>{t(...n),this.off(e,i)};return this.on(e,i)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,...t){this.handlers.get(e)?.forEach(i=>{try{i(...t)}catch(t){console.error(`[Emitter] Error in ${e} handler:`,t)}})}hasListeners(e){const t=this.handlers.get(e);return!!t&&t.size>0}clear(){this.handlers.clear()}}const t={version:"1.2.11",defaultCheckoutOrigin:"https://buy.paypercut.io",defaultApiOrigin:"https://api.paypercut.io",defaultVaultApiUrl:"https://api.basistheory.com",allowedOrigins:["https://buy.paypercut.io"]};function i(e){return t.allowedOrigins.includes(e)}function n(e){return t.defaultCheckoutOrigin}function a(e){return t.defaultApiOrigin}function s(){return t.defaultVaultApiUrl}function o(){const e="undefined"!=typeof window?window.visualViewport:void 0,t="undefined"!=typeof document?document.documentElement:void 0;return{width:e?.width||window.innerWidth||t?.clientWidth||window.screen?.width||460,height:e?.height||window.innerHeight||t?.clientHeight||window.screen?.height||680}}function r(e,t,i){const n=Math.min(t,i);return Math.min(Math.max(e,n),i)}class l{constructor(e){this.options=e,this.modal=null,this.shell=null,this.iframe=null,this.frameSize={},this.resizeHandler=null,this.pendingData=null}show(e){this.close(),this.modal=function(e){const t=document.createElement("div"),i=o();return t.id=e,Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:`${i.width}px`,height:`${i.height}px`,minHeight:`${i.height}px`,display:"flex",alignItems:"center",justifyContent:"center",zIndex:"999999",background:"rgba(0, 0, 0, 0.56)",padding:"16px",boxSizing:"border-box",overflow:"hidden"}),t}(this.options.modalId),this.shell=function(e){const t=document.createElement("div");Object.assign(t.style,{position:"relative",borderRadius:"6px",background:"transparent",boxShadow:"0 24px 64px rgba(0, 0, 0, 0.36), 0 2px 10px rgba(0, 0, 0, 0.18)",overflow:"visible"});const i=document.createElement("iframe");i.allow="payment *",i.setAttribute("frameborder","0"),Object.assign(i.style,{border:"none",borderRadius:"6px",display:"block",background:"transparent",maxWidth:"100%",maxHeight:"100%"});const n=document.createElement("button");n.type="button",n.textContent="Cancel",n.setAttribute("aria-label","Cancel 3D Secure authentication"),Object.assign(n.style,{position:"absolute",top:"-40px",right:"0",zIndex:"2",height:"28px",padding:"0 10px",border:"0",borderRadius:"999px",background:"rgba(17, 24, 39, 0.56)",color:"#ffffff",font:'600 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',letterSpacing:"0.04em",textTransform:"uppercase",cursor:"pointer",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.24)",transform:"translateY(0) scale(1)",transition:window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"none":"transform 300ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow 300ms cubic-bezier(0.22, 1, 0.36, 1), background 300ms cubic-bezier(0.22, 1, 0.36, 1)",willChange:"transform"});const a=()=>{n.style.background="rgba(17, 24, 39, 0.56)",n.style.boxShadow="0 4px 16px rgba(0, 0, 0, 0.24)",n.style.transform="translateY(0) scale(1)"},s=()=>{n.style.background="rgba(17, 24, 39, 0.68)",n.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.26)",n.style.transform="translateY(-1px) scale(1.025)"};return n.addEventListener("mouseenter",s),n.addEventListener("focus",s),n.addEventListener("mouseleave",a),n.addEventListener("blur",a),n.addEventListener("mouseup",s),n.addEventListener("mousedown",()=>{n.style.background="rgba(17, 24, 39, 0.72)",n.style.boxShadow="0 3px 12px rgba(0, 0, 0, 0.22)",n.style.transform="translateY(0) scale(0.985)"}),n.addEventListener("click",e),t.appendChild(i),t.appendChild(n),{shell:t,iframe:i,cancelButton:n}}(()=>this.options.onCancel()),this.iframe=this.shell.iframe,this.iframe.src=this.options.buildUrl(e),this.frameSize={},this.applySize(),this.modal.appendChild(this.shell.shell),document.body.appendChild(this.modal),this.resizeHandler=()=>this.applySize(),window.addEventListener("resize",this.resizeHandler),window.addEventListener("orientationchange",this.resizeHandler),window.visualViewport?.addEventListener("resize",this.resizeHandler),this.pendingData=e}handleFrameResize(e,t){if(!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow)return;const i=function(e){if(!e||"object"!=typeof e)return null;const t=e,i={};return"number"==typeof t.width&&Number.isFinite(t.width)&&t.width>0&&(i.width=t.width),"number"==typeof t.height&&Number.isFinite(t.height)&&t.height>0&&(i.height=t.height),i.width||i.height?i:null}(t);i&&(this.frameSize={...this.frameSize,...i},this.applySize())}handleReady(){return!(!this.pendingData||!this.iframe?.contentWindow)&&(this.options.onReady(this.iframe,this.pendingData),!0)}close(){this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),window.removeEventListener("orientationchange",this.resizeHandler),window.visualViewport?.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),this.modal&&(this.modal.remove(),this.modal=null),this.shell=null,this.iframe=null,this.frameSize={},this.pendingData=null}applySize(){!function(e,t,i={},n){if(!e||!t)return i;const a=o(),s=Math.min(860,Math.max(0,a.width-32)),l=Math.min(860,Math.max(0,a.height-112)),p=i.width??460,h=i.height??680,d=r(p,320,s),c=r(h,300,l);e.style.width=`${a.width}px`,e.style.height=`${a.height}px`,e.style.minHeight=`${a.height}px`,t.style.width=`${Math.round(d)}px`,t.style.height=`${Math.round(c)}px`,n&&(n.style.width=`${Math.round(d)}px`,n.style.height=`${Math.round(c)}px`)}(this.modal,this.iframe,this.frameSize,this.shell?.shell)}}const p=new Set(["bg","bg-BG","en","en-GB","el","el-GR","ro","ro-RO","hr","hr-HR","pl","pl-PL","cs","cs-CZ","sl","sl-SI","sk","sk-SK","hu","hu-HU"]);function h(e){return e&&"auto"!==e?p.has(e)?e:(console.warn(`[PaypercutCheckout] Locale "${e}" is not supported. Falling back to "en".`),"en"):"en"}var d,c,u,y;function m(e){return Object.values(c).includes(e)}function g(e){return Object.values(u).includes(e)}function P(e){var t;if(e)return t=e,Object.values(d).includes(t)?e:void console.warn(`[PaypercutCheckout] Invalid ui_mode: "${e}". Valid options: ${Object.values(d).join(", ")}`)}!function(e){e.EMBEDDED="embedded"}(d||(d={})),function(e){e.CARD="card"}(c||(c={})),function(e){e.APPLE_PAY="apple_pay",e.GOOGLE_PAY="google_pay"}(u||(u={})),function(e){e.Loaded="loaded",e.Processing="processing",e.Success="success",e.Error="error",e.Expired="expired",e.Resize="resize",e.ThreeDSComplete="threeds_complete",e.ThreeDSError="threeds_error",e.ThreeDSCanceled="threeds_canceled",e.ThreeDSStarted="threeds_started",e.Cancel="cancel",e.FormValidation="form_validation"}(y||(y={}));const f="APPLE_PAY_START",S="APPLE_PAY_VALIDATE_MERCHANT",C="APPLE_PAY_MERCHANT_SESSION",b="APPLE_PAY_MERCHANT_ERROR",w="APPLE_PAY_PAYMENT_DATA",E="APPLE_PAY_PAYMENT_RESULT",A="APPLE_PAY_CANCELLED",v="APPLE_PAY_SESSION_ERROR",I=new Set(["ar","bg","ca","cs","da","de","el","en","es","et","fi","fr","hr","id","it","ja","ko","ms","nl","no","pl","pt","ru","sk","sl","sr","sv","th","tr","uk","zh"]);function k(e){return e||"en"}function T(e){const t=e.split("-")[0].toLowerCase();return I.has(t)?t:"en"}var D;function _(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function x(e){return e.startsWith("pk_live_")}!function(e){e.Ready="ready",e.Click="click",e.SessionStart="session_start",e.ShippingOptionsRequired="shipping_options_required",e.ShippingAddressChange="shipping_address_change",e.ShippingOptionChange="shipping_option_change",e.PaymentMethodCreated="payment_method_created",e.PaymentMethodFailed="payment_method_failed",e.Cancel="cancel",e.Error="error"}(D||(D={}));let R=null;function O(){return R||(R=new Promise(e=>{if("undefined"==typeof window)return void e();if(customElements?.get("apple-pay-button"))return void e();const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.async=!0,t.onload=()=>e(),t.onerror=()=>e(),document.head.appendChild(t)}),R)}let M=null;function L(){return M||(M=new Promise((e,t)=>{if("undefined"==typeof window)return void t(new Error("No window"));if(globalThis.google?.payments?.api?.PaymentsClient)return void e();const i=document.createElement("script");i.src="https://pay.google.com/gp/p/js/pay.js",i.async=!0,i.onload=()=>e(),i.onerror=()=>t(new Error("Failed to load Google Pay script")),document.head.appendChild(i)}),M)}function G(e,t,i="DE"){const n={};return void 0!==e.amount&&(n.newTransactionInfo={totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:(e.amount/100).toFixed(2),currencyCode:t,countryCode:i}),e.shippingOptions?.length&&(n.newShippingOptionParameters={defaultSelectedOptionId:e.shippingOptions[0].id,shippingOptions:e.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${t}`}))}),"invalid_shipping_address"===e.status?n.error={reason:"SHIPPING_ADDRESS_UNSERVICEABLE",message:"Cannot ship to this address.",intent:"SHIPPING_ADDRESS"}:"invalid_shipping_option"===e.status&&(n.error={reason:"SHIPPING_OPTION_INVALID",message:"This shipping option is not available.",intent:"SHIPPING_OPTION"}),n}function z(e){return"checkout"===e?"check-out":e}class U{constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.sessionActive=!1,this.tokenizeIframe=null,this.wrapper=null,this.applePayContainer=null,this.applePayButtonEl=null,this.gpayContainer=null,this.gpayClient=null,this.gpayPaymentRequest=null,this.gpayCurrentAmount=0,this.preferredLayout="row",this.layoutResizeObserver=null,this.instanceId=_(),this.idempotencyKey=_(),this.pending3DSAfterGpay=null,this.applePaySession=null,this.applePayCurrentAmount=0,this.currentLineItems=[],this.applePayCurrentShippingOptions=[],this.applePayPendingShippingOption=null,this.applePayPendingCallback=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.expressConfig=null,this.pendingGpayResolve=null,this.pendingGpayReject=null,this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,this.currentShippingOptions=t.shippingOptions??[],this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-express-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler)}buildTokenizeSrc(){const e=n(this.options.hostedCheckoutUrl),t=new URL("/express/tokenize",e);return t.searchParams.set("instanceId",this.instanceId),t.searchParams.set("liveMode",String(x(this.options.publishableKey))),t.toString()}async fetchExpressConfig(){const e=a(this.options.apiUrl),t=new URL("/v1/elements/sessions",e),{amount:i}=this.options;t.searchParams.set("type","deferred_intent"),t.searchParams.set("key",this.options.publishableKey),t.searchParams.set("deferred_intent[mode]","payment"),t.searchParams.set("deferred_intent[currency]",this.options.currency),null!=i&&t.searchParams.set("deferred_intent[amount]",`${i}`),t.searchParams.set("referrer_host",window.location.hostname);try{const e=await fetch(t.toString(),{cache:"no-store"});if(!e.ok)throw new Error(`Config fetch failed: HTTP ${e.status}`);const i=await e.json(),n=x(this.options.publishableKey),a="BCR2DN5T735375Y7",o=i.payment_domain?.wallets?.google_pay?.merchant_ref??"",r=i.payment_domain?.wallets?.google_pay?.status??"inactive";this.expressConfig={tenantId:i.payment_domain?.wallet_provider?.tenant_id??"",publicKey:i.payment_domain?.wallet_provider?.public_key??"",vaultApiUrl:s(),googlePayMerchantId:n?"active"===r?o:a:o||a,googlePayStatus:r,applePayStatus:i.payment_domain?.wallets?.apple_pay?.status??"inactive",displayName:i.merchant?.name??"",merchantMid:i.merchant?.mid??"",merchantMcc:i.merchant?.mcc??"",merchantCountry:i.merchant?.country??"",merchantUrl:i.merchant?.business_url??""}}catch(e){console.error("[PaypercutExpressCheckout] Failed to fetch express config:",e)}}onMessage(e){if(!i(e.origin))return void(e.origin.includes("localhost")&&console.warn("[PaypercutExpressCheckout] Message blocked — origin not allowed:",e.origin));const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.instanceId||t.instanceId===this.instanceId))switch(t.type){case"TOKENIZE_RESPONSE":if("apple_pay"===t.wallet)t.success?this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"apple_pay"}).then(e=>{this.completeApplePaySession(!0),this.emitter.emit(D.PaymentMethodCreated,{paymentMethodId:e,wallet:"apple_pay",billingDetails:this.applePayPendingBillingDetails??void 0,shippingDetails:this.applePayPendingShippingDetails??void 0,selectedShippingOption:this.applePayPendingShippingOption??void 0}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}).catch(e=>{this.completeApplePaySession(!1),this.emitter.emit(D.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(D.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}):(this.completeApplePaySession(!1),this.emitter.emit(D.Error,new Error(t.error??"Apple Pay payment failed")),this.emitter.emit(D.PaymentMethodFailed,{error:t.error??"Apple Pay payment failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null);else if(t.success)this.pendingGpayResolve?(this.pendingGpayResolve(t),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"google_pay"}).then(e=>{this.emitter.emit(D.PaymentMethodCreated,{paymentMethodId:e,wallet:"google_pay",billingDetails:this.pendingGpayBillingDetails??void 0,shippingDetails:this.pendingGpayShippingDetails??void 0,selectedShippingOption:this.pendingGpayShippingOption})}).catch(e=>{this.emitter.emit(D.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(D.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"})}).finally(()=>{this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0});else if(this.pendingGpayReject)this.pendingGpayReject(new Error(t.error??"Tokenization failed")),this.pendingGpayResolve=null,this.pendingGpayReject=null;else{const e=t.error??"Google Pay payment failed";e.toLowerCase().includes("cancel")?this.emitter.emit(D.Cancel):(this.emitter.emit(D.Error,new Error(e)),this.emitter.emit(D.PaymentMethodFailed,{error:e})),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0}break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.pendingGpayResolve?(this.pending3DSAfterGpay=t,this.pendingGpayResolve({__closeSheet:!0}),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.threeDSModal.show(t);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":case"THREEDS_CANCELED":case"THREEDS_ERROR":this.postToTokenizeIframe(t),this.threeDSModal.close()}}mount(e){if(this.mounted)return void console.warn("[PaypercutExpressCheckout] mount() called but already mounted — ignoring");const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error(`[PaypercutExpressCheckout] Container not found: ${e}`);const i=this.options.walletOptions?.length?this.options.walletOptions:[u.APPLE_PAY,u.GOOGLE_PAY],n=i.includes(u.APPLE_PAY),a=i.includes(u.GOOGLE_PAY),s=this.options.layout??"auto";this.preferredLayout="auto"===s?"row":s;const o=document.createElement("div");this.wrapper=o,Object.assign(o.style,{display:"flex",flexDirection:"row"===this.preferredLayout?"row":"column",gap:"8px",width:"100%"}),a&&(this.gpayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.gpayContainer),o.appendChild(this.gpayContainer),L().catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)})),n&&(this.applePayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.applePayContainer),o.appendChild(this.applePayContainer),O()),t.appendChild(o),"auto"===s&&"undefined"!=typeof ResizeObserver&&(this.layoutResizeObserver=new ResizeObserver(e=>{const i=e[0]?.contentRect.width??t.offsetWidth;this.applyLayout(i<=540?"column":"row")}),this.layoutResizeObserver.observe(t));const r=this.buildTokenizeSrc();this.tokenizeIframe=document.createElement("iframe"),this.tokenizeIframe.id="paypercut-express-tokenize-iframe",this.tokenizeIframe.src=r,this.tokenizeIframe.setAttribute("frameborder","0"),this.tokenizeIframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin"),Object.assign(this.tokenizeIframe.style,{position:"absolute",top:"-9999px",left:"-9999px",width:"1px",height:"1px",border:"none",visibility:"hidden"}),document.body.appendChild(this.tokenizeIframe),this.mounted=!0,this.fetchExpressConfig().then(async()=>{if(this.destroyed)return;const e=this.expressConfig;n&&this.applePayContainer&&"active"===e?.applePayStatus?await this.mountApplePayButton(this.applePayContainer):this.applePayContainer&&this.removeApplePayContainer(),a&&e&&this.mountGooglePayFromConfig(),this.emitter.emit(D.Ready)})}applyLayoutToContainers(e,...t){for(const i of t)i&&(i.style.flex="row"===e?"1":"",i.style.minWidth="row"===e?"0":"",i.style.width="row"===e?"":"100%")}applyLayout(e){this.wrapper&&(this.wrapper.style.flexDirection="row"===e?"row":"column",this.applyLayoutToContainers(e,this.applePayContainer,this.gpayContainer))}setLayout(e){this.preferredLayout=e,this.applyLayout(e)}setLocale(e){this.options.locale=e,this.applePayButtonEl&&this.applePayButtonEl.setAttribute("locale",k(e)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest&&this.setButtonOptions({})}setButtonOptions(e){this.options.buttonOptions={...this.options.buttonOptions,...e};const t=this.options.buttonOptions;if(this.applePayButtonEl&&(void 0!==e.applePayStyle&&this.applePayButtonEl.setAttribute("buttonstyle",e.applePayStyle),void 0!==e.type&&this.applePayButtonEl.setAttribute("type",z(e.type)),void 0!==e.borderRadius&&this.applePayButtonEl.style.setProperty("--apple-pay-button-border-radius",e.borderRadius)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest){this.gpayContainer.innerHTML="";const e=this.gpayClient.createButton({onClick:()=>this.startGooglePay(this.gpayPaymentRequest),buttonSizeMode:"fill",buttonType:t?.type??"plain",buttonColor:t?.googlePayColor??"default",...this.options.locale&&{buttonLocale:T(this.options.locale)}}),i=t?.borderRadius??"0.5rem";e.style.width="100%",this.injectGpayInnerStyles(e,i),this.gpayContainer.appendChild(e)}}async mountApplePayButton(e){await O();const t=window.ApplePaySession;if(!t)return void console.log("[PaypercutExpressCheckout] ApplePaySession not available");if(!t.canMakePayments?.())return void console.log("[PaypercutExpressCheckout] ApplePaySession.canMakePayments() returned false — hiding Apple Pay button");const i=this.options.locale?k(this.options.locale):"en",n=this.options.buttonOptions,a=document.createElement("apple-pay-button");a.setAttribute("buttonstyle",n?.applePayStyle??"black"),a.setAttribute("type",z(n?.type??"plain")),a.setAttribute("locale",i),a.style.setProperty("--apple-pay-button-width","100%"),a.style.setProperty("--apple-pay-button-height","48px"),a.style.setProperty("--apple-pay-button-border-radius",n?.borderRadius??"0.5rem"),a.style.display="block",a.style.cursor="pointer",a.addEventListener("click",()=>this.startApplePay());const s=()=>{this.applePayButtonEl=a,e.appendChild(a);const t=a.shadowRoot;if(t){const e=document.createElement("style");e.textContent="span svg { height: 75% !important; width: auto !important; }",t.appendChild(e)}};customElements?.get("apple-pay-button")?s():customElements?.whenDefined("apple-pay-button").then(s).catch(()=>s())}async startApplePay(){if(this.sessionActive)return;if("undefined"==typeof window)return;const e=window.ApplePaySession;if(!e)return void console.error("[PaypercutExpressCheckout] ApplePaySession not available");this.idempotencyKey=_(),this.setSessionActive(!0),this.emitter.emit(D.Click);const t=await new Promise(e=>{if(!this.emitter.hasListeners(D.SessionStart))return void e(null);const t=setTimeout(()=>e(null),3e3);this.emitter.emit(D.SessionStart,{wallet:"apple_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return console.error("[PaypercutExpressCheckout] Apple Pay: no session_start response — aborting"),this.setSessionActive(!1),void this.emitter.emit(D.ShippingOptionsRequired,{wallet:"apple_pay"});"number"==typeof t.amount?this.applePayCurrentAmount=t.amount:this.applePayCurrentAmount=this.options.amount,Array.isArray(t.lineItems)?this.currentLineItems=t.lineItems:this.currentLineItems=this.options.lineItems??[],Array.isArray(t.shippingOptions)?this.applePayCurrentShippingOptions=t.shippingOptions:this.applePayCurrentShippingOptions=this.currentShippingOptions,this.applePayPendingShippingOption=null;const i=this.expressConfig?.displayName||"Checkout",n=(this.applePayCurrentAmount/100).toFixed(2),a=this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})),o={countryCode:this.options.countryCode??"DE",currencyCode:this.options.currency,merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],lineItems:a,total:{label:i,amount:n,type:"final"},requiredBillingContactFields:["postalAddress","name","email"],requiredShippingContactFields:["postalAddress","name","email"]};this.applePayCurrentShippingOptions.length&&(o.shippingMethods=this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:(e.amount/100).toFixed(2),identifier:e.id}))),o.shippingType="shipping",this.abortApplePaySession();const r=e.supportsVersion?.(14)?14:3;try{const t=new e(r,o);this.applePaySession=t,t.onvalidatemerchant=async e=>{const n=this.expressConfig?.vaultApiUrl??s(),a=this.expressConfig?.publicKey??"";try{const s={"Content-Type":"application/json","BT-API-KEY":a};this.idempotencyKey&&(s["Idempotency-Key"]=this.idempotencyKey);const o=await fetch(`${n}/apple-pay/session`,{method:"POST",headers:s,body:JSON.stringify({display_name:i,domain:window.location.host,validation_url:e.validationURL})});if(!o.ok){const e=await o.json().catch(()=>({}));throw new Error(e?.message??`Merchant validation failed: HTTP ${o.status}`)}const r=await o.json();t.completeMerchantValidation(r)}catch(e){console.error("[PaypercutExpressCheckout] Apple Pay merchant validation failed"),this.abortApplePaySession(),this.emitter.emit(D.Error,new Error(e?.message??"Apple Pay merchant validation failed")),this.emitter.emit(D.Cancel)}},t.onshippingcontactselected=async n=>{const a=n.shippingContact,s=await new Promise(e=>{this.applePayPendingCallback={type:"contact",resolve:e},this.emitter.emit(D.ShippingAddressChange,{address:{country:a.countryCode??"",state:a.administrativeArea,city:a.locality,postalCode:a.postalCode},updateWith:e=>this.update(e)}),setTimeout(()=>e({}),3e4)});this.applePayPendingCallback=null,"number"==typeof s.amount&&(this.applePayCurrentAmount=s.amount),Array.isArray(s.lineItems)&&(this.currentLineItems=s.lineItems),Array.isArray(s.shippingOptions)&&(this.applePayCurrentShippingOptions=s.shippingOptions);const o="invalid_shipping_address"===s.status?e.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS:e.STATUS_SUCCESS;try{t.completeShippingContactSelection(o,this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:(e.amount/100).toFixed(2),identifier:e.id})),{label:i,amount:(this.applePayCurrentAmount/100).toFixed(2),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingContactSelection failed",e)}},t.onshippingmethodselected=async n=>{const a=n.shippingMethod,s={id:a.identifier,label:a.label,detail:a.detail,amount:Math.round(100*parseFloat(a.amount))};this.applePayPendingShippingOption=s;const o=await new Promise(e=>{this.applePayPendingCallback={type:"method",resolve:e},this.emitter.emit(D.ShippingOptionChange,{shippingOption:s,updateWith:e=>this.update(e)}),setTimeout(()=>e({}),3e4)});this.applePayPendingCallback=null,"number"==typeof o.amount&&(this.applePayCurrentAmount=o.amount),Array.isArray(o.lineItems)&&(this.currentLineItems=o.lineItems);try{t.completeShippingMethodSelection(e.STATUS_SUCCESS,{label:i,amount:(this.applePayCurrentAmount/100).toFixed(2),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingMethodSelection failed",e)}},t.onpaymentauthorized=e=>{const t=e.payment?.billingContact,i=e.payment?.shippingContact;this.applePayPendingBillingDetails=t?{name:[t.givenName,t.familyName].filter(Boolean).join(" ")||void 0,email:t.emailAddress,address:{line1:t.addressLines?.[0],line2:t.addressLines?.[1],city:t.locality,state:t.administrativeArea,postalCode:t.postalCode,country:t.countryCode}}:null,this.applePayPendingShippingDetails=i?{name:[i.givenName,i.familyName].filter(Boolean).join(" ")||void 0,address:{line1:i.addressLines?.[0],line2:i.addressLines?.[1],city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode}}:null,this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"apple_pay",applePaymentData:e.payment.token,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:this.applePayPendingBillingDetails,amount:this.applePayCurrentAmount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})},t.oncancel=()=>{this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.emitter.emit(D.Cancel)},t.begin()}catch(e){this.applePaySession=null,console.error("[PaypercutExpressCheckout] Failed to create ApplePaySession",{name:e?.name,message:e?.message,hint:"SecurityError"===e?.name?"Page is not HTTPS or merchant domain is not registered for Apple Pay":"Check isSecureContext and that ApplePaySession.canMakePayments() returns true"})}}removeGpayContainer(){this.gpayContainer?.remove(),this.gpayContainer=null}removeApplePayContainer(){this.applePayContainer?.remove(),this.applePayContainer=null,this.applePayButtonEl=null}mountGooglePayFromConfig(){const e=this.expressConfig;if(!e)return;const t=x(this.options.publishableKey),i=e.tenantId,n=e.googlePayMerchantId,a=e.displayName||"Checkout";return i?n?(console.log({liveMode:t}),!t||e.merchantMcc&&e.merchantUrl?void L().then(()=>{this.mountGooglePayButton(i,n,a,t)}).catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)}):(console.warn("[PaypercutExpressCheckout] Google Pay disabled!"),void this.removeGpayContainer())):(console.warn("[PaypercutExpressCheckout] googlePayMerchantId is empty — Google Pay will not be mounted (merchant may not have Google Pay active)."),void this.removeGpayContainer()):(console.error("[PaypercutExpressCheckout] tenantId is empty — Google Pay cannot be mounted without a valid gatewayMerchantId."),void this.removeGpayContainer())}mountGooglePayButton(e,t,i,n){if(!this.gpayContainer)return void console.error("[PaypercutExpressCheckout] gpayContainer is null");const a=globalThis.google;if(!a?.payments?.api?.PaymentsClient)return void console.error("[PaypercutExpressCheckout] google.payments.api.PaymentsClient not available");const s=n?"PRODUCTION":"TEST",o=this.options.countryCode;o||console.warn('[PaypercutExpressCheckout] countryCode is not set. This is required for Google Pay in production. Pass it via options.countryCode (e.g. "DE").');const r={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS","PAN_ONLY"],allowedCardNetworks:["MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!1}},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"basistheory",gatewayMerchantId:e}}}],merchantInfo:{merchantId:t,merchantName:i},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:(this.options.amount/100).toFixed(2),currencyCode:this.options.currency,countryCode:o},callbackIntents:["PAYMENT_AUTHORIZATION","SHIPPING_ADDRESS","SHIPPING_OPTION"],shippingAddressRequired:!0,shippingOptionRequired:!0};this.options.allowedCountries?.length&&(r.shippingAddressParameters={allowedCountryCodes:this.options.allowedCountries,phoneNumberRequired:!1}),this.options.shippingOptions?.length&&(r.shippingOptionParameters={defaultSelectedOptionId:this.options.shippingOptions[0].id,shippingOptions:this.options.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${this.options.currency}`}))}),this.gpayPaymentRequest=r,this.gpayClient=new a.payments.api.PaymentsClient({environment:s,paymentDataCallbacks:{onPaymentAuthorized:e=>this.handleGooglePayAuthorized(e),onPaymentDataChanged:e=>this.handleGooglePayDataChanged(e)}});const l=this.options.buttonOptions,p=this.gpayClient.createButton({onClick:()=>this.startGooglePay(r),buttonSizeMode:"fill",buttonType:l?.type??"plain",buttonColor:l?.googlePayColor??"default",...this.options.locale&&{buttonLocale:T(this.options.locale)}}),h=l?.borderRadius??"0.5rem";p.style.width="100%",this.injectGpayInnerStyles(p,h),this.gpayContainer.appendChild(p)}injectGpayInnerStyles(e,t){const i=document.createElement("style");i.textContent=`.gpay-button { height: 48px !important; border-radius: ${t} !important; background-size: auto 60% !important; } .gpay-card-info-container { border-radius: ${t} !important; } .gpay-card-info-container-fill, .gpay-card-info-container-fill > .gpay-card-info-container { height: 48px !important; }`,e.prepend(i)}async startGooglePay(e){if(this.gpayClient&&!this.sessionActive){if(this.idempotencyKey=_(),this.setSessionActive(!0),this.emitter.emit(D.Click),this.emitter.hasListeners(D.SessionStart)){const t=await new Promise(e=>{const t=setTimeout(()=>e(null),3e3);this.emitter.emit(D.SessionStart,{wallet:"google_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return this.setSessionActive(!1),void this.emitter.emit(D.ShippingOptionsRequired,{wallet:"google_pay"});t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions,e.shippingOptionParameters={defaultSelectedOptionId:t.shippingOptions[0]?.id,shippingOptions:t.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${this.options.currency}`}))}),null!=t.amount&&(this.gpayCurrentAmount=t.amount,e.transactionInfo={...e.transactionInfo,totalPrice:(t.amount/100).toFixed(2)})}this.gpayCurrentAmount||(this.gpayCurrentAmount=this.options.amount);try{if(await this.gpayClient.loadPaymentData(e),this.pending3DSAfterGpay){const e=this.pending3DSAfterGpay;this.pending3DSAfterGpay=null,this.threeDSModal.show(e)}}catch(e){"CANCELED"===e?.statusCode||e?.message?.toLowerCase?.().includes("cancel")?this.emitter.emit(D.Cancel):this.emitter.emit(D.Error,new Error(e?.message??"Google Pay failed"))}finally{this.setSessionActive(!1)}}}async handleGooglePayAuthorized(e){try{const t=e.paymentMethodData.tokenizationData.token,i=e.paymentMethodData?.info?.cardNetwork??"",n=e.paymentMethodData?.info?.billingAddress,a=e.shippingAddress,s=e.shippingOptionData,o=n?{name:n.name,address:{line1:n.address1,city:n.locality,state:n.administrativeArea,postalCode:n.postalCode,country:n.countryCode}}:null,r=a?{name:a.name||void 0,address:{line1:a.address1,city:a.locality,state:a.administrativeArea,postalCode:a.postalCode,country:a.countryCode}}:void 0,l=s?this.currentShippingOptions.find(e=>e.id===s.id)??{id:s.id,label:s.label??s.id,amount:0}:void 0;this.pendingGpayBillingDetails=o,this.pendingGpayShippingDetails=r,this.pendingGpayShippingOption=l;const p=await new Promise((e,n)=>{const a=setTimeout(()=>{this.pendingGpayResolve=null,this.pendingGpayReject=null,n(new Error("Tokenization timed out"))},3e4);this.pendingGpayResolve=t=>{clearTimeout(a),e(t)},this.pendingGpayReject=e=>{clearTimeout(a),n(e)},this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"google_pay",encryptedToken:t,cardNetwork:i,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:o,amount:this.options.amount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})});if(p.__closeSheet)return{transactionState:"SUCCESS"};if(!p.success){const e=p.error??"Tokenization failed";return this.emitter.emit(D.Error,new Error(e)),this.emitter.emit(D.PaymentMethodFailed,{error:e}),{transactionState:"ERROR"}}const h=await this.createPaymentMethod({btTokenId:p.btTokenId,cardPayload:p.cardPayload,billingDetails:p.billingDetails,csessId:p.csessId,walletType:"google_pay"});return this.emitter.emit(D.PaymentMethodCreated,{paymentMethodId:h,wallet:"google_pay",billingDetails:o??void 0,shippingDetails:r,selectedShippingOption:l}),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,{transactionState:"SUCCESS"}}catch(e){return console.error("[PaypercutExpressCheckout] handleGooglePayAuthorized error:",e?.message??e),this.emitter.emit(D.Error,new Error(e?.message??"Google Pay authorization failed")),this.emitter.emit(D.PaymentMethodFailed,{error:e?.message??"Google Pay authorization failed"}),{transactionState:"ERROR"}}}async handleGooglePayDataChanged(e){const{callbackTrigger:t,shippingAddress:i,shippingOptionData:n}=e;if("INITIALIZE"===t)return G({amount:this.gpayCurrentAmount||this.options.amount,shippingOptions:this.currentShippingOptions},this.options.currency,this.options.countryCode);if("SHIPPING_ADDRESS"===t){return G(await new Promise(e=>{this.emitter.emit(D.ShippingAddressChange,{address:{country:i?.countryCode??"",state:i?.administrativeArea,city:i?.locality,postalCode:i?.postalCode},updateWith:t=>{t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions),null!=t.amount&&(this.gpayCurrentAmount=t.amount),e(t)}})}),this.options.currency,this.options.countryCode)}if("SHIPPING_OPTION"===t){const e=n?.id,t=this.currentShippingOptions.find(t=>t.id===e);return G(await new Promise(i=>{this.emitter.emit(D.ShippingOptionChange,{shippingOption:{id:e??"",label:t?.label??e??"",detail:t?.detail,amount:t?.amount??0},updateWith:e=>{null!=e.amount&&(this.gpayCurrentAmount=e.amount),i(e)}})}),this.options.currency,this.options.countryCode)}return{}}update(e){this.mounted?this.applePayPendingCallback&&this.applePayPendingCallback.resolve(e):console.warn("[PaypercutExpressCheckout] Cannot update: not mounted")}on(e,t){return this.emitter.on(e,t)}destroy(){if(!this.destroyed){if(this.tokenizeIframe){try{this.tokenizeIframe.remove()}catch{}this.tokenizeIframe=null}if(this.gpayContainer){try{this.gpayContainer.remove()}catch{}this.gpayContainer=null}if(this.applePayContainer)try{this.removeApplePayContainer()}catch{}this.gpayPaymentRequest=null,this.layoutResizeObserver&&(this.layoutResizeObserver.disconnect(),this.layoutResizeObserver=null),this.threeDSModal.close(),this.abortApplePaySession(),this.sessionActive=!1,this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}setSessionActive(e){this.sessionActive=e;const t=e?"0.5":"",i=e?"none":"";this.applePayContainer&&(this.applePayContainer.style.opacity=t,this.applePayContainer.style.pointerEvents=i),this.gpayContainer&&(this.gpayContainer.style.opacity=t,this.gpayContainer.style.pointerEvents=i)}completeApplePaySession(e){try{if(this.applePaySession){const t=window.ApplePaySession,i=e?t.STATUS_SUCCESS:t.STATUS_FAILURE;this.applePaySession.completePayment(i)}}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}abortApplePaySession(){try{this.applePaySession?.abort()}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}async createPaymentMethod(e){const{btTokenId:t,cardPayload:i,billingDetails:n,csessId:s,walletType:o}=e;if(!i||!t)throw new Error("[createPaymentMethod] Missing required tokenization data.");const r=new URL("/v1/payment_methods",a(this.options.apiUrl)),l={type:"card",key:this.options.publishableKey,card:{token:s??"",brand:i.brand??"",exp_month:i.exp_month??1,exp_year:i.exp_year??1,funding:i.funding??"",last4:i.last4??"",iin:i.bin??"",issuer:i.issuer??null,fingerprint:i.fingerprint??null,segment:i.segment??"",wallet:{type:o,dynamic_last4:null},three_d_secure_usage:{supported:!0}},billing_details:{name:n?.name??null,email:n?.email??null,phone:n?.phone??null,address:{city:n?.address?.city??null,country:n?.address?.country??null,line1:n?.address?.line1??null,line2:n?.address?.line2??null,postal_code:n?.address?.postalCode??null,state:n?.address?.state??null}},confirmation_token:{token_id:t}},p=await fetch(r.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),cache:"no-store"});if(!p.ok){const e=await p.text().catch(()=>`HTTP ${p.status}`);throw new Error(`Payment method creation failed (${p.status}): ${e}`)}return(await p.json()).id}postToTokenizeIframe(e){if(!this.tokenizeIframe?.contentWindow)return;const t=n(this.options.hostedCheckoutUrl);this.tokenizeIframe.contentWindow.postMessage(e,t)}buildThreeDSUrl(e){const t=n(this.options.hostedCheckoutUrl),i=new URL("/express/threeds",t);return i.searchParams.set("instanceId",this.instanceId),i.searchParams.set("sessionId",e.sessionId),i.searchParams.set("step",e.step),e.challengeUrl&&i.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&i.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&i.searchParams.set("threeDSVersion",e.threeDSVersion),i.searchParams.set("liveMode",String(e.liveMode??!1)),i.toString()}handle3DSShellCancel(){this.postToTokenizeIframe({type:"THREEDS_CANCELED",instanceId:this.instanceId,error:"User canceled 3DS authentication"}),this.threeDSModal.close(),this.emitter.emit(D.Cancel)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutExpressCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=n(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",instanceId:this.instanceId},t)}}const N=function(e){return new U(e)};let H=!1;const F=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,B=/^(0|(\d+(\.\d+)?(px|rem|em)))$/;function j(e){e&&(void 0===e.brandColor||F.test(e.brandColor)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.brandColor: "${e.brandColor}". Expected a hex color (#RGB or #RRGGBB). Value ignored.`),void 0===e.fontFamily||e.fontFamily.trim()||console.warn("[PaypercutCheckout] Invalid appearance.variables.fontFamily: value is empty. Value ignored."),void 0===e.logoUrl||/^https:\/\//.test(e.logoUrl)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.logoUrl: "${e.logoUrl}". Must start with https://. Value ignored.`),void 0===e.borderRadius||B.test(e.borderRadius.trim())||console.warn(`[PaypercutCheckout] Invalid appearance.variables.borderRadius: "${e.borderRadius}". Expected a CSS length like "8px", "0.5rem", or "0". Value ignored.`))}class ${constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.iframe=null,this.applePaySession=null,this.applePayBridgeTimeout=null,this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler),P(t.ui_mode??d.EMBEDDED)===d.EMBEDDED&&function(){if("undefined"==typeof window)return;if(window.ApplePaySession)return;if(H)return;H=!0;const e=document.createElement("script");e.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",e.crossOrigin="anonymous",e.async=!0,document.head.appendChild(e)}()}buildSrc(){const e=n(this.options.hostedCheckoutUrl),t=new URL(`/c/${this.options.id}`,e);if(this.options.locale){const e=h(this.options.locale);t.searchParams.set("locale",e)}if(this.options.lang){const e=h(this.options.lang);t.searchParams.set("lang",e)}{const e=P(this.options.ui_mode??d.EMBEDDED);e&&t.searchParams.set("ui_mode",e)}if(this.options.payment_methods&&this.options.payment_methods.length>0){(function(e){const t=[];for(const i of e)m(i)?t.push(i):console.warn(`[PaypercutCheckout] Invalid payment method: "${i}". Skipping.`);return 0===t.length&&(console.warn('[PaypercutCheckout] No valid payment methods provided. Defaulting to "card".'),t.push(c.CARD)),t})(this.options.payment_methods).forEach(e=>{t.searchParams.append("payment_methods",e)})}if(void 0!==this.options.wallet_options)if(0===this.options.wallet_options.length)t.searchParams.set("wallet_options",null);else{(function(e){const t=[];for(const i of e)g(i)?t.push(i):console.warn(`[PaypercutCheckout] Invalid wallet option: "${i}". Skipping.`);return t})(this.options.wallet_options).forEach(e=>{t.searchParams.append("wallet_options",e)})}return this.options.appearance?.preset&&t.searchParams.set("preset",this.options.appearance.preset),this.options.appearance?.theme&&t.searchParams.set("theme",this.options.appearance.theme),this.options.appearance?.variables&&Object.keys(this.options.appearance.variables).length>0&&(j(this.options.appearance.variables),t.searchParams.set("appearance_vars",JSON.stringify(this.options.appearance.variables))),void 0!==this.options.form_only&&t.searchParams.set("form_only",String(this.options.form_only)),void 0!==this.options.validate_form&&t.searchParams.set("validate_form",String(this.options.validate_form)),t.toString()}getContainer(){const e="string"==typeof this.options.containerId?document.querySelector(this.options.containerId):this.options.containerId;if(!e)throw new Error(`Container not found: ${this.options.containerId}`);return e}onMessage(e){if(!i(e.origin))return;const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.checkoutId||t.checkoutId===this.options.id))switch(t.type){case"CHECKOUT_LOADED":this.emitter.emit(y.Loaded);break;case"CHECKOUT_PROCESSING":this.emitter.emit(y.Processing,{checkoutId:t.checkoutId});break;case"CHECKOUT_SUCCESS":const{payment_method:i={},payment:n=null}=t;this.emitter.emit(y.Success,{payment_method:i,payment:n});break;case"CHECKOUT_ERROR":this.emitter.emit(y.Error,(t&&t.error)??t);break;case"CHECKOUT_CANCEL":this.emitter.emit(y.Cancel,{checkoutId:t.checkoutId,wallet:t.wallet});break;case"CHECKOUT_EXPIRED":this.emitter.emit(y.Expired);break;case"CHECKOUT_RESIZE":this.emitter.emit(y.Resize,t.height),this.handleResize(t.height);break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.threeDSModal.show(t),this.emitter.emit(y.ThreeDSStarted);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSComplete);break;case"THREEDS_CANCELED":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSCanceled);break;case"THREEDS_ERROR":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSError,t.error);break;case"FORM_VALIDATION":this.emitter.emit(y.FormValidation,{checkoutId:t.checkoutId,wallet:t.wallet});break;case f:this.handleApplePayStart(t);break;case C:this.handleApplePayMerchantSession(t.merchantSession);break;case b:this.abortApplePaySession();break;case E:this.handleApplePayPaymentResult(!0===t.success)}}render(){if(!this.mounted)try{const e=this.getContainer();this.iframe=document.createElement("iframe"),this.iframe.id="paypercut-checkout-iframe",this.iframe.src=this.buildSrc(),this.iframe.allow="payment *; clipboard-write",this.iframe.setAttribute("frameborder","0"),this.iframe.setAttribute("allowpaymentrequest","true"),this.iframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox"),Object.assign(this.iframe.style,{width:"100%",height:"100%",border:"none",display:"block"}),e.appendChild(this.iframe),this.mounted=!0}catch(e){throw console.error("[PaypercutCheckout] Failed to render:",e),e}}submit(){if(this.mounted)try{this.postToIframe({type:"START_PROCESSING",checkoutId:this.options.id})}catch(e){throw console.error("[PaypercutCheckout] Failed to submit payment:",e),e}}postToIframe(e){if(!this.iframe?.contentWindow)return void console.error("[PaypercutCheckout] Cannot post message: iframe not mounted");const t=n(this.options.hostedCheckoutUrl);this.iframe.contentWindow.postMessage(e,t)}handleResize(e){!this.iframe||"number"!=typeof e||e<=0||(this.iframe.style.height=`${e}px`)}buildThreeDSUrl(e){const t=n(this.options.hostedCheckoutUrl),i=new URL(`/c/${this.options.id}/threeds`,t);return i.searchParams.set("sessionId",e.sessionId),i.searchParams.set("step",e.step),e.challengeUrl&&i.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&i.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&i.searchParams.set("threeDSVersion",e.threeDSVersion),i.searchParams.set("liveMode",String(e.liveMode??!1)),i.toString()}handle3DSShellCancel(){this.postToIframe({type:"THREEDS_CANCELED",checkoutId:this.options.id,reason:"sdk_shell_cancel"}),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSCanceled)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=n(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",checkoutId:this.options.id},t)}handleApplePayStart(e){this.abortApplePaySession();const t=window.ApplePaySession;if(!t)return void this.postToIframe({type:v,checkoutId:this.options.id});const i=t.supportsVersion?.(14)?14:3;let n;try{n=new t(i,e.request)}catch(e){return console.error("SecurityError"===e?.name?'[PaypercutCheckout] Apple Pay blocked — parent page missing allow="payment" on iframe':"[PaypercutCheckout] Failed to create ApplePaySession",e),void this.postToIframe({type:v,checkoutId:this.options.id})}this.applePaySession=n,n.onvalidatemerchant=e=>{this.applePayBridgeTimeout=setTimeout(()=>this.abortApplePaySession(),15e3),this.postToIframe({type:S,checkoutId:this.options.id,validationURL:e.validationURL})},n.onpaymentauthorized=e=>{this.postToIframe({type:w,checkoutId:this.options.id,payment:e.payment})},n.oncancel=()=>{this.applePaySession=null,this.postToIframe({type:A,checkoutId:this.options.id})},n.begin()}handleApplePayMerchantSession(e){if(this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null),this.applePaySession)try{this.applePaySession.completeMerchantValidation(e)}catch(e){console.error("[PaypercutCheckout] completeMerchantValidation failed",e),this.abortApplePaySession(),this.postToIframe({type:v,checkoutId:this.options.id})}}handleApplePayPaymentResult(e){if(!this.applePaySession)return;const t=window.ApplePaySession;try{this.applePaySession.completePayment(e?t.STATUS_SUCCESS:t.STATUS_FAILURE)}catch(e){console.error("[PaypercutCheckout] completePayment failed",e)}this.applePaySession=null}abortApplePaySession(){this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null);try{this.applePaySession?.abort()}catch{}this.applePaySession=null}destroy(){if(!this.destroyed){if(this.iframe)try{this.iframe.remove(),this.iframe=null}catch(e){console.error("[PaypercutCheckout] Error removing iframe:",e)}this.threeDSModal.close(),this.abortApplePaySession(),this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}isMounted(){return this.mounted}completeFormValidation(e){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"success"}):console.warn("[PaypercutCheckout] Cannot complete form validation: not mounted")}updateAppearance(e){this.mounted?(j(e.variables),this.postToIframe({type:"UPDATE_APPEARANCE",checkoutId:this.options.id,appearance:e})):console.warn("[PaypercutCheckout] Cannot update appearance: not mounted")}failFormValidation(e,t){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"failed",errors:t}):console.warn("[PaypercutCheckout] Cannot fail form validation: not mounted")}}const V=function(e){return new $(e)};return V.version=t.version,"undefined"!=typeof window&&(window.PaypercutExpressCheckout=N),V}();
|
|
2
2
|
//# sourceMappingURL=paypercut-checkout.iife.min.js.map
|