@getopenpay/openpay-js 0.2.35 → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -22,7 +22,7 @@ ${n.message}`),n.message)}else return Sn(n.message);if(typeof n=="object")try{re
22
22
  `;const t=document.createElement("div"),r=t.attachShadow({mode:"open"});r.appendChild(e.content.cloneNode(!0));const o=r.querySelector("#three-ds-iframe"),s=r.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:o,cancelButton:s}};function al(n,e,t){const r=async()=>{try{const s=await Xc(n,t);s&&(clearInterval(o),e(s))}catch{}};r();const o=setInterval(r,so);return o}function il({elements:n,pollingInterval:e,resolve:t}){const r=()=>{clearInterval(e),n.host.remove(),t({status:V.CANCELLED})};return n.cancelButton.addEventListener("click",r),()=>{n.cancelButton.removeEventListener("click",r)}}async function fn(n){const{url:e,baseUrl:t}=n,r=po(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{r.host.remove()},1e3),o(l),c==null||c()},i=al(r.iframe,s,new URL(t).origin),c=il({elements:r,pollingInterval:i,resolve:o})})}const fo=async n=>{const e=await fn(n);if(e.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===V.FAILURE)throw new Error("3DS verification failed");return e.status!==V.SUCCESS&&un(e.status),{href:e.href}},cl=(n,e)=>{const t=window.open(e,"_blank");if(!t)throw new Error(`${n} popup window blocked. Please allow popups for this site.`);return t},ll=async(n,e,t,r)=>{const{err__:o}=F("popup-verify");return new Promise((s,i)=>{const c=cl(n,r),l=setInterval(async()=>{try{const u=await Hc(e,t);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${n} payment cancelled`)}catch(u){o(re(u)),clearInterval(l),i(re(u))}},1e3)})},{log__:ul,err__:Gn}=F("airwallex-cc"),dl=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),pl=n=>{const e=dl.safeParse(n);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",r=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(n)}`;throw Gn(r),new Error(t)}return e.data},fl=n=>(n==null?void 0:n["op-airwallex-3ds-url"])!==void 0,ml=n=>{try{const e=new URL(n??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return ul(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw Gn(t,`Resulting URL: ${n}.
23
23
  Error: ${re(e)}`),new Error(t)}},hl=async(n,e)=>{const t=pl(e),r=await fo({url:t["op-airwallex-3ds-url"],baseUrl:n}),o=ml(r.href??""),s=t["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Gn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},mo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),ho=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:yo,err__:_o}=F("common-cc"),je=(n,e,t)=>{if(t){yo(`Received default field values: ${JSON.stringify(t)}`);for(const[o,s]of Object.entries(t))n[o]||(n[o]=s)}const r=Tt.safeParse(n);if(!r.success){const o=r.error.format(),s=pr(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw _o("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},yl=(n,e)=>{for(const t of n)if(t.success===!1)throw t.errors.forEach(r=>{const o=ur.safeParse(r.elementType);if(!o.success)_o(`Unknown field name in onValidationError: ${r.elementType}. Error object:`,r);else{const s=o.data;e(s,r.errors)}}),yo(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},{log__:mn}=F("awx-apple-pay");async function _l(n,e){try{const r=(await zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:n.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(t){throw e.session.abort(),t}}async function gl(n,e){if(!n.redirect_url)throw new Error("No redirect URL found");mn("3DS Required, starting verification...",n);const{status:t}=await fn({url:n.redirect_url,baseUrl:e.baseUrl});if(mn(`╰ 3DS verification completed [Status: ${t}]`),t===V.CANCELLED)throw new Error("3DS verification cancelled");if(t===V.FAILURE)throw new Error("3DS verification failed");const r=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:n.their_pm_id,airwallex_consent_id:n.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return mn("[2nd] Confirm payment flow response",r),r}async function vl(n,e){var t,r,o,s,i;try{const c=n.payment,l=lo(e.nonCdeFormInputs,c),u=je(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);E("billing_details_received",{...u});const h=(await it(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!h)throw new Error("No consent ID received from payment flow");let f=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:h,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});mn("[1st] Confirm payment flow response",f);let _=(r=(t=f.payment_methods)==null?void 0:t[0])==null?void 0:r.id;const w=(o=f.required_user_actions)==null?void 0:o.find(C=>C.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(f=await gl(w,e),_=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!_)throw new Error("No PM ID found");const T={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(T),pn({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Dt,err__:go}=F("awx-apple-pay"),wl=ze(async({context:n,formCallbacks:e})=>{const t={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,mo);if(!r)return t;if(Dt("Loading Apple Pay script"),await co(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Dt("Apple Pay is not available on this device/browser"),t;if(Dt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Dt("No active cards available for Apple Pay"),t;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=n.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async p=>{try{await Z.airwallexApplePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(h){go("Apple Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),bl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:r,formCallbacks:o})=>{var _;const s=ue(n.checkoutPaymentMethods,mo),{overridePaymentRequest:i,initialPreview:c}=r,l=n.anyCdeConnection,u=await q(l),d=u.mode==="setup",p=uo({overridePaymentRequest:i,initialPreview:c,prefill:{...u},defaultLabel:(_=s==null?void 0:s.metadata)==null?void 0:_.processor_account_name}),h=new ApplePaySession(3,p),f={session:h,connection:n.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:n.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:Qr(u,["brand"]),overridePaymentRequest:i}),new Promise((w,T)=>{const C=()=>{Dt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))};h.oncancel=C,h.onvalidatemerchant=async x=>{try{await _l(x,f)}catch(R){T(R)}},h.onpaymentmethodselected=()=>{const x={newTotal:{...p.total}};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{E("apple_pay_payment_authorized");try{const R=await vl(x,f);w(R)}catch(R){T(R)}},h.begin()}).catch(w=>{throw go("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),hn=({gateway:n,gatewayMerchantId:e,merchantName:t,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,h;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((h=s==null?void 0:s.amount)==null?void 0:h.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:n,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:t},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?typeof s.googlePayPaymentRequest=="function"?{...d,...s.googlePayPaymentRequest(d)}:{...d,...s.googlePayPaymentRequest}:d},vo=()=>io({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var n,e;return!!((e=(n=window.google)==null?void 0:n.payments)!=null&&e.api)}});let Bn=null;const wo=async n=>await Jr(n)==="prod"?"PRODUCTION":"TEST",yn=async(n,e)=>{const t=await wo(n);return Bn===null&&(Bn=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),Bn},El=n=>{const e=n.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?dr.parse(e):null},bo=(n,e)=>{var o,s,i,c;const t={...n},r=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(r){const[l,...u]=((c=(i=r.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;t[m.EMAIL]=t[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[m.COUNTRY]=t[m.COUNTRY]||r.countryCode||"US",t[m.ADDRESS]=t[m.ADDRESS]||r.address1||"",t[m.CITY]=t[m.CITY]||r.locality||"",t[m.ZIP_CODE]=t[m.ZIP_CODE]||r.postalCode||"00000",t[m.STATE]=t[m.STATE]||r.administrativeArea||"";const p=t[m.FIRST_NAME]||l||"",h=t[m.LAST_NAME]||d||"";p||h?(t[m.FIRST_NAME]=p,t[m.LAST_NAME]=h):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]="")}return t},{log__:de,err__:lt}=F("awx-google-pay"),kl=ze(async({context:n,formCallbacks:e})=>{var p,h;const t={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,ho);if(!r)return t;de("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return lt("No gateway merchant ID found in processor account"),t;if(de("Loading Google Pay script"),await vo(),!((h=(p=window.google)==null?void 0:p.payments)!=null&&h.api))return lt("Google Pay SDK not loaded properly"),t;if(await wo(n.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return lt("Google Pay merchant ID is required for production environment"),t;de("Google Pay SDK loaded",window.google.payments);try{const f=hn({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),_=await yn(n.baseUrl,f),{result:w}=await _.isReadyToPay(f);if(!w)return de("Google Pay is not available for this user"),t}catch(f){return lt("Error checking Google Pay availability",f),t}const i=n.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async f=>{try{Z.airwallexGooglePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(_){lt("Google Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Cl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{var f,_,w,T,C,x,R;de("Starting Google Pay flow...");const s=ue(n.checkoutPaymentMethods,ho),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=hn({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=n.anyCdeConnection,p=await q(d);E("google_pay_flow_started",{processor_name:s.processor_name,prefill:Qr(p,["brand"]),overridePaymentRequest:c});const h=await yn(n.baseUrl,u);try{const j=await h.loadPaymentData(u);de("Google Pay Payment data",j);const J=bo(t,j),W=je(J,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);E("billing_details_received",{...W});const Se=(_=(f=j.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!Se)throw new Error("No payment token received from Google Pay");const zu=await it(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:W[m.EMAIL],new_customer_first_name:W[m.FIRST_NAME],new_customer_last_name:W[m.LAST_NAME],new_customer_address:{zip_code:W[m.ZIP_CODE],country:W[m.COUNTRY]}}),gn=El(zu);de("Start flow next actions",gn);let Ye=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:gn==null?void 0:gn.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Se}}}});de("[1st] Confirm payment flow response",Ye);let Wn=(T=(w=Ye.payment_methods)==null?void 0:w[0])==null?void 0:T.id;const We=(C=Ye.required_user_actions)==null?void 0:C.find(Vt=>Vt.type==="airwallex_payment_consent");if(We&&We.redirect_url){de("3DS Required, starting verification...",We);const{status:Vt}=await fn({url:We.redirect_url,baseUrl:n.baseUrl});if(de(`╰ 3DS verification completed [Status: ${Vt}]`),Vt===V.CANCELLED)throw new Error("3DS verification cancelled");if(Vt===V.FAILURE)throw new Error("3DS verification failed")}if(We&&!Wn&&(Ye=await ce(d,{secure_token:p.token,their_pm_id:We.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:We.consent_id}}),de("[2nd] Confirm payment flow response",Ye),Wn=(R=(x=Ye.payment_methods)==null?void 0:x[0])==null?void 0:R.id),!Wn)throw new Error("No PM ID found");return pn({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:W,confirmResult:Ye,usePayFirstFlow:!1})}catch(j){throw lt("Google Pay payment error",j),E("google_pay_payment_error",{error:j}),new Error((j==null?void 0:j.message)??"Unknown error")}}),Eo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),ko=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})});async function Sl(n,e){try{const r=(await zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:n.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(t){throw e.session.abort(),t}}async function Pl(n,e){var t,r;try{const o=n.payment,s=lo(e.nonCdeFormInputs,o),i=je(s,e.formCallbacks.get.onValidationError);E("billing_details_received",{...i}),await it(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((r=(t=l.payment_methods)==null?void 0:t[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),pn({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const{log__:_n,err__:Co}=F("authnet-applepay"),Al=ze(async({context:n,formCallbacks:e})=>{const t={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,Eo);if(!r)return t;if(_n("Loading Apple Pay script"),await co(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return _n("Apple Pay is not available on this device/browser"),t;if(!await ApplePaySession.canMakePayments())return _n("No active cards available for Apple Pay"),t;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=n.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await ct(i,c.token,l,void 0),d=async p=>{try{await Z.authorizeNetApplePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(h){Co("Apple Pay payment error",h),E("apple_pay_payment_error",{error:h}),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Tl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:r,formCallbacks:o})=>{var _;const{initialPreview:s,overridePaymentRequest:i}=r,c=ue(n.checkoutPaymentMethods,Eo),l=n.anyCdeConnection,u=await q(l),d=u.mode==="setup",p=uo({overridePaymentRequest:i,initialPreview:s,prefill:u,defaultLabel:(_=c==null?void 0:c.metadata)==null?void 0:_.processor_account_name});E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:u,overridePaymentRequest:i});const h=new ApplePaySession(3,p),f={session:h,connection:n.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:e.metadata,prefill:u,isSetupMode:d,baseUrl:n.baseUrl,formCallbacks:o};return new Promise((w,T)=>{h.oncancel=()=>{_n("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async C=>{try{await Sl(C,f)}catch(x){T(x)}},h.onpaymentmethodselected=()=>{const C={newTotal:p.total};h.completePaymentMethodSelection(C)},h.onpaymentauthorized=async C=>{E("apple_pay_payment_authorized");try{const x=await Pl(C,f);w(x)}catch(x){T(x)}},h.begin()}).catch(w=>{throw Co("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),{log__:Ge,err__:Lt}=F("authnet-googlepay"),Il=ze(async({context:n,formCallbacks:e})=>{var d,p;Ge("Initializing Authnet GooglePay flow");const t={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ue(n.checkoutPaymentMethods,ko);if(!r)return t;Ge("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return Lt("No gateway merchant ID found in processor account"),t;if(Ge("Loading Google Pay script"),await vo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Lt("Google Pay SDK not loaded properly"),t;Ge("Google Pay SDK loaded",window.google.payments);try{const h=hn({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),f=await yn(n.baseUrl,h),{result:_}=await f.isReadyToPay(h);if(!_)return Ge("Google Pay is not available for this user"),t}catch(h){return Lt("Error checking Google Pay availability",h),t}const s=n.anyCdeConnection,i=await q(s),c=i.mode==="setup",l=await ct(s,i.token,c,void 0),u=async h=>{try{Z.authorizeNetGooglePay.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,initResult:void 0,customParams:{...h,initialPreview:l}})}catch(f){Lt("Google Pay payment error",f),E("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),xl=Ie(async({context:n,nonCdeFormInputs:e,checkoutPaymentMethod:t,formCallbacks:r,customParams:o})=>{var f,_,w,T;const{initialPreview:s,overridePaymentRequest:i}=o,l=ue(n.checkoutPaymentMethods,ko).metadata,u=hn({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=n.anyCdeConnection,p=await q(d);E("google_pay_flow_started",{processor_name:t.processor_name,prefill:p,overridePaymentRequest:i});const h=await yn(n.baseUrl,u);try{const C=await h.loadPaymentData(u);Ge("Google Pay Payment data",C);const x=bo(e,C),R=je(x,r.get.onValidationError);E("billing_details_received",{...R});const j=(_=(f=C.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!j)throw new Error("No payment token received from Google Pay");const J=await it(d,{payment_provider:t.provider,checkout_payment_method:t,new_customer_email:R[m.EMAIL],new_customer_first_name:R[m.FIRST_NAME],new_customer_last_name:R[m.LAST_NAME],new_customer_address:{zip_code:R[m.ZIP_CODE],country:R[m.COUNTRY]}});Ge("Start payment flow response",J);const W=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:t.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(j)}}});if(!((T=(w=W.payment_methods)==null?void 0:w[0])==null?void 0:T.id))throw new Error("No PM ID found");return pn({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:t,requiredFormFields:R,confirmResult:W,usePayFirstFlow:!1})}catch(C){throw Lt("Google Pay payment error",C),E("google_pay_payment_error",{error:C}),new Error((C==null?void 0:C.message)??"Unknown error")}}),{log__:Rl,err__:So}=F("pockyt-cc"),Nl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Ol=n=>{const e=Nl.safeParse(n);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",r=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(n)}`;throw So(r),new Error(t)}return e.data},Po=n=>{try{const e=new URL(n??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Rl(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw So(t,`Resulting URL: ${n}.
24
24
  Error: ${re(e)}`),new Error(t)}},Ml=(n,e)=>new URL(n).searchParams.get(e),Dl=n=>(n==null?void 0:n["op-pockyt-3ds-url"])!==void 0,Ll=async(n,e)=>{const t=Ol(e),r=await fo({url:t["op-pockyt-3ds-url"],baseUrl:n});return{existing_cc:{vault_id:Po(r.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},Fl=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),jl=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:ut,err__:Ft}=F("adyen-cc"),Ul=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":Fl,"op-adyen-action":a.string()}),Ao="Unable to process your credit card. Please contact support for assistance.",$l=n=>{const e=Ul.safeParse(n);if(!e.success)throw Ft(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(n)}`),new Error(Ao);return e.data},Vl=n=>JSON.parse(n),To=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Zl=async()=>{ut("Waiting for Adyen SDK to load...");for(let n=0;n<10;n++)To()||await An(500);if(!To())throw Ft("Adyen SDK not loaded properly"),new Error(Ao);return ut("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},zl=n=>{const{headers:e,locale:t,countryCode:r,component:o,host:s,cancelButton:i}=n,c=Vl(e["op-adyen-action"]);return ut(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{ut("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",h),s.remove()},d=_=>{Ft("Authentication failed. Result:",_),l({status:V.FAILURE,cleanup:u})},p=_=>{Ft("Adyen error:",_),l({status:V.FAILURE,cleanup:u})},h=()=>{l({status:V.CANCELLED,cleanup:u})};i.addEventListener("click",h);const f=(_,w,T)=>{s.remove(),l({status:V.SUCCESS,additionalDetails:_,cleanup:u})};Zl().then(_=>_({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:t,countryCode:r,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(_=>{_.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},Gl=n=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,t=n??e,r=jl.safeParse(t);return r.success?(ut(`Resolved locale: ${r.data}`),r.data):(Ft(`Resolved invalid locale: ${t}. Defaulting to en-US.`),"en-US")},Bl=n=>(n==null?void 0:n["op-adyen-action"])!==void 0,ql=async(n,e,t)=>{const r=$l(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=po("http://example.com");i.replaceWith(o);const l=await zl({headers:r,locale:Gl(t),countryCode:n,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===V.FAILURE)throw new Error("3DS verification failed");if(l.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===V.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return ut("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else un(l.status)},{log__:D,err__:Io}=F("common-cc"),{log__:xo}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Yl=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{var u;D("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=n.anyCdeConnection,i=await q(s);E("common_cc_flow_started",{...e,prefill:i}),D(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=je(t,r.get.onValidationError);E("billing_details_received",{...c});const l={session_id:n.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin},payment_route_id:o.paymentRouteId};try{D(`├ Tokenizing card info in CDE [Session: ${n.elementsSessionId}]`);const d=await Jc(o.currentCdeConnections,{session_id:n.elementsSessionId});if(yl(d,r.get.onValidationError),i.mode==="setup"){D(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await Qc(s,l);return D(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{D(`├ Initial checkout flow. Checking out card info in CDE [Session: ${n.elementsSessionId}]`);const p=await oo(s,l);return D("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof ro&&d.originalErrorMessage.includes("3DS_REQUIRED")){D("├ Card requires 3DS, starting non-legacy payment flow"),D("Received 3DS error response headers:",d.response.headers),E("3ds_required",{...e,...d.response.headers});const p=Dl(d.response.headers);if(p){D("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await Ll(n.baseUrl,d.response.headers);l.extra_metadata.pockyt=C}if(fl(d.response.headers)){D("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await hl(n.baseUrl,d.response.headers);l.extra_metadata.airwallex=C}if(Bl(d.response.headers)){D("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const C=await ql(t[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=C}const _=await qc(s,l);D("├ Payment flow result:",_);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?D("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(D("├ Using stripe 3DS flow"),await Ql(_)):(D("├ Using common 3DS flow"),await Jl(_,n.baseUrl));const T=_.cc_pm_id;if(i.mode==="setup"){D(`├ Confirming payment flow [cc_pm_id: ${T}]`);const C=await ce(s,{secure_token:i.token,existing_cc_pm_id:T});D("├ Confirm payment flow result received Result:",C);const x=Mt(C);return D(`╰ Setup completed successfully [PM ID: ${x.payment_method_id}]`),{mode:"setup",result:x}}else{D(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const C=await oo(s,{...l,existing_cc_pm_id:T,do_not_use_legacy_cc_flow:w});return D("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw Io("╰ Error checking out card info in CDE"),Io(d),d}}),Wl=n=>{const e=n.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Sa.parse(e)},Hl=["airwallex_payment_consent","adyen"],Kl=n=>{const e=n.required_user_actions.find(t=>Hl.includes(t.type));if(!e)throw new Error("No common 3DS action found");return Ea.parse(e)},Jl=async(n,e)=>{const t=Kl(n);if(t.redirect_url==="3DS_COMPLETE"){D("├ 3DS flow completed successfully"),E("3ds_complete");return}D(`├ Using common 3DS flow [URL: ${t.redirect_url}]`),E("3ds_redirect",{...t});const{status:r}=await fn({url:t.redirect_url,baseUrl:e});if(D(`╰ 3DS verification completed [Status: ${r}]`),r===V.CANCELLED)throw E("3ds_cancelled"),new Error("3DS verification cancelled");if(r===V.FAILURE)throw E("3ds_failure"),new Error("3DS verification failed")},Ql=async n=>{const e=Wl(n);E("3ds_stripe_redirect",{...e}),xo(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Na(e),E("3ds_stripe_complete"),xo("╰ Stripe 3DS flow completed successfully")},Xl=1,eu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:ee,err__:Ro}=F("loop-crypto"),tu=a.object({loopFirstName:$,loopLastName:$,loopEmail:$,[m.PROMOTION_CODE]:O}),nu=a.object({loopFirstName:O,loopLastName:O,loopEmail:O,[m.PROMOTION_CODE]:O}),No=(n,e,t,r)=>{const o=t.safeParse(n);if(!o.success){const s=o.error.format(),i=pr(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Ro("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},ru=ze(async({context:n})=>{ee("Checking if there are any CPMs for Loop Crypto...");const e=ue(n.checkoutPaymentMethods,eu);ee(`checkoutPaymentMethod: ${JSON.stringify(e)}`),ee("Starting Loop Crypto flow...");const t=await q(n.anyCdeConnection),r=await zn(n.anyCdeConnection,{checkout_payment_method:e});if(t.mode!=="setup"&&!e.metadata.supported_currencies.includes(t.currency))throw Error(`Currency ${t.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!r||!r.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=r.next_action_metadata;let s;t.mode==="setup"?s=Xl:s=t.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=Xt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),ou=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{ee("Running Loop flow..."),ee("context",n),ee("checkoutPaymentMethod",e),ee("nonCdeFormInputs",t),ee("flowCallbacks",r),ee("customParams",o);let s;o!=null&&o.success?s=No(t,r.get.onValidationError,tu):s=No(t,r.get.onValidationError,nu);const i=n.anyCdeConnection,c=await q(n.anyCdeConnection),l=c.mode!=="setup",u=await it(n.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await ce(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_debug_info:o.success?void 0:o.debugInfo,loop_success:o.success}});if(ee(`Confirm result: ${d}`),c.mode==="setup"){ee("Doing payment setup..."),ee("├ Confirm payment flow result received Result:",d);const p=Mt(d);return ee(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(ee("Doing checkout..."),!d.pay_first_success_response)throw Ro("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}}),{log__:be,err__:Oo}=F("pockyt-paypal"),su=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const au=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{var W,Se;be("Running Pockyt Paypal flow...");const s=n.anyCdeConnection,i=await q(s);be("Verifying CPM...");const c=su.parse(e);be("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=je(t,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=ol(u);be(`Starting payment flow... Mode: ${i.mode}`);const p=Xt(),h=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:h,pay_first_flow_cart_info:h?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((W=o==null?void 0:o.settings)!=null&&W.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},_=new URL("/app/pre-action/start/",n.baseUrl).toString(),w=btoa(JSON.stringify(f)),T=new URLSearchParams({st:i.token,r:w}),C=`${_}?${T.toString()}`;if((Se=o==null?void 0:o.settings)!=null&&Se.useRedirectFlow)throw be("Starting redirect mode for PayPal..."),window.location.href=C,await An(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");be("Starting popup mode for PayPal..."),be("Opening paypal iframe...");const x=await ll("PayPal",s,p,C);be("Paypal flow result",x);const R=Po(x.href),j=Ml(x.href,"catt");if(!j)throw Oo("Checkout attempt ID not found in redirect URL:",x.href),new Error("Checkout attempt ID not found in redirect URL");be(`Confirming payment flow using vault ID ${R}`);const J=await ce(s,{secure_token:i.token,their_pm_id:R,checkout_attempt_id:h?j:void 0});if(be("Confirm payment flow result",J),i.mode==="setup")return{mode:"setup",result:{payment_method_id:J.payment_methods[0].id}};if(!J.pay_first_success_response)throw Oo("Checkout failed, no pay-first success response:",J),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:J.pay_first_success_response}}),Mo="ojs-stripe-link-btn",{log__:Y,err__:iu}=F("stripe-link"),cu=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),lu=a.array(a.object({our_existing_pm_id:a.string()})).length(1),uu=ze(async({context:n,formCallbacks:e})=>{const t=n.customInitParams.stripeLink;Y("Checking if there are any CPMs for Stripe Link...");const r=ue(n.checkoutPaymentMethods,cu);Y("Starting stripe link flow...");const o=n.anyCdeConnection,s=await q(o),i=s.mode==="setup";Y("Creating stripe elements...");const c=await ct(o,s.token,i,void 0),{elements:l,stripe:u}=await Ta(r.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});Y("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),p=()=>{d.mount(`#${Mo}`)},h=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?Y("NOT mounting stripe link button (doNotMountOnInit is true)"):(Y("Mounting stripe link button..."),p()),d.on("click",async f=>{if(Y("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){Y("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{Y("Stripe Link window confirmed",f);const _=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});_.error?(iu("error",_.error),e.get.onCheckoutError(_.error.message??"Stripe Link unknown error")):(Y("paymentMethod",_.paymentMethod),Z.stripeLink.run({context:n,checkoutPaymentMethod:r,nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{stripePM:_.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:h,waitForButtonToMount:async()=>await fu(Mo)}}}),du=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o})=>{Y("Running Stripe Link flow...");const s=n.anyCdeConnection;Y("Merging PM fields with form fields...");const i=pu(t,o.stripePM),c=je(i,r.get.onValidationError);E("billing_details_received",{...c}),Y("Starting payment flow...");const l=await it(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[m.EMAIL],new_customer_first_name:c[m.FIRST_NAME],new_customer_last_name:c[m.LAST_NAME],new_customer_address:{zip_code:c[m.ZIP_CODE],country:c[m.COUNTRY]}});Y("Start payment flow response",l);const d=lu.parse(l.required_user_actions)[0].our_existing_pm_id,p=await q(s);if(p.mode==="setup"){Y("Doing payment setup...");const h=await ce(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:Mt(h)}}else{Y("Doing checkout...");const h={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:c[m.EMAIL],customer_zip_code:c[m.ZIP_CODE],customer_country:c[m.COUNTRY],promotion_code:c[m.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zn(s,h)}}}),pu=(n,e)=>{var l,u,d,p,h;const t={...n},[r,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;t[m.EMAIL]=t[m.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||((p=e.billing_details.address)==null?void 0:p.postal_code)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||((h=e.billing_details.address)==null?void 0:h.country)||"US";const i=t[m.FIRST_NAME]||r||"",c=t[m.LAST_NAME]||s||"";return i||c?(t[m.FIRST_NAME]=i,t[m.LAST_NAME]=c):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]=""),Y("Final form inputs:",t),t},fu=n=>new Promise(e=>{const t=()=>{const r=document.getElementById(n);r?e(r):requestAnimationFrame(t)};t()}),{log__:X,err__:mu}=F("stripe-pr"),hu=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),yu=ze(async({context:n,formCallbacks:e})=>{X("Checking if there are any CPMs for Stripe PR...");const t=ue(n.checkoutPaymentMethods,hu);X("Initializing Stripe PR flow...");const r=n.anyCdeConnection,o=await q(r),s=o.mode==="setup";X("Getting initial preview amount");const i=await ct(r,o.token,s,void 0),c=await Ia(t.metadata.stripe_pk,i.amountAtom,i.currency,s);X("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return mu("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};X("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>Z.stripePR.run({context:n,checkoutPaymentMethod:jt(n.checkoutPaymentMethods,d),nonCdeFormInputs:ge(n.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:le.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:le.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),_u=Ie(async({context:n,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:r,customParams:o,initResult:s})=>{if(X("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=n.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const _=o.overridePaymentRequest;X("Overriding PR amount with",_);const w=typeof _.applePayPaymentRequest=="function"?_.applePayPaymentRequest({}):_.applePayPaymentRequest;vu(c,_.amount,_.pending,w,_.label)}X("Showing PR dialog..."),c.show();const l=await xa(c);X("Stripe PM added event:",l),X("Merging PM fields with form fields...");const u=gu(t,l),d=je(u,r.get.onValidationError);E("billing_details_received",{...d}),X("PR dialog finished. Starting payment flow...",d);const p=await Yc(i,{fields:d,checkoutPaymentMethod:e}),h=wu(p);X("Confirming PR with Stripe..."),await Ra(h,l);const f=await q(i);if(f.mode==="setup"){X("Confirming payment flow for setup...");const _=await ce(i,{secure_token:f.token});return{mode:"setup",result:Mt(_)}}else{X("Performing checkout...");const _={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zn(i,_)}}}),gu=(n,e)=>{var d,p,h,f;const t={...n},[r,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(h=e.paymentMethod)==null?void 0:h.billing_details)==null?void 0:f.address,c=e.shippingAddress;t[m.EMAIL]=t[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=t[m.FIRST_NAME]||r||"",u=t[m.LAST_NAME]||s||"";return l||u?(t[m.FIRST_NAME]=l,t[m.LAST_NAME]=u):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]=""),X("Final form inputs:",t),t},vu=(n,e,t,r,o)=>{n.update({total:{amount:e.amountAtom,label:o??"Total",pending:t},currency:e.currency,applePay:r})},wu=n=>{if(n.required_user_actions.length!==1)throw new Error(`Error occurred.
25
- Details: got ${n.required_user_actions.length} required user actions`);return Pa.parse(n.required_user_actions[0])},jt=(n,e,t)=>{const r=n.filter(o=>{const s=t===void 0?!0:o.processor_name===t,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",n),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);return r.length!==1&&(console.warn("CPMs list",n),console.warn(`More than one CPM found with provider '${e}' and processor '${t}'`),E("more_than_one_cpm_found",{provider:e,processor:t,cpms:n})),r[0]},Z={commonCC:{init:async()=>{},run:Yl},stripePR:{init:yu,run:_u},stripeLink:{init:uu,run:du},pockytPaypal:{run:au},airwallexGooglePay:{init:kl,run:Cl},airwallexApplePay:{init:wl,run:bl},loopCrypto:{init:ru,run:ou},authorizeNetApplePay:{init:Al,run:Tl},authorizeNetGooglePay:{init:Il,run:xl}},{log__:bu,err__:Eu}=F("init-flows"),Be=(n,e)=>{const t=new Ot;return{publisher:t,initialize:async r=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);bu(`✔ ${n} flow initialized successfully. Result:`,o),t.set(o)}catch(o){Eu(`𝙭 ${n} flow initialization failed. Error:`,re(o),"Details:",o),t.throw(o,re(o))}}}},ku=async(n,e,t)=>{await Promise.all(Object.values(n).map(r=>r.initialize({context:e,formCallbacks:t})))},Cu=()=>({stripePR:Be("Stripe PR",Z.stripePR.init),stripeLink:Be("Stripe Link",Z.stripeLink.init),airwallexGooglePay:Be("Airwallex GooglePay",Z.airwallexGooglePay.init),airwallexApplePay:Be("Airwallex ApplePay",Z.airwallexApplePay.init),loop:Be("Loop",Z.loopCrypto.init),authorizeNetGooglePay:Be("Authnet GooglePay",Z.authorizeNetGooglePay.init),authorizeNetApplePay:Be("Authnet ApplePay",Z.authorizeNetApplePay.init)}),{err__:Su}=F("form-callbacks"),pe=a.function().optional(),Do=a.object({onFocus:pe,onBlur:pe,onChange:pe,onLoad:pe,onLoadError:pe,onValidationError:pe,onCheckoutStarted:pe,onCheckoutSuccess:pe,onSetupPaymentMethodSuccess:pe,onCheckoutError:pe,onPaymentRequestLoad:pe}),ke=class ke{constructor(){this.setCallbacks=e=>{this._callbacks=ke.createEmptyCallbacks(),Object.entries(e).forEach(([t,r])=>{const o=Hs(t,r??ke.NOOP,Su);this._callbacks[t]=o})},this._callbacks=ke.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ke.NOOP=()=>{},ke.createEmptyCallbacks=()=>{const e={};return Object.keys(Do.keyof().enum).forEach(t=>{e[t]=ke.NOOP}),e},ke.fromObject=e=>{const t=new ke;return t.setCallbacks(Do.parse(e)),t};let qn=ke;const Lo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ut=32,Pu=16,Fo=10,jo=0xffffffffffff;var qe;(function(n){n.Base32IncorrectEncoding="B32_ENC_INVALID",n.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",n.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",n.EncodeTimeNegative="ENC_TIME_NEG",n.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",n.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",n.PRNGDetectFailure="PRNG_DETECT",n.ULIDInvalid="ULID_INVALID",n.Unexpected="UNEXPECTED",n.UUIDInvalid="UUID_INVALID"})(qe||(qe={}));class $t extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e}}function Au(n){let e=Math.floor(n()*Ut);return e===Ut&&(e=Ut-1),Lo.charAt(e)}function Tu(n){const e=Iu(),t=e&&(e.crypto||e.msCrypto)||null;if(typeof(t==null?void 0:t.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return()=>t.randomBytes(1).readUInt8()/255;throw new $t(qe.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Iu(){return Nu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function xu(n,e){let t="";for(;n>0;n--)t=Au(e)+t;return t}function Ru(n,e=Fo){if(isNaN(n))throw new $t(qe.EncodeTimeValueMalformed,`Time must be a number: ${n}`);if(n>jo)throw new $t(qe.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${jo}: ${n}`);if(n<0)throw new $t(qe.EncodeTimeNegative,`Time must be positive: ${n}`);if(Number.isInteger(n)===!1)throw new $t(qe.EncodeTimeValueMalformed,`Time must be an integer: ${n}`);let t,r="";for(let o=e;o>0;o--)t=n%Ut,r=Lo.charAt(t)+r,n=(n-t)/Ut;return r}function Nu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ou(n,e){const t=Tu(),r=Date.now();return Ru(r,Fo)+xu(Pu,t)}const Uo="op_analytics_device_token",Mu=()=>{const n=document.cookie.split(";").find(t=>t.includes(Uo));if(n)return n.split("=")[1];const e=Ou();return Du(e),e},Du=n=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Uo}=${n}; path=/; expires=${e.toUTCString()}`};function Lu(){try{const n=U();if(n!=null&&n.next||n!=null&&n.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=U();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(r=>r.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(r=>r._reactRootContainer))return"react";const t=U();return t!=null&&t.Vue||t!=null&&t.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Fu(n){var e,t,r;try{switch(n){case"react":return null;case"nextjs":{const o=U();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((t=o==null?void 0:o.__NEXT_DATA__)==null?void 0:t.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=U())==null?void 0:r.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function ju(){const n=Lu(),e=Fu(n);return{framework:n,version:e}}class Uu{constructor(e,t,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if($o(s.origin)!==$o(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=ja(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=r,this.internalCallbacks=o}}const $o=n=>new URL(n).origin;async function $u(n,e){const r=await vr({iframe:n,debug:!1,childOrigin:e}).promise,o=await ai(r);if(!ii(r,o))throw new Error("Got invalid CDE connection object");return r}class Vu{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Zu=(n,e,t)=>{const{stripePR:r}=n;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Vo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Vo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},Vo=(n,e,t,r,o)=>Z.stripePR.run({context:t,checkoutPaymentMethod:jt(t.checkoutPaymentMethods,n),nonCdeFormInputs:ge(t.formDiv),formCallbacks:r,customParams:{provider:n,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Zo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ee,err__:fe}=F("op-form"),Ce=class Ce{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ot,this.anyCdeConn=new Ot,this.context=new Ot,this.initFlows=Cu(),this.startFormInit=async()=>{try{const s=this.createElement(_e.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),Ee("CDE bridge element mounted"),Ee("Initializing OpenPay form:"),Ee("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Zo});Ee("├ CDE load event received"),Ee("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Zo});Ee("├ CDE connection received"),await el(c,this.deviceToken),Ee("├ Creating OJS context, setting up handlers...");const l=Ce.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Zu(this.initFlows,l,this.formCallbacks),Ee("├ Starting OJS init flows..."),await ku(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),Ee("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);fe("╰ Error initializing OP form:",i),E("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===_e.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),E("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),E("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(!this.isValidFormInstance("createElement"))throw new Error("Form instance is invalid or has been destroyed");if(!this.config)throw new Error("OpenPay form not initialized");const c=Js.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),E("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[_e.CARD]:void 0,[_e.CARD_NUMBER]:void 0,[_e.CARD_EXPIRY]:void 0,[_e.CARD_CVC]:void 0,[_e.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Oa(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{$u(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===_e.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>fe("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=s=>{if(E("submit_card",{...s}),!this.isValidFormInstance("submitCard")){E("outdated_form_instance",{caller:"submitCard"});return}const i=this.context.getValueIfLoadedElse(null);if(!i){fe("Please wait for the form to finish loading before submitting.");return}Z.commonCC.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ge(i.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:s==null?void 0:s.paymentRouteId},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.isValidFormInstance("getAvailablePaymentMethods"))return[];if(!this.context.getValueIfLoadedElse(null)){fe("Please wait for the form to finish loading before getting available payment methods.");return}const i={airwallexGooglePay:ne.airwallexGooglePay,airwallexApplePay:ne.airwallexApplePay,authorizeNetGooglePay:ne.authorizenetGooglePay,authorizeNetApplePay:ne.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return E("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{if(E("general_form_submit",{method:s,settings:i}),!this.isValidFormInstance("generalSubmit")){E("outdated_form_instance",{caller:"generalSubmit"});return}const c=this.context.getValueIfLoadedElse(null);if(!c){fe("Please wait for the form to finish loading before submitting.");return}switch(s){case ne.pockytPaypal:return Z.pockytPaypal.run({context:c,checkoutPaymentMethod:jt(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ge(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case ne.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){fe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){fe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){fe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){fe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.loopCrypto:return Z.loopCrypto.run({context:c,checkoutPaymentMethod:jt(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:ge(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:un(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;if(Ee("Destroying OpenPay form..."),!!this.isValidFormInstance("destroy")){this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=U())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Zc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")}},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Ce.assignAsSingleton(this),this.ojsVersion="0.2.35",this.ojsReleaseVersion="0.2.35",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=qn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Xt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Vu,this.deviceToken=Mu(),Vc();const{framework:t,version:r}=ju();Jr(this.baseUrl).then(s=>{if(!Vn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:t,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Vn.set(i)}}),E("form_init"),this.eventHandler=new Uu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=U())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}isValidFormInstance(e="unknown"){const t=Ce.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(t==null?void 0:t.formId)||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},o=`
25
+ Details: got ${n.required_user_actions.length} required user actions`);return Pa.parse(n.required_user_actions[0])},jt=(n,e,t)=>{const r=n.filter(o=>{const s=t===void 0?!0:o.processor_name===t,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",n),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);return r.length!==1&&(console.warn("CPMs list",n),console.warn(`More than one CPM found with provider '${e}' and processor '${t}'`),E("more_than_one_cpm_found",{provider:e,processor:t,cpms:n})),r[0]},Z={commonCC:{init:async()=>{},run:Yl},stripePR:{init:yu,run:_u},stripeLink:{init:uu,run:du},pockytPaypal:{run:au},airwallexGooglePay:{init:kl,run:Cl},airwallexApplePay:{init:wl,run:bl},loopCrypto:{init:ru,run:ou},authorizeNetApplePay:{init:Al,run:Tl},authorizeNetGooglePay:{init:Il,run:xl}},{log__:bu,err__:Eu}=F("init-flows"),Be=(n,e)=>{const t=new Ot;return{publisher:t,initialize:async r=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);bu(`✔ ${n} flow initialized successfully. Result:`,o),t.set(o)}catch(o){Eu(`𝙭 ${n} flow initialization failed. Error:`,re(o),"Details:",o),t.throw(o,re(o))}}}},ku=async(n,e,t)=>{await Promise.all(Object.values(n).map(r=>r.initialize({context:e,formCallbacks:t})))},Cu=()=>({stripePR:Be("Stripe PR",Z.stripePR.init),stripeLink:Be("Stripe Link",Z.stripeLink.init),airwallexGooglePay:Be("Airwallex GooglePay",Z.airwallexGooglePay.init),airwallexApplePay:Be("Airwallex ApplePay",Z.airwallexApplePay.init),loop:Be("Loop",Z.loopCrypto.init),authorizeNetGooglePay:Be("Authnet GooglePay",Z.authorizeNetGooglePay.init),authorizeNetApplePay:Be("Authnet ApplePay",Z.authorizeNetApplePay.init)}),{err__:Su}=F("form-callbacks"),pe=a.function().optional(),Do=a.object({onFocus:pe,onBlur:pe,onChange:pe,onLoad:pe,onLoadError:pe,onValidationError:pe,onCheckoutStarted:pe,onCheckoutSuccess:pe,onSetupPaymentMethodSuccess:pe,onCheckoutError:pe,onPaymentRequestLoad:pe}),ke=class ke{constructor(){this.setCallbacks=e=>{this._callbacks=ke.createEmptyCallbacks(),Object.entries(e).forEach(([t,r])=>{const o=Hs(t,r??ke.NOOP,Su);this._callbacks[t]=o})},this._callbacks=ke.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ke.NOOP=()=>{},ke.createEmptyCallbacks=()=>{const e={};return Object.keys(Do.keyof().enum).forEach(t=>{e[t]=ke.NOOP}),e},ke.fromObject=e=>{const t=new ke;return t.setCallbacks(Do.parse(e)),t};let qn=ke;const Lo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ut=32,Pu=16,Fo=10,jo=0xffffffffffff;var qe;(function(n){n.Base32IncorrectEncoding="B32_ENC_INVALID",n.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",n.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",n.EncodeTimeNegative="ENC_TIME_NEG",n.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",n.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",n.PRNGDetectFailure="PRNG_DETECT",n.ULIDInvalid="ULID_INVALID",n.Unexpected="UNEXPECTED",n.UUIDInvalid="UUID_INVALID"})(qe||(qe={}));class $t extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e}}function Au(n){let e=Math.floor(n()*Ut);return e===Ut&&(e=Ut-1),Lo.charAt(e)}function Tu(n){const e=Iu(),t=e&&(e.crypto||e.msCrypto)||null;if(typeof(t==null?void 0:t.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return()=>t.randomBytes(1).readUInt8()/255;throw new $t(qe.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Iu(){return Nu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function xu(n,e){let t="";for(;n>0;n--)t=Au(e)+t;return t}function Ru(n,e=Fo){if(isNaN(n))throw new $t(qe.EncodeTimeValueMalformed,`Time must be a number: ${n}`);if(n>jo)throw new $t(qe.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${jo}: ${n}`);if(n<0)throw new $t(qe.EncodeTimeNegative,`Time must be positive: ${n}`);if(Number.isInteger(n)===!1)throw new $t(qe.EncodeTimeValueMalformed,`Time must be an integer: ${n}`);let t,r="";for(let o=e;o>0;o--)t=n%Ut,r=Lo.charAt(t)+r,n=(n-t)/Ut;return r}function Nu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ou(n,e){const t=Tu(),r=Date.now();return Ru(r,Fo)+xu(Pu,t)}const Uo="op_analytics_device_token",Mu=()=>{const n=document.cookie.split(";").find(t=>t.includes(Uo));if(n)return n.split("=")[1];const e=Ou();return Du(e),e},Du=n=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Uo}=${n}; path=/; expires=${e.toUTCString()}`};function Lu(){try{const n=U();if(n!=null&&n.next||n!=null&&n.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=U();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(r=>r.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(r=>r._reactRootContainer))return"react";const t=U();return t!=null&&t.Vue||t!=null&&t.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Fu(n){var e,t,r;try{switch(n){case"react":return null;case"nextjs":{const o=U();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((t=o==null?void 0:o.__NEXT_DATA__)==null?void 0:t.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=U())==null?void 0:r.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function ju(){const n=Lu(),e=Fu(n);return{framework:n,version:e}}class Uu{constructor(e,t,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if($o(s.origin)!==$o(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=ja(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=r,this.internalCallbacks=o}}const $o=n=>new URL(n).origin;async function $u(n,e){const r=await vr({iframe:n,debug:!1,childOrigin:e}).promise,o=await ai(r);if(!ii(r,o))throw new Error("Got invalid CDE connection object");return r}class Vu{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Zu=(n,e,t)=>{const{stripePR:r}=n;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Vo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Vo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},Vo=(n,e,t,r,o)=>Z.stripePR.run({context:t,checkoutPaymentMethod:jt(t.checkoutPaymentMethods,n),nonCdeFormInputs:ge(t.formDiv),formCallbacks:r,customParams:{provider:n,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Zo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ee,err__:fe}=F("op-form"),Ce=class Ce{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ot,this.anyCdeConn=new Ot,this.context=new Ot,this.initFlows=Cu(),this.startFormInit=async()=>{try{const s=this.createElement(_e.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),Ee("CDE bridge element mounted"),Ee("Initializing OpenPay form:"),Ee("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Zo});Ee("├ CDE load event received"),Ee("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Zo});Ee("├ CDE connection received"),await el(c,this.deviceToken),Ee("├ Creating OJS context, setting up handlers...");const l=Ce.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Zu(this.initFlows,l,this.formCallbacks),Ee("├ Starting OJS init flows..."),await ku(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),Ee("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);fe("╰ Error initializing OP form:",i),E("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===_e.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),E("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),E("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(this.checkValidFormInstance("createElement"),!this.config)throw new Error("OpenPay form not initialized");const c=Js.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),E("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[_e.CARD]:void 0,[_e.CARD_NUMBER]:void 0,[_e.CARD_EXPIRY]:void 0,[_e.CARD_CVC]:void 0,[_e.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Oa(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{$u(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===_e.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>fe("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=s=>{E("submit_card",{...s}),this.checkValidFormInstance("submitCard");const i=this.context.getValueIfLoadedElse(null);if(!i){fe("Please wait for the form to finish loading before submitting.");return}Z.commonCC.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ge(i.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:s==null?void 0:s.paymentRouteId},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(this.checkValidFormInstance("getAvailablePaymentMethods"),!this.context.getValueIfLoadedElse(null)){fe("Please wait for the form to finish loading before getting available payment methods.");return}const i={airwallexGooglePay:ne.airwallexGooglePay,airwallexApplePay:ne.airwallexApplePay,authorizeNetGooglePay:ne.authorizenetGooglePay,authorizeNetApplePay:ne.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return E("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{E("general_form_submit",{method:s,settings:i}),this.checkValidFormInstance("generalSubmit");const c=this.context.getValueIfLoadedElse(null);if(!c){fe("Please wait for the form to finish loading before submitting.");return}switch(s){case ne.pockytPaypal:return Z.pockytPaypal.run({context:c,checkoutPaymentMethod:jt(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ge(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case ne.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){fe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){fe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){fe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){fe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case ne.loopCrypto:return Z.loopCrypto.run({context:c,checkoutPaymentMethod:jt(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:ge(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:un(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;Ee("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=U())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Zc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Ce.assignAsSingleton(this),this.ojsVersion="0.2.36",this.ojsReleaseVersion="0.2.36",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=qn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Xt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Vu,this.deviceToken=Mu(),Vc();const{framework:t,version:r}=ju();Jr(this.baseUrl).then(s=>{if(!Vn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:t,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Vn.set(i)}}),E("form_init"),this.eventHandler=new Uu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=U())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(e="unknown"){const t=Ce.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(t==null?void 0:t.formId)||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},o=`
26
26
  [Warning] Invalid form instance detected.
27
27
  It looks like you are still using an old instance that has been destroyed.
28
28
  Please make sure you are using the latest instance of the form and cleanup event listeners.
@@ -33,4 +33,4 @@ Details: got ${n.required_user_actions.length} required user actions`);return Pa
33
33
  - current_active_form_id: ${r.currentFormId}
34
34
  - is_destroyed: ${r.isDestroyed}
35
35
  - checkout_token: ${r.checkoutToken}
36
- `;return this.isDestroyed||!t||t.formId!==this.formId?(fe(o),!1):!0}};Ce.ojsFlows=Z,Ce.assignAsSingleton=e=>{if(Ce.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ce.getInstance=()=>window.ojs??null,Ce.buildOjsFlowContext=(e,t,r,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??He).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:r,customInitParams:e.customInitParams??{}});let Yn=Ce;Pe.FieldName=m,Pe.OpenPayForm=Yn,Pe.SubmitMethod=Ks,Pe.SubmitMethods=ne,Object.defineProperty(Pe,Symbol.toStringTag,{value:"Module"})});
36
+ `;return this.isDestroyed?(fe(o),E("outdated_form_instance",{error:o}),!1):!t||t.formId!==this.formId?(fe(o),E("outdated_form_instance",{error:o}),!1):!0}};Ce.ojsFlows=Z,Ce.assignAsSingleton=e=>{if(Ce.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ce.getInstance=()=>window.ojs??null,Ce.buildOjsFlowContext=(e,t,r,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??He).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:r,customInitParams:e.customInitParams??{}});let Yn=Ce;Pe.FieldName=m,Pe.OpenPayForm=Yn,Pe.SubmitMethod=Ks,Pe.SubmitMethods=ne,Object.defineProperty(Pe,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getopenpay/openpay-js",
3
- "version": "0.2.35",
3
+ "version": "0.2.36",
4
4
  "description": "Accept payments through OpenPay, right on your site",
5
5
  "author": "OpenPay <info@getopenpay.com> (https://getopenpay.com)",
6
6
  "license": "ISC",