From a467533ba65a40992db6156345e17e34c6172b40 Mon Sep 17 00:00:00 2001
From: Philipp Stracker
Date: Mon, 26 Aug 2024 17:10:51 +0200
Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Sync=20WC=20shipping=20details?=
=?UTF-8?q?=20with=20Google=20Pay?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
This change keeps the checkout & cart forms in-sync with the Google Pay form, to ensure the form submits the same details that the user can see inside Google Pay
---
.../resources/js/GooglepayButton.js | 54 +++++++++++++++++++
1 file changed, 54 insertions(+)
diff --git a/modules/ppcp-googlepay/resources/js/GooglepayButton.js b/modules/ppcp-googlepay/resources/js/GooglepayButton.js
index 6b67dab72..3e1fc2eb4 100644
--- a/modules/ppcp-googlepay/resources/js/GooglepayButton.js
+++ b/modules/ppcp-googlepay/resources/js/GooglepayButton.js
@@ -525,6 +525,11 @@ class GooglepayButton extends PaymentButton {
updatedData.total,
updatedData.shipping_fee
);
+
+ // This page contains a real cart and potentially a form for shipping options.
+ this.syncShippingOptionWithForm(
+ paymentData?.shippingOptionData?.id
+ );
} else {
transactionInfo.shippingFee = this.getShippingCosts(
paymentData?.shippingOptionData?.id,
@@ -728,6 +733,55 @@ class GooglepayButton extends PaymentButton {
return response;
}
+
+ /**
+ * Updates the shipping option in the checkout form, if a form with shipping options is
+ * detected.
+ *
+ * @param {string} shippingOption - The shipping option ID, e.g. "flat_rate:4".
+ * @return {boolean} - True if a shipping option was found and selected, false otherwise.
+ */
+ syncShippingOptionWithForm( shippingOption ) {
+ const wrappers = [
+ // Classic checkout, Classic cart.
+ '.woocommerce-shipping-methods',
+ // Block checkout.
+ '.wc-block-components-shipping-rates-control',
+ // Block cart.
+ '.wc-block-components-totals-shipping',
+ ];
+
+ const sanitizedShippingOption = shippingOption.replace( /"/g, '' );
+
+ // Check for radio buttons with shipping options.
+ for ( const wrapper of wrappers ) {
+ const selector = `${ wrapper } input[type="radio"][value="${ sanitizedShippingOption }"]`;
+ const radioInput = document.querySelector( selector );
+
+ if ( radioInput ) {
+ radioInput.click();
+ return true;
+ }
+ }
+
+ // Check for select list with shipping options.
+ for ( const wrapper of wrappers ) {
+ const selector = `${ wrapper } select option[value="${ sanitizedShippingOption }"]`;
+ const selectOption = document.querySelector( selector );
+
+ if ( selectOption ) {
+ const selectElement = selectOption.closest( 'select' );
+
+ if ( selectElement ) {
+ selectElement.value = sanitizedShippingOption;
+ selectElement.dispatchEvent( new Event( 'change' ) );
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
}
export default GooglepayButton;