@getopenpay/openpay-js 0.3.3 → 0.3.4
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.es.js +671 -671
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -22,7 +22,7 @@ ${t.message}`),t.message)}else return An(t.message);if(typeof t=="object")try{re
|
|
|
22
22
|
`;const n=document.createElement("div"),r=n.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(n),{host:n,iframe:o,cancelButton:s}};function ul(t,e,n){const r=async()=>{try{const s=await sl(t,n);s&&(clearInterval(o),e(s))}catch{}};r();const o=setInterval(r,io);return o}function dl({elements:t,pollingInterval:e,resolve:n}){const r=()=>{clearInterval(e),t.host.remove(),n({status:Z.CANCELLED})};return t.cancelButton.addEventListener("click",r),()=>{t.cancelButton.removeEventListener("click",r)}}async function hn(t){const{url:e,baseUrl:n}=t,r=yo(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{r.host.remove()},1e3),o(l),c==null||c()},i=ul(r.iframe,s,new URL(n).origin),c=dl({elements:r,pollingInterval:i,resolve:o})})}const _o=async t=>{const e=await hn(t);if(e.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===Z.FAILURE)throw new Error("3DS verification failed");return e.status!==Z.SUCCESS&&fn(e.status),{href:e.href}},pl=(t,e)=>{const n=window.open(e,"_blank");if(!n)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return n},go=async(t,e,n,r)=>{const{err__:o}=D("popup-verify");return new Promise((s,i)=>{const c=pl(t,r),l=setInterval(async()=>{try{const u=await tl(e,n);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(re(u)),clearInterval(l),i(re(u))}},1e3)})},{log__:fl,err__:Bn}=D("airwallex-cc"),ml=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),hl=t=>{const e=ml.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Bn(r),new Error(n)}return e.data},yl=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,_l=t=>{try{const e=new URL(t??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return fl(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const n="Error verifying Airwallex 3DS verification result.";throw Bn(n,`Resulting URL: ${t}.
|
|
23
23
|
Error: ${re(e)}`),new Error(n)}},gl=async(t,e)=>{const n=hl(e),r=await _o({url:n["op-airwallex-3ds-url"],baseUrl:t}),o=_l(r.href??""),s=n["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 Bn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:n["op-airwallex-consent-id"]}}},vo=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()})}),wo=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__:bo,err__:Eo}=D("common-cc"),Re=(t,e,n)=>{if(n){bo(`Received default field values: ${JSON.stringify(n)}`);for(const[o,s]of Object.entries(n))t[o]||(t[o]=s)}const r=Rt.safeParse(t);if(!r.success){const o=r.error.format(),s=mr(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Eo("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},vl=(t,e)=>{for(const n of t)if(n.success===!1)throw n.errors.forEach(r=>{const o=pr.safeParse(r.elementType);if(!o.success)Eo(`Unknown field name in onValidationError: ${r.elementType}. Error object:`,r);else{const s=o.data;e(s,r.errors)}}),bo(`Error tokenizing card: got validation errors: ${JSON.stringify(n.errors)}`),new Error("Got validation errors while tokenizing card")},{log__:yn}=D("awx-apple-pay");async function wl(t,e){try{const r=(await Gn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.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(n){throw e.session.abort(),n}}async function bl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");yn("3DS Required, starting verification...",t);const{status:n}=await hn({url:t.redirect_url,baseUrl:e.baseUrl});if(yn(`╰ 3DS verification completed [Status: ${n}]`),n===Z.CANCELLED)throw new Error("3DS verification cancelled");if(n===Z.FAILURE)throw new Error("3DS verification failed");const r=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return yn("[2nd] Confirm payment flow response",r),r}async function El(t,e){var n,r,o,s,i;try{const c=t.payment,l=po(e.nonCdeFormInputs,c),u=Re(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);E("billing_details_received",{...u});const m=(await lt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[h.EMAIL],new_customer_first_name:u[h.FIRST_NAME],new_customer_last_name:u[h.LAST_NAME],new_customer_address:{zip_code:u[h.ZIP_CODE],country:u[h.COUNTRY]}})).required_user_actions[0].consent_id;if(!m)throw new Error("No consent ID received from payment flow");let p=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:m,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});yn("[1st] Confirm payment flow response",p);let _=(r=(n=p.payment_methods)==null?void 0:n[0])==null?void 0:r.id;const w=(o=p.required_user_actions)==null?void 0:o.find(k=>k.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(p=await bl(w,e),_=(i=(s=p.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!_)throw new Error("No PM ID found");const A={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(A),jt({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:p,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Ut,err__:ko}=D("awx-apple-pay"),kl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:de.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,vo);if(!r)return n;if(Ut("Loading Apple Pay script"),await uo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Ut("Apple Pay is not available on this device/browser"),n;if(Ut("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Ut("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await ut(i,c.token,l,void 0),d=async f=>{try{await U.airwallexApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(m){ko("Apple Pay payment error",m),e.get.onCheckoutError((m==null?void 0:m.message)??"Unknown error")}};return{processor:de.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Cl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var _;const s=ae(t.checkoutPaymentMethods,vo),{overridePaymentRequest:i,initialPreview:c}=r,l=t.anyCdeConnection,u=await G(l),d=u.mode==="setup",f=fo({overridePaymentRequest:i,initialPreview:c,prefill:{...u},defaultLabel:(_=s==null?void 0:s.metadata)==null?void 0:_.processor_account_name}),m=new ApplePaySession(3,f),p={session:m,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:eo(u,["brand"]),overridePaymentRequest:i}),new Promise((w,A)=>{const k=()=>{Ut("Payment cancelled by user"),A(new Error("Payment cancelled by user"))};m.oncancel=k,m.onvalidatemerchant=async x=>{try{await wl(x,p)}catch(I){A(I)}},m.onpaymentmethodselected=()=>{const x={newTotal:{...f.total}};m.completePaymentMethodSelection(x)},m.onpaymentauthorized=async x=>{E("apple_pay_payment_authorized");try{const I=await El(x,p);w(I)}catch(I){A(I)}},m.begin()}).catch(w=>{throw ko("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),_n=({gateway:t,gatewayMerchantId:e,merchantName:n,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var f,m;const c=((f=s==null?void 0:s.amount)==null?void 0:f.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((m=s==null?void 0:s.amount)==null?void 0:m.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:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:n},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},Co=()=>lo({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let qn=null;const So=async t=>await Xr(t)==="prod"?"PRODUCTION":"TEST",gn=async(t,e)=>{const n=await So(t);return qn===null&&(qn=new window.google.payments.api.PaymentsClient({environment:n,merchantInfo:e.merchantInfo})),qn},Sl=t=>{const e=t.required_user_actions.find(n=>n.type==="airwallex_payment_consent");return e?fr.parse(e):null},Po=(t,e)=>{var o,s,i,c;const n={...t},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;n[h.EMAIL]=n[h.EMAIL]||e.email||"op_unfilled@getopenpay.com",n[h.COUNTRY]=n[h.COUNTRY]||r.countryCode||"US",n[h.ADDRESS]=n[h.ADDRESS]||r.address1||"",n[h.CITY]=n[h.CITY]||r.locality||"",n[h.ZIP_CODE]=n[h.ZIP_CODE]||r.postalCode||"00000",n[h.STATE]=n[h.STATE]||r.administrativeArea||"";const f=n[h.FIRST_NAME]||l||"",m=n[h.LAST_NAME]||d||"";f||m?(n[h.FIRST_NAME]=f,n[h.LAST_NAME]=m):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]="")}return n},{log__:pe,err__:dt}=D("awx-google-pay"),Pl=Ge(async({context:t,formCallbacks:e})=>{var f,m;const n={processor:de.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,wo);if(!r)return n;pe("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return dt("No gateway merchant ID found in processor account"),n;if(pe("Loading Google Pay script"),await Co(),!((m=(f=window.google)==null?void 0:f.payments)!=null&&m.api))return dt("Google Pay SDK not loaded properly"),n;if(await So(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return dt("Google Pay merchant ID is required for production environment"),n;pe("Google Pay SDK loaded",window.google.payments);try{const p=_n({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),_=await gn(t.baseUrl,p),{result:w}=await _.isReadyToPay(p);if(!w)return pe("Google Pay is not available for this user"),n}catch(p){return dt("Error checking Google Pay availability",p),n}const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await ut(i,c.token,l,void 0),d=async p=>{try{U.airwallexGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...p,initialPreview:u}})}catch(_){dt("Google Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:de.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Al=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var p,_,w,A,k,x,I;pe("Starting Google Pay flow...");const s=ae(t.checkoutPaymentMethods,wo),{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=_n({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,f=await G(d);E("google_pay_flow_started",{processor_name:s.processor_name,prefill:eo(f,["brand"]),overridePaymentRequest:c});const m=await gn(t.baseUrl,u);try{const L=await m.loadPaymentData(u);pe("Google Pay Payment data",L);const B=Po(n,L),$=Re(B,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);E("billing_details_received",{...$});const Pe=(_=(p=L.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!Pe)throw new Error("No payment token received from Google Pay");const Hu=await lt(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:$[h.EMAIL],new_customer_first_name:$[h.FIRST_NAME],new_customer_last_name:$[h.LAST_NAME],new_customer_address:{zip_code:$[h.ZIP_CODE],country:$[h.COUNTRY]}}),wn=Sl(Hu);pe("Start flow next actions",wn);let We=await se(d,{secure_token:f.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:wn==null?void 0:wn.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Pe}}}});pe("[1st] Confirm payment flow response",We);let Kn=(A=(w=We.payment_methods)==null?void 0:w[0])==null?void 0:A.id;const He=(k=We.required_user_actions)==null?void 0:k.find(Gt=>Gt.type==="airwallex_payment_consent");if(He&&He.redirect_url){pe("3DS Required, starting verification...",He);const{status:Gt}=await hn({url:He.redirect_url,baseUrl:t.baseUrl});if(pe(`╰ 3DS verification completed [Status: ${Gt}]`),Gt===Z.CANCELLED)throw new Error("3DS verification cancelled");if(Gt===Z.FAILURE)throw new Error("3DS verification failed")}if(He&&!Kn&&(We=await se(d,{secure_token:f.token,their_pm_id:He.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:He.consent_id}}),pe("[2nd] Confirm payment flow response",We),Kn=(I=(x=We.payment_methods)==null?void 0:x[0])==null?void 0:I.id),!Kn)throw new Error("No PM ID found");return jt({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:$,confirmResult:We,usePayFirstFlow:!1})}catch(L){throw dt("Google Pay payment error",L),E("google_pay_payment_error",{error:L}),new Error((L==null?void 0:L.message)??"Unknown error")}}),Ao=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()})}),To=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 Tl(t,e){try{const r=(await Gn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.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(n){throw e.session.abort(),n}}async function Il(t,e){var n,r;try{const o=t.payment,s=po(e.nonCdeFormInputs,o),i=Re(s,e.formCallbacks.get.onValidationError);E("billing_details_received",{...i}),await lt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[h.EMAIL],new_customer_first_name:i[h.FIRST_NAME],new_customer_last_name:i[h.LAST_NAME],new_customer_address:{zip_code:i[h.ZIP_CODE],country:i[h.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((r=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),jt({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__:vn,err__:Io}=D("authnet-applepay"),xl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:de.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,Ao);if(!r)return n;if(vn("Loading Apple Pay script"),await uo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return vn("Apple Pay is not available on this device/browser"),n;if(!await ApplePaySession.canMakePayments())return vn("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await ut(i,c.token,l,void 0),d=async f=>{try{await U.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(m){Io("Apple Pay payment error",m),E("apple_pay_payment_error",{error:m}),e.get.onCheckoutError((m==null?void 0:m.message)??"Unknown error")}};return{processor:de.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Rl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var _;const{initialPreview:s,overridePaymentRequest:i}=r,c=ae(t.checkoutPaymentMethods,Ao),l=t.anyCdeConnection,u=await G(l),d=u.mode==="setup",f=fo({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 m=new ApplePaySession(3,f),p={session:m,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:e.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((w,A)=>{m.oncancel=()=>{vn("Payment cancelled by user"),A(new Error("Payment cancelled by user"))},m.onvalidatemerchant=async k=>{try{await Tl(k,p)}catch(x){A(x)}},m.onpaymentmethodselected=()=>{const k={newTotal:f.total};m.completePaymentMethodSelection(k)},m.onpaymentauthorized=async k=>{E("apple_pay_payment_authorized");try{const x=await Il(k,p);w(x)}catch(x){A(x)}},m.begin()}).catch(w=>{throw Io("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),{log__:Be,err__:$t}=D("authnet-googlepay"),Nl=Ge(async({context:t,formCallbacks:e})=>{var d,f;Be("Initializing Authnet GooglePay flow");const n={processor:de.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,To);if(!r)return n;Be("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return $t("No gateway merchant ID found in processor account"),n;if(Be("Loading Google Pay script"),await Co(),!((f=(d=window.google)==null?void 0:d.payments)!=null&&f.api))return $t("Google Pay SDK not loaded properly"),n;Be("Google Pay SDK loaded",window.google.payments);try{const m=_n({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),p=await gn(t.baseUrl,m),{result:_}=await p.isReadyToPay(m);if(!_)return Be("Google Pay is not available for this user"),n}catch(m){return $t("Error checking Google Pay availability",m),n}const s=t.anyCdeConnection,i=await G(s),c=i.mode==="setup",l=await ut(s,i.token,c,void 0),u=async m=>{try{U.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...m,initialPreview:l}})}catch(p){$t("Google Pay payment error",p),E("google_pay_payment_error",{error:p}),e.get.onCheckoutError((p==null?void 0:p.message)??"Unknown error")}};return{processor:de.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Ol=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var p,_,w,A;const{initialPreview:s,overridePaymentRequest:i}=o,l=ae(t.checkoutPaymentMethods,To).metadata,u=_n({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,f=await G(d);E("google_pay_flow_started",{processor_name:n.processor_name,prefill:f,overridePaymentRequest:i});const m=await gn(t.baseUrl,u);try{const k=await m.loadPaymentData(u);Be("Google Pay Payment data",k);const x=Po(e,k),I=Re(x,r.get.onValidationError);E("billing_details_received",{...I});const L=(_=(p=k.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!L)throw new Error("No payment token received from Google Pay");const B=await lt(d,{payment_provider:n.provider,checkout_payment_method:n,new_customer_email:I[h.EMAIL],new_customer_first_name:I[h.FIRST_NAME],new_customer_last_name:I[h.LAST_NAME],new_customer_address:{zip_code:I[h.ZIP_CODE],country:I[h.COUNTRY]}});Be("Start payment flow response",B);const $=await se(d,{secure_token:f.token,processor_specific_metadata:{payment_provider:n.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(L)}}});if(!((A=(w=$.payment_methods)==null?void 0:w[0])==null?void 0:A.id))throw new Error("No PM ID found");return jt({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:n,requiredFormFields:I,confirmResult:$,usePayFirstFlow:!1})}catch(k){throw $t("Google Pay payment error",k),E("google_pay_payment_error",{error:k}),new Error((k==null?void 0:k.message)??"Unknown error")}}),{log__:Ml,err__:xo}=D("pockyt-cc"),Dl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Fl=t=>{const e=Dl.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw xo(r),new Error(n)}return e.data},Ro=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Ml(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const n="Error verifying 3DS verification result.";throw xo(n,`Resulting URL: ${t}.
|
|
24
24
|
Error: ${re(e)}`),new Error(n)}},Yn=(t,e)=>new URL(t).searchParams.get(e),Ll=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,jl=async(t,e)=>{const n=Fl(e),r=await _o({url:n["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:Ro(r.href??""),transaction_no:n["op-pockyt-txn-no"],reference_no:n["op-pockyt-ref-no"]}}},Ul=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),$l=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__:pt,err__:Vt}=D("adyen-cc"),Vl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":Ul,"op-adyen-action":a.string()}),No="Unable to process your credit card. Please contact support for assistance.",Zl=t=>{const e=Vl.safeParse(t);if(!e.success)throw Vt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(No);return e.data},zl=t=>JSON.parse(t),Oo=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Gl=async()=>{pt("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)Oo()||await tn(500);if(!Oo())throw Vt("Adyen SDK not loaded properly"),new Error(No);return pt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},Bl=t=>{const{headers:e,locale:n,countryCode:r,component:o,host:s,cancelButton:i}=t,c=zl(e["op-adyen-action"]);return pt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{pt("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",m),s.remove()},d=_=>{Vt("Authentication failed. Result:",_),l({status:Z.FAILURE,cleanup:u})},f=_=>{Vt("Adyen error:",_),l({status:Z.FAILURE,cleanup:u})},m=()=>{l({status:Z.CANCELLED,cleanup:u})};i.addEventListener("click",m);const p=(_,w,A)=>{s.remove(),l({status:Z.SUCCESS,additionalDetails:_,cleanup:u})};Gl().then(_=>_({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:n,countryCode:r,onAdditionalDetails:p,onPaymentFailed:d,onError:f})).then(_=>{_.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},ql=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,n=t??e,r=$l.safeParse(n);return r.success?(pt(`Resolved locale: ${r.data}`),r.data):(Vt(`Resolved invalid locale: ${n}. Defaulting to en-US.`),"en-US")},Yl=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Wl=async(t,e,n)=>{const r=Zl(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=yo("http://example.com");i.replaceWith(o);const l=await Bl({headers:r,locale:ql(n),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===Z.FAILURE)throw new Error("3DS verification failed");if(l.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===Z.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return pt("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else fn(l.status)},{log__:F,err__:Mo}=D("common-cc"),{log__:Do}=D("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Hl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var u;F("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await G(s);E("common_cc_flow_started",{...e,prefill:i}),F(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Re(n,r.get.onValidationError);E("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin},payment_route_id:o.paymentRouteId};try{F(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await rl(o.currentCdeConnections,{session_id:t.elementsSessionId});if(vl(d,r.get.onValidationError),i.mode==="setup"){F(`├ Setting up payment method in CDE [Token: ${i.token}]`);const f=await ol(s,l);return F(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{F(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const f=await ao(s,l);return F("╰ Checkout completed successfully."),{mode:"checkout",result:f}}}catch(d){if(d instanceof so&&d.originalErrorMessage.includes("3DS_REQUIRED")){F("├ Card requires 3DS, starting non-legacy payment flow"),F("Received 3DS error response headers:",d.response.headers),E("3ds_required",{...e,...d.response.headers});const f=Ll(d.response.headers);if(f){F("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const k=await jl(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=k}if(yl(d.response.headers)){F("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const k=await gl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=k}if(Yl(d.response.headers)){F("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const k=await Wl(n[h.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=k}const _=await Qc(s,l);F("├ Payment flow result:",_);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";f?F("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(F("├ Using stripe 3DS flow"),await eu(_)):(F("├ Using common 3DS flow"),await Xl(_,t.baseUrl));const A=_.cc_pm_id;if(i.mode==="setup"){F(`├ Confirming payment flow [cc_pm_id: ${A}]`);const k=await se(s,{secure_token:i.token,existing_cc_pm_id:A});F("├ Confirm payment flow result received Result:",k);const x=Lt(k);return F(`╰ Setup completed successfully [PM ID: ${x.payment_method_id}]`),{mode:"setup",result:x}}else{F(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const k=await ao(s,{...l,existing_cc_pm_id:A,do_not_use_legacy_cc_flow:w});return F("╰ Checkout completed successfully."),{mode:"checkout",result:k}}}throw Mo("╰ Error checking out card info in CDE"),Mo(d),d}}),Kl=t=>{const e=t.required_user_actions.find(n=>n.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Ra.parse(e)},Jl=["airwallex_payment_consent","adyen"],Ql=t=>{const e=t.required_user_actions.find(n=>Jl.includes(n.type));if(!e)throw new Error("No common 3DS action found");return Ta.parse(e)},Xl=async(t,e)=>{const n=Ql(t);if(n.redirect_url==="3DS_COMPLETE"){F("├ 3DS flow completed successfully"),E("3ds_complete");return}F(`├ Using common 3DS flow [URL: ${n.redirect_url}]`),E("3ds_redirect",{...n});const{status:r}=await hn({url:n.redirect_url,baseUrl:e});if(F(`╰ 3DS verification completed [Status: ${r}]`),r===Z.CANCELLED)throw E("3ds_cancelled"),new Error("3DS verification cancelled");if(r===Z.FAILURE)throw E("3ds_failure"),new Error("3DS verification failed")},eu=async t=>{const e=Kl(t);E("3ds_stripe_redirect",{...e}),Do(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await ja(e),E("3ds_stripe_complete"),Do("╰ Stripe 3DS flow completed successfully")},tu=1,nu=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__:te,err__:Fo}=D("loop-crypto"),ru=a.object({loopFirstName:V,loopLastName:V,loopEmail:V,[h.PROMOTION_CODE]:O}),ou=a.object({loopFirstName:O,loopLastName:O,loopEmail:O,[h.PROMOTION_CODE]:O}),Lo=(t,e,n,r)=>{const o=n.safeParse(t);if(!o.success){const s=o.error.format(),i=mr(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Fo("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},su=Ge(async({context:t})=>{te("Checking if there are any CPMs for Loop Crypto...");const e=ae(t.checkoutPaymentMethods,nu);te(`checkoutPaymentMethod: ${JSON.stringify(e)}`),te("Starting Loop Crypto flow...");const n=await G(t.anyCdeConnection),r=await Gn(t.anyCdeConnection,{checkout_payment_method:e});if(n.mode!=="setup"&&!e.metadata.supported_currencies.includes(n.currency))throw Error(`Currency ${n.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;n.mode==="setup"?s=tu:s=n.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=rt(),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}}),au=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{te("Running Loop flow..."),te("context",t),te("checkoutPaymentMethod",e),te("nonCdeFormInputs",n),te("flowCallbacks",r),te("customParams",o);let s;o!=null&&o.success?s=Lo(n,r.get.onValidationError,ru):s=Lo(n,r.get.onValidationError,ou);const i=t.anyCdeConnection,c=await G(t.anyCdeConnection),l=c.mode!=="setup",u=await lt(t.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 se(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(te(`Confirm result: ${d}`),c.mode==="setup"){te("Doing payment setup..."),te("├ Confirm payment flow result received Result:",d);const f=Lt(d);return te(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{if(te("Doing checkout..."),!d.pay_first_success_response)throw Fo("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__:Ee,err__:jo}=D("pockyt-paypal"),iu=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 cu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var $,Pe;Ee("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await G(s);Ee("Verifying CPM...");const c=iu.parse(e);Ee("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Re(n,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=ho(u);Ee(`Starting payment flow... Mode: ${i.mode}`);const f=rt(),m=i.mode!=="setup",p={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:m,pay_first_flow_cart_info:m?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!(($=o==null?void 0:o.settings)!=null&&$.useRedirectFlow),frontend_token_for_redirect_flow:f},...d},_=new URL("/app/pre-action/start/",t.baseUrl).toString(),w=btoa(JSON.stringify(p)),A=new URLSearchParams({st:i.token,r:w}),k=`${_}?${A.toString()}`;if((Pe=o==null?void 0:o.settings)!=null&&Pe.useRedirectFlow)throw Ee("Starting redirect mode for PayPal..."),window.location.href=k,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");Ee("Starting popup mode for PayPal..."),Ee("Opening paypal iframe...");const x=await go("PayPal",s,f,k);Ee("Paypal flow result",x);const I=Ro(x.href),L=Yn(x.href,"catt");if(!L)throw jo("Checkout attempt ID not found in redirect URL:",x.href),new Error("Checkout attempt ID not found in redirect URL");Ee(`Confirming payment flow using vault ID ${I}`);const B=await se(s,{secure_token:i.token,their_pm_id:I,checkout_attempt_id:m?L:void 0});if(Ee("Confirm payment flow result",B),i.mode==="setup")return{mode:"setup",result:{payment_method_id:B.payment_methods[0].id}};if(!B.pay_first_success_response)throw jo("Checkout failed, no pay-first success response:",B),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:B.pay_first_success_response}}),Uo="ojs-stripe-link-btn",{log__:H,err__:lu}=D("stripe-link"),uu=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),du=a.array(a.object({our_existing_pm_id:a.string()})).length(1),pu=Ge(async({context:t,formCallbacks:e})=>{const n=t.customInitParams.stripeLink;H("Checking if there are any CPMs for Stripe Link...");const r=ae(t.checkoutPaymentMethods,uu);H("Starting stripe link flow...");const o=t.anyCdeConnection,s=await G(o),i=s.mode==="setup";H("Creating stripe elements...");const c=await ut(o,s.token,i,void 0),{elements:l,stripe:u}=await Ma(r.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});H("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:n==null?void 0:n.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),f=()=>{d.mount(`#${Uo}`)},m=()=>{d.unmount()};return n!=null&&n.doNotMountOnInit?H("NOT mounting stripe link button (doNotMountOnInit is true)"):(H("Mounting stripe link button..."),f()),d.on("click",async p=>{if(H("Stripe Link button clicked"),n!=null&&n.overrideLinkSubmit&&!await n.overrideLinkSubmit()){H("Stripe Link submit aborted by overrideLinkSubmit");return}p.resolve()}),d.on("confirm",async p=>{H("Stripe Link window confirmed",p);const _=await u.createPaymentMethod({elements:l,params:{billing_details:p.billingDetails}});_.error?(lu("error",_.error),e.get.onCheckoutError(_.error.message??"Stripe Link unknown error")):(H("paymentMethod",_.paymentMethod),U.stripeLink.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{stripePM:_.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:f,dismountButton:m,waitForButtonToMount:async()=>await hu(Uo)}}}),fu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{H("Running Stripe Link flow...");const s=t.anyCdeConnection;H("Merging PM fields with form fields...");const i=mu(n,o.stripePM),c=Re(i,r.get.onValidationError);E("billing_details_received",{...c}),H("Starting payment flow...");const l=await lt(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[h.EMAIL],new_customer_first_name:c[h.FIRST_NAME],new_customer_last_name:c[h.LAST_NAME],new_customer_address:{zip_code:c[h.ZIP_CODE],country:c[h.COUNTRY]}});H("Start payment flow response",l);const d=du.parse(l.required_user_actions)[0].our_existing_pm_id,f=await G(s);if(f.mode==="setup"){H("Doing payment setup...");const m=await se(s,{secure_token:f.token,existing_cc_pm_id:d});return{mode:"setup",result:Lt(m)}}else{H("Doing checkout...");const m={secure_token:f.token,payment_input:{provider_type:e.provider},customer_email:c[h.EMAIL],customer_zip_code:c[h.ZIP_CODE],customer_country:c[h.COUNTRY],promotion_code:c[h.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(s,m)}}}),mu=(t,e)=>{var l,u,d,f,m;const n={...t},[r,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;n[h.EMAIL]=n[h.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",n[h.ZIP_CODE]=n[h.ZIP_CODE]||((f=e.billing_details.address)==null?void 0:f.postal_code)||"00000",n[h.COUNTRY]=n[h.COUNTRY]||((m=e.billing_details.address)==null?void 0:m.country)||"US";const i=n[h.FIRST_NAME]||r||"",c=n[h.LAST_NAME]||s||"";return i||c?(n[h.FIRST_NAME]=i,n[h.LAST_NAME]=c):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]=""),H("Final form inputs:",n),n},hu=t=>new Promise(e=>{const n=()=>{const r=document.getElementById(t);r?e(r):requestAnimationFrame(n)};n()}),{log__:ee,err__:yu}=D("stripe-pr"),_u=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()})}),gu=Ge(async({context:t,formCallbacks:e})=>{ee("Checking if there are any CPMs for Stripe PR...");const n=ae(t.checkoutPaymentMethods,_u);ee("Initializing Stripe PR flow...");const r=t.anyCdeConnection,o=await G(r),s=o.mode==="setup";ee("Getting initial preview amount");const i=await ut(r,o.token,s,void 0),c=await Da(n.metadata.stripe_pk,i.amountAtom,i.currency,s);ee("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return yu("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};ee("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,f)=>U.stripePR.run({context:t,checkoutPaymentMethod:ft(t.checkoutPaymentMethods,d),nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:f==null?void 0:f.overridePaymentRequest},initResult:{processor:de.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:de.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),vu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o,initResult:s})=>{if(ee("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const _=o.overridePaymentRequest;ee("Overriding PR amount with",_);const w=typeof _.applePayPaymentRequest=="function"?_.applePayPaymentRequest({}):_.applePayPaymentRequest;bu(c,_.amount,_.pending,w,_.label)}ee("Showing PR dialog..."),c.show();const l=await Fa(c);ee("Stripe PM added event:",l),ee("Merging PM fields with form fields...");const u=wu(n,l),d=Re(u,r.get.onValidationError);E("billing_details_received",{...d}),ee("PR dialog finished. Starting payment flow...",d);const f=await Xc(i,{fields:d,checkoutPaymentMethod:e}),m=Eu(f);ee("Confirming PR with Stripe..."),await La(m,l);const p=await G(i);if(p.mode==="setup"){ee("Confirming payment flow for setup...");const _=await se(i,{secure_token:p.token});return{mode:"setup",result:Lt(_)}}else{ee("Performing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_first_name:d[h.FIRST_NAME],customer_last_name:d[h.LAST_NAME],customer_email:d[h.EMAIL],customer_zip_code:d[h.ZIP_CODE],customer_country:d[h.COUNTRY],promotion_code:d[h.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(i,_)}}}),wu=(t,e)=>{var d,f,m,p;const n={...t},[r,...o]=((f=(d=e.payerName)==null?void 0:d.trim())==null?void 0:f.split(/\s+/))??[],s=o.join(" ")||void 0,i=(p=(m=e.paymentMethod)==null?void 0:m.billing_details)==null?void 0:p.address,c=e.shippingAddress;n[h.EMAIL]=n[h.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",n[h.ZIP_CODE]=n[h.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",n[h.COUNTRY]=n[h.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=n[h.FIRST_NAME]||r||"",u=n[h.LAST_NAME]||s||"";return l||u?(n[h.FIRST_NAME]=l,n[h.LAST_NAME]=u):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]=""),ee("Final form inputs:",n),n},bu=(t,e,n,r,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:n},currency:e.currency,applePay:r})},Eu=t=>{if(t.required_user_actions.length!==1)throw new Error(`Error occurred.
|
|
25
|
-
Details: got ${t.required_user_actions.length} required user actions`);return Na.parse(t.required_user_actions[0])},ku=()=>{const t=rt().split("-")[0];return{firstName:`xx_${t}`,lastName:`xx_${t}`,email:`xx_${t}@email.com`,zipCode:`xx_${t}`,country:"US"}},{log__:qe,err__:Cu}=D("paypal"),$o=a.object({provider:a.literal("paypal"),metadata:a.object({client_id:a.string()}),processor_name:a.literal("paypal")}),Su=async({context:t,formCallbacks:e})=>{const n=ae(t.checkoutPaymentMethods,$o);if(!n)throw new Error("PayPal CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:()=>U.paypal.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{settings:{}}})}},Pu=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{try{qe("Running PayPal flow...");const s=t.anyCdeConnection,i=await G(s),{isAnonymous:c,useRedirectFlow:l}=o.settings??{};qe("Verifying CPM...");const u=$o.parse(n);qe("├ Validating non-CDE form fields");const d=Re(e,r.get.onValidationError,c?ku():void 0),f=ho(d);qe(`Starting payment flow... Mode: ${i.mode}`);const m=rt(),p=i.mode!=="setup",_={payment_provider:u.provider,checkout_payment_method:u,use_pay_first_flow:p,pay_first_flow_cart_info:p?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:l,frontend_token_for_redirect_flow:m},...f},w=new URL("/app/pre-action/start/",t.baseUrl).toString(),A=btoa(JSON.stringify(_)),k=new URLSearchParams({st:i.token,r:A}),x=`${w}?${k.toString()}`;if(l)throw qe("Starting redirect mode for PayPal..."),window.location.href=x,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");const I=await go("PayPal",s,m,x);qe("Paypal flow result",I);const L=Yn(I.href,"catt"),B=Yn(I.href,"approval_session_id"),$=await se(s,{secure_token:i.token,checkout_attempt_id:p?L:void 0,their_pm_id:p?B:void 0});return qe("Confirm payment flow result",$),jt({logPrefix:"paypal",anyCdeConnection:s,checkoutPaymentMethod:u,requiredFormFields:d,confirmResult:$,usePayFirstFlow:p})}catch(s){throw Cu("PayPal payment error",s),E("checkout_error",{payment_method:"paypal",error:s}),new Error((s==null?void 0:s.message)??"Unknown error")}}),ft=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);return r.length!==1&&(console.warn("CPMs list",t),console.warn(`More than one CPM found with provider '${e}' and processor '${n}'`),E("more_than_one_cpm_found",{provider:e,processor:n,cpms:t})),r[0]},U={commonCC:{init:async()=>{},run:Hl},stripePR:{init:gu,run:vu},stripeLink:{init:pu,run:fu},pockytPaypal:{run:cu},paypal:{init:Su,run:Pu},airwallexGooglePay:{init:Pl,run:Al},airwallexApplePay:{init:kl,run:Cl},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:xl,run:Rl},authorizeNetGooglePay:{init:Nl,run:Ol}},{log__:Au,err__:Tu}=D("init-flows"),Ue=(t,e)=>{const n=new Ft;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);Au(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){Tu(`𝙭 ${t} flow initialization failed. Error:`,re(o),"Details:",o),n.throw(o,re(o))}}}},Iu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},xu=()=>({stripePR:Ue("Stripe PR",U.stripePR.init),stripeLink:Ue("Stripe Link",U.stripeLink.init),airwallexGooglePay:Ue("Airwallex GooglePay",U.airwallexGooglePay.init),airwallexApplePay:Ue("Airwallex ApplePay",U.airwallexApplePay.init),loop:Ue("Loop",U.loopCrypto.init),paypal:Ue("PayPal",U.paypal.init),authorizeNetGooglePay:Ue("Authnet GooglePay",U.authorizeNetGooglePay.init),authorizeNetApplePay:Ue("Authnet ApplePay",U.authorizeNetApplePay.init)}),{err__:Ru}=D("form-callbacks"),fe=a.function().optional(),Vo=a.object({onFocus:fe,onBlur:fe,onChange:fe,onLoad:fe,onLoadError:fe,onValidationError:fe,onCheckoutStarted:fe,onCheckoutSuccess:fe,onSetupPaymentMethodSuccess:fe,onCheckoutError:fe,onPaymentRequestLoad:fe}),Ce=class Ce{constructor(){this.setCallbacks=e=>{this._callbacks=Ce.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=ta(n,r??Ce.NOOP,Ru);this._callbacks[n]=o})},this._callbacks=Ce.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ce.NOOP=()=>{},Ce.createEmptyCallbacks=()=>{const e={};return Object.keys(Vo.keyof().enum).forEach(n=>{e[n]=Ce.NOOP}),e},Ce.fromObject=e=>{const n=new Ce;return n.setCallbacks(Vo.parse(e)),n};let Wn=Ce;const Zo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Zt=32,Nu=16,zo=10,Go=0xffffffffffff;var Ye;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(Ye||(Ye={}));class zt extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function Ou(t){let e=Math.floor(t()*Zt);return e===Zt&&(e=Zt-1),Zo.charAt(e)}function Mu(t){const e=Du(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new zt(Ye.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Du(){return ju()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Fu(t,e){let n="";for(;t>0;t--)n=Ou(e)+n;return n}function Lu(t,e=zo){if(isNaN(t))throw new zt(Ye.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Go)throw new zt(Ye.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Go}: ${t}`);if(t<0)throw new zt(Ye.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new zt(Ye.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Zt,r=Zo.charAt(n)+r,t=(t-n)/Zt;return r}function ju(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Uu(t,e){const n=Mu(),r=Date.now();return Lu(r,zo)+Fu(Nu,n)}const Bo="op_analytics_device_token",$u=()=>{const t=document.cookie.split(";").find(n=>n.includes(Bo));if(t)return t.split("=")[1];const e=Uu();return Vu(e),e},Vu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Bo}=${t}; path=/; expires=${e.toUTCString()}`};function Zu(){try{const t=z(),e=t;if(e!=null&&e.next||e!=null&&e.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const n=t;if(n!=null&&n.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(o=>o.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(o=>o._reactRootContainer))return"react";const r=t;return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function zu(t){var e,n,r;try{switch(t){case"react":return null;case"nextjs":{const s=z();return((e=s==null?void 0:s.next)==null?void 0:e.version)||((n=s==null?void 0:s.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=z())==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 Gu(){const t=Zu(),e=zu(t);return{framework:t,version:e}}class Bu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(qo(s.origin)!==qo(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=Ga(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=n,this.formCallbacks=r,this.internalCallbacks=o}}const qo=t=>new URL(t).origin;async function qu(t,e){const r=await br({iframe:t,debug:!1,childOrigin:e}).promise,o=await pi(r);if(!fi(r,o))throw new Error("Got invalid CDE connection object");return r}class Yu{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Wu=(t,e,n)=>{const{stripePR:r}=t;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&&Yo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Yo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Yo=(t,e,n,r,o)=>U.stripePR.run({context:n,checkoutPaymentMethod:ft(n.checkoutPaymentMethods,t),nonCdeFormInputs:oe(n.formDiv),formCallbacks:r,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Wo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:ke,err__:me}=D("op-form"),Se=class Se{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ft,this.anyCdeConn=new Ft,this.context=new Ft,this.initFlows=xu(),this.startFormInit=async()=>{try{const s=this.createElement(ge.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"),ke("CDE bridge element mounted"),ke("Initializing OpenPay form:"),ke("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE load event received"),ke("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE connection received"),await al(c,this.deviceToken),ke("├ Creating OJS context, setting up handlers...");const l=Se.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Wu(this.initFlows,l,this.formCallbacks),ke("├ Starting OJS init flows..."),await Iu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),ke("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);me("╰ 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===ge.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=ra.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={[ge.CARD]:void 0,[ge.CARD_NUMBER]:void 0,[ge.CARD_EXPIRY]:void 0,[ge.CARD_CVC]:void 0,[ge.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",Ua(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{qu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ge.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>me("[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){me("Please wait for the form to finish loading before submitting.");return}U.commonCC.run({context:i,checkoutPaymentMethod:ft(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:oe(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)){me("Please wait for the form to finish loading before getting available payment methods.");return}const i={paypal:X.paypal,airwallexGooglePay:X.airwallexGooglePay,airwallexApplePay:X.airwallexApplePay,authorizeNetGooglePay:X.authorizenetGooglePay,authorizeNetApplePay:X.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){me("Please wait for the form to finish loading before submitting.");return}switch(s){case X.pockytPaypal:return U.pockytPaypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case X.paypal:return U.paypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","paypal"),nonCdeFormInputs:oe(c.formDiv),initResult:void 0,customParams:{settings:{...i,useRedirectFlow:!0}},formCallbacks:this.formCallbacks});case X.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.loopCrypto:return U.loopCrypto.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:fn(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;ke("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=z())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Wc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Se.assignAsSingleton(this),this.ojsVersion="0.3.3",this.ojsReleaseVersion="0.3.3",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Wn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${rt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Yu,this.deviceToken=$u(),Yc();const{framework:n,version:r}=Gu();Xr(this.baseUrl).then(s=>{if(!Zn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Zn.set(i)}}),E("form_init"),this.eventHandler=new Bu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=z())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(e="unknown"){const n=Se.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(n==null?void 0:n.formId)||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},o=`
|
|
25
|
+
Details: got ${t.required_user_actions.length} required user actions`);return Na.parse(t.required_user_actions[0])},ku=()=>{const t=rt().split("-")[0];return{firstName:`xx_${t}`,lastName:`xx_${t}`,email:`xx_${t}@email.com`,zipCode:`xx_${t}`,country:"US"}},{log__:qe,err__:Cu}=D("paypal"),$o=a.object({provider:a.literal("paypal"),metadata:a.object({client_id:a.string()}),processor_name:a.literal("paypal")}),Su=async({context:t,formCallbacks:e})=>{const n=ae(t.checkoutPaymentMethods,$o);if(!n)throw new Error("PayPal CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:()=>U.paypal.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{settings:{}}})}},Pu=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{try{qe("Running PayPal flow...");const s=t.anyCdeConnection,i=await G(s),{isAnonymous:c,useRedirectFlow:l}=o.settings??{};qe("Verifying CPM...");const u=$o.parse(n);qe("├ Validating non-CDE form fields");const d=Re(e,r.get.onValidationError,c?ku():void 0),f=ho(d);qe(`Starting payment flow... Mode: ${i.mode}`);const m=rt(),p=i.mode!=="setup",_={payment_provider:u.provider,checkout_payment_method:u,use_pay_first_flow:p,pay_first_flow_cart_info:p?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:l,frontend_token_for_redirect_flow:m},...f},w=new URL("/app/pre-action/start/",t.baseUrl).toString(),A=btoa(JSON.stringify(_)),k=new URLSearchParams({st:i.token,r:A}),x=`${w}?${k.toString()}`;if(l)throw qe("Starting redirect mode for PayPal..."),window.location.href=x,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");const I=await go("PayPal",s,m,x);qe("Paypal flow result",I);const L=Yn(I.href,"catt"),B=Yn(I.href,"approval_session_id"),$=await se(s,{secure_token:i.token,checkout_attempt_id:p?L:void 0,their_pm_id:p?B:void 0});return qe("Confirm payment flow result",$),jt({logPrefix:"paypal",anyCdeConnection:s,checkoutPaymentMethod:u,requiredFormFields:d,confirmResult:$,usePayFirstFlow:p})}catch(s){throw Cu("PayPal payment error",s),E("checkout_error",{payment_method:"paypal",error:s}),new Error((s==null?void 0:s.message)??"Unknown error")}}),ft=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);return r.length!==1&&(console.warn("CPMs list",t),console.warn(`More than one CPM found with provider '${e}' and processor '${n}'`),E("more_than_one_cpm_found",{provider:e,processor:n,cpms:t})),r[0]},U={commonCC:{init:async()=>{},run:Hl},stripePR:{init:gu,run:vu},stripeLink:{init:pu,run:fu},pockytPaypal:{run:cu},paypal:{init:Su,run:Pu},airwallexGooglePay:{init:Pl,run:Al},airwallexApplePay:{init:kl,run:Cl},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:xl,run:Rl},authorizeNetGooglePay:{init:Nl,run:Ol}},{log__:Au,err__:Tu}=D("init-flows"),Ue=(t,e)=>{const n=new Ft;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);Au(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){Tu(`𝙭 ${t} flow initialization failed. Error:`,re(o),"Details:",o),n.throw(o,re(o))}}}},Iu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},xu=()=>({stripePR:Ue("Stripe PR",U.stripePR.init),stripeLink:Ue("Stripe Link",U.stripeLink.init),airwallexGooglePay:Ue("Airwallex GooglePay",U.airwallexGooglePay.init),airwallexApplePay:Ue("Airwallex ApplePay",U.airwallexApplePay.init),loop:Ue("Loop",U.loopCrypto.init),paypal:Ue("PayPal",U.paypal.init),authorizeNetGooglePay:Ue("Authnet GooglePay",U.authorizeNetGooglePay.init),authorizeNetApplePay:Ue("Authnet ApplePay",U.authorizeNetApplePay.init)}),{err__:Ru}=D("form-callbacks"),fe=a.function().optional(),Vo=a.object({onFocus:fe,onBlur:fe,onChange:fe,onLoad:fe,onLoadError:fe,onValidationError:fe,onCheckoutStarted:fe,onCheckoutSuccess:fe,onSetupPaymentMethodSuccess:fe,onCheckoutError:fe,onPaymentRequestLoad:fe}),Ce=class Ce{constructor(){this.setCallbacks=e=>{this._callbacks=Ce.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=ta(n,r??Ce.NOOP,Ru);this._callbacks[n]=o})},this._callbacks=Ce.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ce.NOOP=()=>{},Ce.createEmptyCallbacks=()=>{const e={};return Object.keys(Vo.keyof().enum).forEach(n=>{e[n]=Ce.NOOP}),e},Ce.fromObject=e=>{const n=new Ce;return n.setCallbacks(Vo.parse(e)),n};let Wn=Ce;const Zo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Zt=32,Nu=16,zo=10,Go=0xffffffffffff;var Ye;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(Ye||(Ye={}));class zt extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function Ou(t){let e=Math.floor(t()*Zt);return e===Zt&&(e=Zt-1),Zo.charAt(e)}function Mu(t){const e=Du(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new zt(Ye.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Du(){return ju()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Fu(t,e){let n="";for(;t>0;t--)n=Ou(e)+n;return n}function Lu(t,e=zo){if(isNaN(t))throw new zt(Ye.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Go)throw new zt(Ye.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Go}: ${t}`);if(t<0)throw new zt(Ye.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new zt(Ye.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Zt,r=Zo.charAt(n)+r,t=(t-n)/Zt;return r}function ju(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Uu(t,e){const n=Mu(),r=Date.now();return Lu(r,zo)+Fu(Nu,n)}const Bo="op_analytics_device_token",$u=()=>{const t=document.cookie.split(";").find(n=>n.includes(Bo));if(t)return t.split("=")[1];const e=Uu();return Vu(e),e},Vu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Bo}=${t}; path=/; expires=${e.toUTCString()}`};function Zu(){try{const t=z(),e=t;if(e!=null&&e.next||e!=null&&e.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const n=t;if(n!=null&&n.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(o=>o.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(o=>o._reactRootContainer))return"react";const r=t;return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function zu(t){var e,n,r;try{switch(t){case"react":return null;case"nextjs":{const s=z();return((e=s==null?void 0:s.next)==null?void 0:e.version)||((n=s==null?void 0:s.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=z())==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 Gu(){const t=Zu(),e=zu(t);return{framework:t,version:e}}class Bu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(qo(s.origin)!==qo(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=Ga(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=n,this.formCallbacks=r,this.internalCallbacks=o}}const qo=t=>new URL(t).origin;async function qu(t,e){const r=await br({iframe:t,debug:!1,childOrigin:e}).promise,o=await pi(r);if(!fi(r,o))throw new Error("Got invalid CDE connection object");return r}class Yu{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Wu=(t,e,n)=>{const{stripePR:r}=t;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&&Yo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Yo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Yo=(t,e,n,r,o)=>U.stripePR.run({context:n,checkoutPaymentMethod:ft(n.checkoutPaymentMethods,t),nonCdeFormInputs:oe(n.formDiv),formCallbacks:r,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Wo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:ke,err__:me}=D("op-form"),Se=class Se{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ft,this.anyCdeConn=new Ft,this.context=new Ft,this.initFlows=xu(),this.startFormInit=async()=>{try{const s=this.createElement(ge.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"),ke("CDE bridge element mounted"),ke("Initializing OpenPay form:"),ke("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE load event received"),ke("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE connection received"),await al(c,this.deviceToken),ke("├ Creating OJS context, setting up handlers...");const l=Se.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Wu(this.initFlows,l,this.formCallbacks),ke("├ Starting OJS init flows..."),await Iu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),ke("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);me("╰ 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===ge.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=ra.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={[ge.CARD]:void 0,[ge.CARD_NUMBER]:void 0,[ge.CARD_EXPIRY]:void 0,[ge.CARD_CVC]:void 0,[ge.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",Ua(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{qu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ge.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>me("[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){me("Please wait for the form to finish loading before submitting.");return}U.commonCC.run({context:i,checkoutPaymentMethod:ft(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:oe(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)){me("Please wait for the form to finish loading before getting available payment methods.");return}const i={paypal:X.paypal,airwallexGooglePay:X.airwallexGooglePay,airwallexApplePay:X.airwallexApplePay,authorizeNetGooglePay:X.authorizenetGooglePay,authorizeNetApplePay:X.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){me("Please wait for the form to finish loading before submitting.");return}switch(s){case X.pockytPaypal:return U.pockytPaypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case X.paypal:return U.paypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","paypal"),nonCdeFormInputs:oe(c.formDiv),initResult:void 0,customParams:{settings:i},formCallbacks:this.formCallbacks});case X.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.loopCrypto:return U.loopCrypto.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:fn(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;ke("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=z())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Wc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Se.assignAsSingleton(this),this.ojsVersion="0.3.4",this.ojsReleaseVersion="0.3.4",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Wn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${rt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Yu,this.deviceToken=$u(),Yc();const{framework:n,version:r}=Gu();Xr(this.baseUrl).then(s=>{if(!Zn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Zn.set(i)}}),E("form_init"),this.eventHandler=new Bu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=z())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(e="unknown"){const n=Se.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(n==null?void 0:n.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.
|
package/package.json
CHANGED