From 60fda823c6757e08f5960bf65a7e4f566d89c5c0 Mon Sep 17 00:00:00 2001 From: ndeet Date: Wed, 31 Jan 2024 14:35:45 +0100 Subject: [PATCH] Add support for modal checkout on woocommerce blocks (#39) * Fix formatting. * Add modal checkout for woocommerce blocks. --- btcpay-greenfield-for-woocommerce.php | 69 ++++++- .../btcpay-greenfield-for-woocommerce.pot | 97 +++++----- readme.txt | 11 +- resources/js/frontend/blocksModalCheckout.js | 173 ++++++++++++++++++ src/Gateway/AbstractGateway.php | 61 ++++-- webpack.config.js | 1 + 6 files changed, 335 insertions(+), 77 deletions(-) create mode 100644 resources/js/frontend/blocksModalCheckout.js diff --git a/btcpay-greenfield-for-woocommerce.php b/btcpay-greenfield-for-woocommerce.php index 58ec8d5..df9c6b2 100644 --- a/btcpay-greenfield-for-woocommerce.php +++ b/btcpay-greenfield-for-woocommerce.php @@ -7,7 +7,7 @@ * Author URI: https://btcpayserver.org * Text Domain: btcpay-greenfield-for-woocommerce * Domain Path: /languages - * Version: 2.4.1 + * Version: 2.5.0 * Requires PHP: 7.4 * Tested up to: 6.4 * Requires at least: 5.2 @@ -26,7 +26,7 @@ defined( 'ABSPATH' ) || exit(); -define( 'BTCPAYSERVER_VERSION', '2.4.1' ); +define( 'BTCPAYSERVER_VERSION', '2.5.0' ); define( 'BTCPAYSERVER_VERSION_KEY', 'btcpay_gf_version' ); define( 'BTCPAYSERVER_PLUGIN_FILE_PATH', plugin_dir_path( __FILE__ ) ); define( 'BTCPAYSERVER_PLUGIN_URL', plugin_dir_url(__FILE__ ) ); @@ -44,6 +44,8 @@ public function __construct() { add_action( 'wp_ajax_btcpaygf_notifications', [$this, 'processAjaxNotification'] ); add_action( 'wp_ajax_nopriv_btcpaygf_modal_checkout', [$this, 'processAjaxModalCheckout'] ); add_action( 'admin_enqueue_scripts', [$this, 'enqueueAdminScripts'] ); + add_action( 'wp_ajax_btcpaygf_modal_blocks_checkout', [$this, 'processAjaxModalBlocksCheckout'] ); + add_action( 'wp_ajax_nopriv_btcpaygf_modal_blocks_checkout', [$this, 'processAjaxModalBlocksCheckout'] ); // Run the updates. \BTCPayServer\WC\Helper\UpdateManager::processUpdates(); @@ -237,13 +239,14 @@ public function processAjaxApiUrl() { } /** - * Handles the AJAX callback from the Payment Request on the checkout page. + * Handles the modal AJAX callback from the checkout page. */ public function processAjaxModalCheckout() { Logger::debug('Entering ' . __METHOD__); + Logger::debug('$_POST: ' . print_r($_POST, true)); - $nonce = $_POST['apiNonce']; + $nonce = sanitize_text_field($_POST['apiNonce']); if ( ! wp_verify_nonce( $nonce, 'btcpay-nonce' ) ) { wp_die('Unauthorized!', '', ['response' => 401]); } @@ -261,6 +264,61 @@ public function processAjaxModalCheckout() { } } + /** + * Handles the modal AJAX callback on the blocks checkout page. + */ + public function processAjaxModalBlocksCheckout() { + + Logger::debug('Entering ' . __METHOD__); + Logger::debug('$_POST: ' . print_r($_POST, true)); + + $nonce = sanitize_text_field($_POST['apiNonce']); + if ( ! wp_verify_nonce( $nonce, 'btcpay-nonce' ) ) { + wp_die('Unauthorized!', '', ['response' => 401]); + } + + if ( get_option('btcpay_gf_modal_checkout') !== 'yes' ) { + wp_die('Modal checkout mode not enabled.', '', ['response' => 400]); + } + + $selectedPaymentGateway = sanitize_text_field($_POST['paymentGateway']); + $orderId = sanitize_text_field($_POST['orderId']); + $order = wc_get_order($orderId); + + if ($order) { + + $orderPaymentMethod = $order->get_payment_method(); + if (empty($orderPaymentMethod) || $orderPaymentMethod !== $selectedPaymentGateway) { + $order->set_payment_method($selectedPaymentGateway); + $order->save(); + } + + $payment_gateways = \WC_Payment_Gateways::instance(); + + if ($payment_gateway = $payment_gateways->payment_gateways()[$selectedPaymentGateway]) { + + // Run the process_payment() method. + $result = $payment_gateway->process_payment($order->get_id()); + + if (isset($result['result']) && $result['result'] === 'success') { + wp_send_json_success($result); + } else { + wp_send_json_error($result); + } + + } else { + wp_send_json_error('Payment gateway not found.'); + } + } else { + wp_send_json_error('Order not found, stopped processing.'); + } + + wp_die(); + } + + /** + * Handles the AJAX callback to dismiss review notification. + */ public function processAjaxNotification() { check_ajax_referer('btcpaygf-notifications-nonce', 'nonce'); // Dismiss review notice for 30 days. @@ -268,6 +326,9 @@ public function processAjaxNotification() { wp_send_json_success(); } + /** + * Displays the payment status on the thank you page. + */ public static function orderStatusThankYouPage($order_id) { if (!$order = wc_get_order($order_id)) { diff --git a/languages/btcpay-greenfield-for-woocommerce.pot b/languages/btcpay-greenfield-for-woocommerce.pot index 6214695..b33413a 100644 --- a/languages/btcpay-greenfield-for-woocommerce.pot +++ b/languages/btcpay-greenfield-for-woocommerce.pot @@ -9,7 +9,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"POT-Creation-Date: 2024-01-22T21:36:35+00:00\n" +"POT-Creation-Date: 2024-01-31T10:40:12+00:00\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "X-Generator: WP-CLI 2.9.0\n" "language-team: LANGUAGE \n" @@ -35,84 +35,72 @@ msgstr "" msgid "https://btcpayserver.org" msgstr "" -#: btcpay-greenfield-for-woocommerce.php:135 +#: btcpay-greenfield-for-woocommerce.php:137 msgid "Plugin not configured yet, please %1$sconfigure the plugin here%2$s" msgstr "" -#: btcpay-greenfield-for-woocommerce.php:153 +#: btcpay-greenfield-for-woocommerce.php:155 msgid "Your PHP version is %s but BTCPay Greenfield Payment plugin requires version 7.4+." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:159 +#: btcpay-greenfield-for-woocommerce.php:161 msgid "WooCommerce seems to be not installed. Make sure you do before you activate BTCPayServer Payment Gateway." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:165 +#: btcpay-greenfield-for-woocommerce.php:167 msgid "The PHP cURL extension is not installed. Make sure it is available otherwise this plugin will not work." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:175 +#: btcpay-greenfield-for-woocommerce.php:177 msgid "Seems you have the old BTCPay for WooCommerce plugin installed. While it should work it is strongly recommended to not run both versions but rely on the maintained version (BTCPay Greenfield for WooCommerce)." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:186 +#: btcpay-greenfield-for-woocommerce.php:188 msgid "Thank you for using BTCPay for WooCommerce! If you like the plugin, we would love if you %1$sleave us a review%2$s." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:370 +#: btcpay-greenfield-for-woocommerce.php:431 msgid "Settings" msgstr "" -#: btcpay-greenfield-for-woocommerce.php:372 +#: btcpay-greenfield-for-woocommerce.php:433 msgid "Debug log" msgstr "" -#: btcpay-greenfield-for-woocommerce.php:374 +#: btcpay-greenfield-for-woocommerce.php:435 msgid "Docs" msgstr "" -#: btcpay-greenfield-for-woocommerce.php:376 +#: btcpay-greenfield-for-woocommerce.php:437 msgid "Support Chat" msgstr "" -#: btcpay-greenfield-for-woocommerce.php:416 +#: btcpay-greenfield-for-woocommerce.php:477 msgid "Error on verifiying redirected API wey with stored BTCPay Server url. Aborting API wizard. Please try again or do a manual setup." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:438 +#: btcpay-greenfield-for-woocommerce.php:499 msgid "Successfully received api key and store id from BTCPay Server API. Please finish setup by saving this settings form." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:442 +#: btcpay-greenfield-for-woocommerce.php:503 #: src/Admin/GlobalSettings.php:369 msgid "Successfully registered a new webhook on BTCPay Server." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:446 +#: btcpay-greenfield-for-woocommerce.php:507 #: src/Admin/GlobalSettings.php:373 msgid "Could not register a new webhook on the store." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:455 +#: btcpay-greenfield-for-woocommerce.php:516 msgid "Please make sure you only select one store on the BTCPay API authorization page." msgstr "" -#: btcpay-greenfield-for-woocommerce.php:460 +#: btcpay-greenfield-for-woocommerce.php:521 msgid "Error processing the data from BTCPay. Please try again." msgstr "" -#: generated/BTCPay_GF_BTC.php:25 -#: generated/BTCPay_GF_BTC_LightningNetwork.php:25 -#: generated/BTCPay_GF_BTC_LNURLPAY.php:25 -msgid "Token type" -msgstr "" - -#: generated/BTCPay_GF_BTC.php:32 -#: generated/BTCPay_GF_BTC_LightningNetwork.php:32 -#: generated/BTCPay_GF_BTC_LNURLPAY.php:32 -msgid "Tokens of type promotion will not have a FIAT (USD, EUR, ..) exchange rate but counted as 1 per item quantity. See here for more details." -msgstr "" - #: src/Admin/GlobalSettings.php:24 msgid "BTCPay Settings" msgstr "" @@ -403,97 +391,102 @@ msgstr "" msgid "Can't process order. Please contact us if the problem persists." msgstr "" -#: src/Gateway/AbstractGateway.php:204 +#: src/Gateway/AbstractGateway.php:219 msgid "Refund of order " msgstr "" -#: src/Gateway/AbstractGateway.php:282 +#: src/Gateway/AbstractGateway.php:297 msgid "Gateway Icon:" msgstr "" -#: src/Gateway/AbstractGateway.php:287 +#: src/Gateway/AbstractGateway.php:302 msgid "Upload or select icon" msgstr "" -#: src/Gateway/AbstractGateway.php:293 +#: src/Gateway/AbstractGateway.php:308 msgid "Remove image" msgstr "" -#: src/Gateway/AbstractGateway.php:343 +#: src/Gateway/AbstractGateway.php:358 msgid "Use this image" msgstr "" -#: src/Gateway/AbstractGateway.php:344 +#: src/Gateway/AbstractGateway.php:359 msgid "Insert image" msgstr "" -#: src/Gateway/AbstractGateway.php:382 +#: src/Gateway/AbstractGateway.php:397 msgctxt "js" msgid "The invoice expired. Please try again, choose a different payment method or contact us if you paid but the payment did not confirm in time." msgstr "" -#: src/Gateway/AbstractGateway.php:383 +#: src/Gateway/AbstractGateway.php:398 msgctxt "js" msgid "Payment aborted by you. Please try again or choose a different payment method." msgstr "" -#: src/Gateway/AbstractGateway.php:466 +#: src/Gateway/AbstractGateway.php:399 +msgctxt "js" +msgid "Error processing checkout. Please try again or choose another payment option." +msgstr "" + +#: src/Gateway/AbstractGateway.php:495 msgid "Webhook (%s) received from BTCPay, but the order is already processing or completed, skipping to update order status. Please manually check if everything is alright." msgstr "" -#: src/Gateway/AbstractGateway.php:478 +#: src/Gateway/AbstractGateway.php:507 msgid "Invoice (partial) payment incoming (unconfirmed) after invoice was already expired." msgstr "" -#: src/Gateway/AbstractGateway.php:481 +#: src/Gateway/AbstractGateway.php:510 msgid "Invoice (partial) payment incoming (unconfirmed). Waiting for settlement." msgstr "" -#: src/Gateway/AbstractGateway.php:500 +#: src/Gateway/AbstractGateway.php:529 msgid "Invoice fully settled after invoice was already expired. Needs manual checking." msgstr "" -#: src/Gateway/AbstractGateway.php:505 +#: src/Gateway/AbstractGateway.php:534 msgid "(Partial) payment settled but invoice not settled yet (could be more transactions incoming). Needs manual checking." msgstr "" -#: src/Gateway/AbstractGateway.php:509 +#: src/Gateway/AbstractGateway.php:538 msgid "Invoice (partial) payment settled." msgstr "" -#: src/Gateway/AbstractGateway.php:519 +#: src/Gateway/AbstractGateway.php:548 msgid "Invoice payment received fully with overpayment, waiting for settlement." msgstr "" -#: src/Gateway/AbstractGateway.php:521 +#: src/Gateway/AbstractGateway.php:550 msgid "Invoice payment received fully, waiting for settlement." msgstr "" -#: src/Gateway/AbstractGateway.php:527 +#: src/Gateway/AbstractGateway.php:556 msgid "Invoice manually marked invalid." msgstr "" -#: src/Gateway/AbstractGateway.php:529 +#: src/Gateway/AbstractGateway.php:558 msgid "Invoice became invalid." msgstr "" -#: src/Gateway/AbstractGateway.php:535 +#: src/Gateway/AbstractGateway.php:564 msgid "Invoice expired but was paid partially, please check." msgstr "" -#: src/Gateway/AbstractGateway.php:538 +#: src/Gateway/AbstractGateway.php:567 msgid "Invoice expired." msgstr "" -#: src/Gateway/AbstractGateway.php:544 +#: src/Gateway/AbstractGateway.php:573 msgid "Invoice payment settled but was overpaid." msgstr "" -#: src/Gateway/AbstractGateway.php:547 +#: src/Gateway/AbstractGateway.php:576 msgid "Invoice payment settled." msgstr "" -#: src/Gateway/AbstractGateway.php:590 +#: src/Gateway/AbstractGateway.php:619 msgid "BTCPay invoice manually set to invalid because customer went back to checkout and changed payment gateway." msgstr "" diff --git a/readme.txt b/readme.txt index 5da0eea..ce28453 100644 --- a/readme.txt +++ b/readme.txt @@ -5,7 +5,7 @@ Tags: Bitcoin, Lightning Network, BTCPay Server, WooCommerce, payment gateway, a Requires at least: 5.2 Tested up to: 6.4 Requires PHP: 7.4 -Stable tag: 2.4.1 +Stable tag: 2.5.0 License: MIT License URI: https://github.com/btcpayserver/woocommerce-greenfield-plugin/blob/master/license.txt @@ -15,7 +15,7 @@ BTCPay Server is a free and open-source bitcoin payment processor which allows y = Accept Bitcoin payments in your WooCommerce powered WordPress site with BTCPay Server = -BTCPay Server for WooCommerce is a revolutionary, self-hosted, open-source payment gateway to accept Bitcoin payments. Our** seamless integration** with WooCommerce allows you to connect your self-hosted [BTCPay Server](https://btcpayserver.org) and start accepting Bitcoin payments in **[just a few simple steps](https://docs.btcpayserver.org/WooCommerce)**. +BTCPay Server for WooCommerce is a revolutionary, self-hosted, open-source payment gateway to accept Bitcoin payments. Our **seamless integration** with WooCommerce allows you to connect your self-hosted [BTCPay Server](https://btcpayserver.org) and start accepting Bitcoin payments in **[just a few simple steps](https://docs.btcpayserver.org/WooCommerce)**. = Features: = @@ -111,10 +111,13 @@ You'll find extensive documentation and answers to many of your questions on [BT 6. On BTCPay Server you have extensive reporting and accounting features. == Upgrade Notice == -= 2.4.0 = -* New feature: Add basic support for [WooCommerce cart and checkout blocks](https://woo.com/document/cart-checkout-blocks-status/). += 2.5.0 = +* New feature: Added support for modal checkout with [WooCommerce checkout blocks](https://woo.com/document/cart-checkout-blocks-status/). == Changelog == += 2.5.0 :: 2024-01-31 = +* Fix: Formatting in readme.txt +* Add support for modal overlay for checkout blocks. = 2.4.1 :: 2024-01-22 = * Fix: Ensure order status is not cancelled if paid by other payment gateway. diff --git a/resources/js/frontend/blocksModalCheckout.js b/resources/js/frontend/blocksModalCheckout.js new file mode 100644 index 0000000..51b3bb4 --- /dev/null +++ b/resources/js/frontend/blocksModalCheckout.js @@ -0,0 +1,173 @@ + +// Add debouncing to avoid infinite loop. +let isProcessingOrder = false; +let lastExecutionTime = 0; +const debounceInterval = 1000; + +/** + * Subscribe to the checkout store and listen to place order button event, + * which changes emits the isBeforeProcessing() event. + */ +wp.data.subscribe(() => { + const now = Date.now(); + + // Check if the function was executed recently. + if (now - lastExecutionTime < debounceInterval) { + return; + } + + const isBeforeProcessing = wp.data.select(wc.wcBlocksData.CHECKOUT_STORE_KEY).isBeforeProcessing(); + + // Check the payment method on placing the order. + if (isBeforeProcessing && !isProcessingOrder) { + //console.log('Checkout is before processing. Run your custom code here.'); + + isProcessingOrder = true; // Set the flag to avoid re-triggering. + lastExecutionTime = now; // Update the last execution time. + + const store = wp.data.select(wc.wcBlocksData.PAYMENT_STORE_KEY); + const currentState = store.getState(); + const activePM = currentState.activePaymentMethod; + + //console.log('current payment method:'); + //console.log(activePM); + + if (activePM.startsWith('btcpaygf_')) { + //console.log('BTCPay is selected'); + + // Make sure the order exists and invoice is created. + let responseData = blocksProcessOrder(activePM); + //console.log(responseData); + if (responseData) { + //console.log('got response: '); + //console.log(responseData); + blocksShowBTCPayModal(responseData); + isProcessingOrder = false; + return false; + } else { + blocksSubmitError(BTCPayWP.textProcessingError); + isProcessingOrder = false; + return false; + } + } + + return true; + } + + +}); + +/** + * Trigger ajax request to create order object and assign an invoice id. + */ +const blocksProcessOrder = function (paymentGateway) { + //console.log('Triggered processOrderBlocks()'); + let responseData = null; + + // Block the UI. + //blockElement('.woocommerce-checkout-payment'); + const checkout = wp.data.select(wc.wcBlocksData.CHECKOUT_STORE_KEY); + const orderId = checkout.getOrderId(); + + // Prepare form data. + let data = { + 'action': 'btcpaygf_modal_blocks_checkout', + 'orderId': orderId, + 'paymentGateway': paymentGateway, + 'apiNonce': BTCPayWP.apiNonce, + }; + + //console.log(data); + // We need to make sure the order processing worked before returning from this function. + jQuery.ajaxSetup({async: false}); + + jQuery.post(wc_add_to_cart_params.ajax_url, data, function (response) { + //console.log('Received response when processing order: '); + //console.log(response); + + if (response.data.invoiceId) { + responseData = response.data; + } else { + ///unblockElement('.woocommerce-checkout-payment'); + // Show errors. + if (response.data) { + blocksSubmitError(response.data); + } else { + blocksSubmitError(BTCPayWP.textProcessingError); // eslint-disable-line max-len + } + } + }).fail(function () { + ///unblockElement('.woocommerce-checkout-payment'); + blocksSubmitError(BTCPayWP.textProcessingError); + console.error('Error on ajax request 2'); + }); + + // Reenable async. + jQuery.ajaxSetup({async: true}); + + return responseData; +}; + +/** + * Show the BTCPay modal and listen to events sent by BTCPay server. + */ +const blocksShowBTCPayModal = function (data) { + //console.log('Triggered blocksShowBTCPModal()'); + + if (data.invoiceId !== undefined) { + window.btcpay.setApiUrlPrefix(BTCPayWP.apiUrl); + window.btcpay.showInvoice(data.invoiceId); + } + let invoice_paid = false; + window.btcpay.onModalReceiveMessage(function (event) { + if (isObject(event.data)) { + //console.log('BTCPay modal event: invoiceId: ' + event.data.invoiceId); + //console.log('BTCPay modal event: status: ' + event.data.status); + if (event.data.status) { + switch (event.data.status) { + case 'complete': + case 'paid': + invoice_paid = true; + window.location = data.orderCompleteLink; + break; + case 'expired': + window.btcpay.hideFrame(); + blocksSubmitError(BTCPayWP.textInvoiceExpired); + console.error('Invoice expired'); + break; + } + } + } else { // handle event.data "loaded" "closed" + if (event.data === 'close') { + if (invoice_paid === true) { + window.location = data.orderCompleteLink; + } + blocksSubmitError(BTCPayWP.textModalClosed); + } + } + }); + const isObject = obj => { + return Object.prototype.toString.call(obj) === '[object Object]' + } +} + +/** + * Show errors on the checkout page. + * + * @param error_message + */ +const blocksSubmitError = function (error_message) { + window.wp.data.dispatch( 'core/notices' ) + .createErrorNotice( + error_message, + { context: 'wc/checkout' } + ); + resetCheckout(); +}; + +/** + * Reset the checkout store to reenable the place order button. + */ +const resetCheckout = function () { + wp.data.dispatch( wc.wcBlocksData.CHECKOUT_STORE_KEY ).__internalSetIdle(); +} diff --git a/src/Gateway/AbstractGateway.php b/src/Gateway/AbstractGateway.php index 4259064..5e25253 100644 --- a/src/Gateway/AbstractGateway.php +++ b/src/Gateway/AbstractGateway.php @@ -101,25 +101,35 @@ public function process_payment( $orderId ) { throw new \Exception( $message ); } - // Check if the order is a modal payment. if (isset($_POST['action'])) { $action = wc_clean( wp_unslash( $_POST['action'] ) ); - if ( $action === 'btcpaygf_modal_checkout' ) { + if ( in_array($action, ['btcpaygf_modal_checkout', 'btcpaygf_modal_blocks_checkout']) ) { Logger::debug( 'process_payment called via modal checkout.' ); } } + // Determine if modal checkout is enabled. + $isModal = false; + if ( get_option('btcpay_gf_modal_checkout') === 'yes' ) { + $isModal = true; + } + // Check for existing invoice and redirect instead. if ( $this->validInvoiceExists( $orderId ) ) { $existingInvoiceId = $order->get_meta( 'BTCPay_id' ); Logger::debug( 'Found existing BTCPay Server invoice and redirecting to it. Invoice id: ' . $existingInvoiceId ); - return [ + $response = [ 'result' => 'success', - 'redirect' => $this->apiHelper->getInvoiceRedirectUrl( $existingInvoiceId ), 'invoiceId' => $existingInvoiceId, 'orderCompleteLink' => $order->get_checkout_order_received_url(), ]; + + if (!$isModal) { + $response['redirect'] = $this->apiHelper->getInvoiceRedirectUrl( $existingInvoiceId ); + } + + return $response; } // Create an invoice. @@ -136,12 +146,17 @@ public function process_payment( $orderId ) { $url = str_replace($this->apiHelper->url, $_SERVER['SERVER_NAME'], $url); } */ - return [ + $response = [ 'result' => 'success', - 'redirect' => $url, 'invoiceId' => $invoice->getData()['id'], 'orderCompleteLink' => $order->get_checkout_order_received_url(), ]; + + if (!$isModal) { + $response['redirect'] = $url; + } + + return $response; } } @@ -360,31 +375,43 @@ public function addPublicScripts() { // Load BTCPay modal JS. wp_enqueue_script( 'btcpay_gf_modal_js', $this->apiHelper->url . '/modal/btcpay.js', [], BTCPAYSERVER_VERSION ); + // Get page id of checkout page. + $checkoutPageId = wc_get_page_id('checkout'); + // Check if the checkout page uses the new woocommerce blocks. + $isBlockCheckout = has_block( 'woocommerce/checkout' , $checkoutPageId); + if ($isBlockCheckout) { + $scriptName = 'btcpay_gf_modal_blocks_checkout'; + $scriptFile = BTCPAYSERVER_PLUGIN_URL . 'assets/js/frontend/blocksModalCheckout.js'; + } else { + $scriptName = 'btcpay_gf_modal_checkout'; + $scriptFile = BTCPAYSERVER_PLUGIN_URL . 'assets/js/frontend/modalCheckout.js'; + } + // Register modal script. wp_register_script( - 'btcpay_gf_modal_checkout', - BTCPAYSERVER_PLUGIN_URL . 'assets/js/frontend/modalCheckout.js', - [ 'jquery' ], + $scriptName, + $scriptFile, + [ 'jquery', 'wp-data' ], BTCPAYSERVER_VERSION, true ); // Pass object BTCPayWP to be available on the frontend. - wp_localize_script( 'btcpay_gf_modal_checkout', 'BTCPayWP', [ - 'modalEnabled' => get_option('btcpay_gf_modal_checkout') === 'yes', - 'debugEnabled' => get_option('btcpay_gf_debug') === 'yes', + wp_localize_script( $scriptName, 'BTCPayWP', [ + 'modalEnabled' => get_option( 'btcpay_gf_modal_checkout' ) === 'yes', + 'debugEnabled' => get_option( 'btcpay_gf_debug' ) === 'yes', 'url' => admin_url( 'admin-ajax.php' ), 'apiUrl' => $this->apiHelper->url, 'apiNonce' => wp_create_nonce( 'btcpay-nonce' ), 'isChangePaymentPage' => isset( $_GET['change_payment_method'] ) ? 'yes' : 'no', 'isPayForOrderPage' => is_wc_endpoint_url( 'order-pay' ) ? 'yes' : 'no', 'isAddPaymentMethodPage' => is_add_payment_method_page() ? 'yes' : 'no', - 'textInvoiceExpired' => _x('The invoice expired. Please try again, choose a different payment method or contact us if you paid but the payment did not confirm in time.', 'js', 'btcpay-greenfield-for-woocommerce'), - 'textModalClosed' => _x('Payment aborted by you. Please try again or choose a different payment method.', 'js', 'btcpay-greenfield-for-woocommerce'), + 'textInvoiceExpired' => _x( 'The invoice expired. Please try again, choose a different payment method or contact us if you paid but the payment did not confirm in time.', 'js', 'btcpay-greenfield-for-woocommerce' ), + 'textModalClosed' => _x( 'Payment aborted by you. Please try again or choose a different payment method.', 'js', 'btcpay-greenfield-for-woocommerce' ), + 'textProcessingError' => _x( 'Error processing checkout. Please try again or choose another payment option.', 'js', 'btcpay-greenfield-for-woocommerce' ), ] ); - - // Add the registered modal script to frontend. - wp_enqueue_script( 'btcpay_gf_modal_checkout' ); + // Add the registered modal blocks script to frontend. + wp_enqueue_script( $scriptName ); } /** diff --git a/webpack.config.js b/webpack.config.js index 5c68ba3..4556d5b 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -47,6 +47,7 @@ module.exports = { new CopyWebpackPlugin({ patterns: [ { from: 'resources/js/frontend/modalCheckout.js', to: 'frontend/', info: { minimized: true } }, + { from: 'resources/js/frontend/blocksModalCheckout.js', to: 'frontend/', info: { minimized: false } }, { from: 'resources/js/backend/gatewayIconMedia.js', to: 'backend/', info: { minimized: true } }, { from: 'resources/js/backend/apiKeyRedirect.js', to: 'backend/', info: { minimized: true } }, { from: 'resources/js/backend/notifications.js', to: 'backend/', info: { minimized: true } }