1 line
No EOL
13 KiB
JavaScript
1 line
No EOL
13 KiB
JavaScript
(()=>{"use strict";jQuery(document).ready((e=>{window.WC_Square_Digital_Wallet_Handler=class{constructor(t){!1!==t.payment_request&&(this.args=t,this.payment_request=t.payment_request,this.total_amount=t.payment_request.total?.amount,this.isPayForOrderPage=t.is_pay_for_order_page,this.orderId=t.order_id,this.id_dasherized=t.gateway_id_dasherized,this.cartForm=".cart",this.wallet="#wc-square-digital-wallet",this.buttons=".wc-square-wallet-buttons",this.isGooglePayHidden=this.args.hide_button_options.includes("google"),this.isApplePayHidden=this.args.hide_button_options.includes("apple"),this.productPageForm=e(".product form"),this.cartTotalsForms=e(".cart_totals, .woocommerce-cart-form"),this.checkoutForm=e("form.checkout, #wc-square-digital-wallet"),0!==e(this.wallet).length&&(e(this.wallet).hide(),e(this.buttons).hide(),this.build_digital_wallet(),this.attach_page_events(),this.buildDigitalWalletDebounced=this.debounce(this.build_digital_wallet,500)))}build_digital_wallet(){this.block_ui(),this.get_payment_request().then((e=>{this.payment_request=JSON.parse(e),this.total_amount=this.payment_request.total?.amount,this.load_square_form()}),(t=>{this.log("[Square] Could not build payment request. "+t,"error"),e(this.wallet).hide()}))}attach_page_events(){if("product"===this.args.context){const t=e(".single_add_to_cart_button");e("#apple-pay-button, #wc-square-google-pay").on("click",(e=>{if(t.is(".disabled")||!this.isProductAddonsFormsValid())return e.stopImmediatePropagation(),void(t.is(".wc-variation-is-unavailable")?window.alert(wc_add_to_cart_variation_params.i18n_unavailable_text):t.is(".wc-variation-selection-needed")&&window.alert(wc_add_to_cart_variation_params.i18n_make_a_selection_text));this.add_to_cart()})),e(document.body).on("woocommerce_variation_has_changed",(()=>this.build_digital_wallet())),e(".quantity").on("input",".qty",(()=>this.buildDigitalWalletDebounced()))}"cart"===this.args.context&&e(document.body).on("updated_cart_totals",(()=>this.build_digital_wallet())),"checkout"===this.args.context&&e(document.body).on("updated_checkout",(()=>this.build_digital_wallet())),e(document).on("payment_method_selected",(()=>{this.isPayForOrderPage&&e("#payment_method_override").remove()}))}load_square_form(){if(this.googlePay&&(this.googlePay.destroy(),this.squareFormLoaded=!1),this.applePay&&(this.applePay.destroy(),this.squareFormLoaded=!1),this.squareFormLoaded)return;this.squareFormLoaded=!0,this.log("[Square] Building digital wallet payment form");const{applicationId:e,locationId:t}=this.get_form_params();this.payments=window.Square.payments(e,t),this.initializeDigitalWalletPaymentMethods()}async initializeDigitalWalletPaymentMethods(){if(!this.payments)return;const t=this.payments.paymentRequest(this.create_payment_request());if(this.registerDigitalWalletShippingEventHandlers(t),this.isGooglePayHidden||(this.googlePay=await this.payments.googlePay(t),this.googlePay.attach("#wc-square-google-pay",{buttonSizeMode:"fill",buttonType:"long",buttonColor:this.args.google_pay_color}),e("#wc-square-google-pay").on("click",(async e=>this.handleGooglePayPaymentMethodSubmission(e,this.googlePay))),e("#wc-square-google-pay").show()),!this.isApplePayHidden)try{this.applePay=await this.payments.applePay(t),e("#apple-pay-button").on("click",(async e=>this.handleApplePayPaymentMethodSubmission(e,this.applePay))),e("#apple-pay-button").show()}catch(e){console.log(e.message)}(this.googlePay||this.applePay)&&(e(this.buttons).unblock(),e(this.wallet).show())}async handleGooglePayPaymentMethodSubmission(e,t=null){if(e.preventDefault(),!t)return;switch(this.blockedForm=null,this.args.context){case"product":this.blockedForm=this.blockForms(this.productPageForm);break;case"cart":this.blockedForm=this.blockForms(this.cartTotalsForms);break;case"checkout":this.blockedForm=this.blockForms(this.checkoutForm)}const a=await t.tokenize();if("OK"===a.status){const e={...a.details.card,digital_wallet_type:a.details.method},t={billingContact:a.details.billing};a.details.shipping&&(t.shippingContact=a.details.shipping.contact,t.shippingOption=a.details.shipping.option),this.handle_card_nonce_response(!1,a.token,e,t)}else this.blockedForm&&this.blockedForm.unblock()}blockForms(e){return e.block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),e}async handleApplePayPaymentMethodSubmission(e,t=null){if(e.preventDefault(),!t)return;const a=await t.tokenize();if("OK"===a.status){const e={...a.details.card,digital_wallet_type:a.details.method},t={billingContact:a.details.billing};a.details.shipping&&(t.shippingContact=a.details.shipping.contact,t.shippingOption=a.details.shipping.option),this.handle_card_nonce_response(!1,a.token,e,t)}}registerDigitalWalletShippingEventHandlers(e){e.addEventListener("shippingoptionchanged",(e=>this.handle_shipping_option_changed(e))),e.addEventListener("shippingcontactchanged",(e=>this.handle_shipping_address_changed(e)))}get_form_params(){const e={applicationId:this.args.application_id,locationId:this.args.location_id,autobuild:!1,applePay:{elementId:"apple-pay-button"},googlePay:{elementId:"wc-square-google-pay"}};return!1===this.payment_request.requestShippingAddress&&delete e.callbacks.shippingOptionChanged,this.args.hide_button_options.includes("google")&&delete e.googlePay,this.args.hide_button_options.includes("apple")&&delete e.applePay,e}create_payment_request(){return this.payment_request}methods_supported(t,a){!0===t.applePay||!0===t.googlePay?(!0===t.applePay&&e("#apple-pay-button").show(),!0===t.googlePay&&e("#wc-square-google-pay").show(),e(this.wallet).show()):this.log(a)}get_payment_request(){return new Promise(((t,a)=>{const i={context:this.args.context,security:this.args.payment_request_nonce,is_pay_for_order_page:this.isPayForOrderPage,order_id:this.orderId};if("product"===this.args.context){const t=this.get_product_data();e.extend(i,t)}e.post(this.get_ajax_url("get_payment_request"),i,(e=>e.success?t(e.data):a(e.data)))}))}async handle_shipping_address_changed(e){const t={context:this.args.context,shipping_contact:e,security:this.args.recalculate_totals_nonce,is_pay_for_order_page:this.isPayForOrderPage,order_id:this.orderId};return await this.recalculate_totals(t)}async handle_shipping_option_changed(e){const t={context:this.args.context,shipping_option:e.id,security:this.args.recalculate_totals_nonce,is_pay_for_order_page:this.isPayForOrderPage,order_id:this.orderId};return await this.recalculate_totals(t)}handle_card_nonce_response(t=!1,a=!1,i={},s={}){if(t)return this.render_errors(t);if(!a)return this.render_errors(this.args.general_error);this.block_ui();const o=e("#order_review"),{billingContact:n={},shippingContact:r={},shippingOption:l=null}=s,d={action:"",_wpnonce:this.args.process_checkout_nonce,billing_first_name:n.givenName?n.givenName:"",billing_last_name:n.familyName?n.familyName:"",billing_company:e("#billing_company").val(),billing_email:r.email?r.email:n.email?n.email:"",billing_phone:r.phone?r.phone:"",billing_country:n.countryCode?n.countryCode.toUpperCase():"",billing_address_1:n.addressLines&&n.addressLines[0]?n.addressLines[0]:"",billing_address_2:n.addressLines&&n.addressLines[1]?n.addressLines[1]:"",billing_city:n.city?n.city:"",billing_state:n.state?n.state:"",billing_postcode:n.postalCode?n.postalCode:"",shipping_first_name:r.givenName?r.givenName:"",shipping_last_name:r.familyName?r.familyName:"",shipping_company:e("#shipping_company").val(),shipping_country:r.countryCode?r.countryCode.toUpperCase():"",shipping_address_1:r.addressLines&&r.addressLines[0]?r.addressLines[0]:"",shipping_address_2:r.addressLines&&r.addressLines[1]?r.addressLines[1]:"",shipping_city:r.city?r.city:"",shipping_state:r.state?r.state:"",shipping_postcode:r.postalCode?r.postalCode:"",shipping_method:[l?l.id:null],order_comments:"",payment_method:"square_credit_card",ship_to_different_address:1,terms:1,"wc-square-credit-card-payment-nonce":a,"wc-square-credit-card-last-four":i.last4?i.last4:null,"wc-square-credit-card-exp-month":i.expMonth?i.expMonth:null,"wc-square-credit-card-exp-year":i.expYear?i.expYear:null,"wc-square-credit-card-payment-postcode":i.billing.postalCode?i.billing.postalCode:null,"wc-square-digital-wallet-type":i.digital_wallet_type,is_pay_for_order_page:this.isPayForOrderPage};this.isPayForOrderPage&&(i.last4&&e(`input[name=wc-${this.id_dasherized}-last-four]`).val(i.last4),i.expMonth&&e(`input[name=wc-${this.id_dasherized}-exp-month]`).val(i.expMonth),i.expYear&&e(`input[name=wc-${this.id_dasherized}-exp-year]`).val(i.expYear),i?.billing?.postalCode&&e(`input[name=wc-${this.id_dasherized}-payment-postcode]`).val(i.billing.postalCode),i.brand&&e(`input[name=wc-${this.id_dasherized}-card-type]`).val(i.brand),e(`input[name=wc-${this.id_dasherized}-payment-nonce]`).val(a),e("#payment_method_override").remove(),e("#payment").after('<input id="payment_method_override" type="hidden" name="payment_method" value="square_credit_card" />')),"GOOGLE_PAY"===i.digital_wallet_type&&(n.givenName&&(d.billing_first_name=n.givenName.split(" ").slice(0,1).join(" "),d.billing_last_name=n.givenName.split(" ").slice(1).join(" ")),r.givenName&&(d.shipping_last_name=r.givenName.split(" ").slice(0,1).join(" "),d.shipping_last_name=r.givenName.split(" ").slice(1).join(" "))),!d.billing_phone&&n.phone&&(d.billing_phone=n.phone),this.log("3DS verification enabled. Verifying buyer");var c=this;e("form.checkout").find(":input:not(:hidden)").serializeArray().forEach((function(e){e.name in d||(d[e.name]=e.value)})),delete d["wc-square-credit-card-payment-token"];try{this.payments.verifyBuyer(a,c.get_verification_details(n,r)).then((t=>{if(t.token){if(this.isPayForOrderPage&&o.length)return e(`input[name=wc-${this.id_dasherized}-buyer-verification-token]`).val(t.token),void o.trigger("submit");c.log("3DS verification successful"),d["wc-square-credit-card-buyer-verification-token"]=t.token,c.do_checkout(d)}}))}catch(e){c.log("3DS verification failed"),c.log(e),c.render_errors([e.message])}}do_checkout(e){this.process_digital_wallet_checkout(e).then((e=>{window.location=e.redirect}),(e=>{this.log(e,"error"),this.render_errors_html(e.messages)}))}get_verification_details(e,t){const a={intent:"CHARGE",amount:this.total_amount,currencyCode:this.payment_request.currencyCode,billingContact:{familyName:e.familyName?e.familyName:"",givenName:e.givenName?e.givenName:"",email:t.email?t.email:"",countryCode:e.countryCode?e.countryCode.toUpperCase():"",state:e.state?e.state:"",city:e.city?e.city:"",postalCode:e.postalCode?e.postalCode:"",phone:t.phone?t.phone:"",addressLines:e.addressLines?e.addressLines:""}};return this.log(a),a}async recalculate_totals(t){return new Promise(((a,i)=>e.post(this.get_ajax_url("recalculate_totals"),t,(e=>e.success?(this.total_amount=e.data.total?.amount,a(e.data)):i(e.data)))))}get_product_data(){let t=e(".single_add_to_cart_button").val();const a={};return e(".single_variation_wrap").length&&(t=e(".single_variation_wrap").find('input[name="product_id"]').val(),e(".variations_form").length&&e(".variations_form").find(".variations select").each(((t,i)=>{const s=e(i).data("attribute_name")||e(i).attr("name"),o=e(i).val()||"";return a[s]=o}))),{product_id:t,quantity:e(".quantity .qty").val(),attributes:a}}isProductAddonsFormsValid(){const t=e("form.cart");if(!t.length)return!0;const a=t.get(0).reportValidity();return window.WC_PAO&&WC_PAO.Form(t).$addons?WC_PAO.Form(t).validation.validate(!0)&&a:a}add_to_cart(){const t={security:this.args.add_to_cart_nonce},a=this.get_product_data(),i=e("form.cart");if(!i.length)return;e.extend(t,a);const s=new FormData(i.get(0));for(const[e,a]of s.entries())e.endsWith("[]")?Array.isArray(t[e])?t[e].push(a):t[e]=[a]:t[e]=a;e.post(this.get_ajax_url("add_to_cart"),t,(e=>{if(e.error)return window.alert(e.data);const t=JSON.parse(e.data);this.payment_request=t.payment_request,this.args.payment_request_nonce=t.payment_request_nonce,this.args.add_to_cart_nonce=t.add_to_cart_nonce,this.args.recalculate_totals_nonce=t.recalculate_totals_nonce,this.args.process_checkout_nonce=t.process_checkout_nonce}))}process_digital_wallet_checkout(t){return new Promise(((a,i)=>{e.post(this.get_ajax_url("process_checkout"),t,(e=>"success"===e.result?a(e):i(e)))}))}get_ajax_url(e){return this.args.ajax_url.replace("%%endpoint%%","square_digital_wallet_"+e)}render_errors_html(t){e(".woocommerce-error, .woocommerce-message").remove();let a="";switch(this.args.context){case"product":a=e(".product");break;case"cart":a=e(".shop_table.cart").closest("form");break;case"checkout":a=e('form[name="checkout"]')}a.before(t),this.blockedForm.unblock(),e("html, body").animate({scrollTop:a.offset().top-100},1e3)}render_errors(e){const t='<ul class="woocommerce-error"><li>'+e.join("</li><li>")+"</li></ul>";this.render_errors_html(t)}block_ui(){e(this.buttons).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})}log(e,t="notice"){if(this.args.logging_enabled)return"error"===t?console.error(e):console.log(e)}debounce(e,t,a){let i;return function(){let s=this,o=arguments,n=a&&!i;clearTimeout(i),i=setTimeout((function(){i=null,a||e.apply(s,o)}),t),n&&e.apply(s,o)}}}}))})(); |