diff --git a/resources/js/src/features/surcharge/gatewaySurcharge.js b/resources/js/src/features/surcharge/gatewaySurcharge.js index 6de6cf845..d7f91636f 100644 --- a/resources/js/src/features/surcharge/gatewaySurcharge.js +++ b/resources/js/src/features/surcharge/gatewaySurcharge.js @@ -1,17 +1,50 @@ ( function ( { jQuery, surchargeData } ) { - jQuery( function ( $ ) { - $( 'body' ).on( 'change', 'input[name="payment_method"]', function () { - $( 'body' ).trigger( 'update_checkout' ); - } ); - } ); if ( ! surchargeData ) { return; } + const surchargeGatewayIds = Array.isArray( surchargeData.surchargeGatewayIds ) + ? surchargeData.surchargeGatewayIds + : []; + + const gatewayHasSurcharge = ( gatewayId ) => + surchargeGatewayIds.indexOf( gatewayId ) !== -1; + const isOrderPay = document.body.classList.contains( 'woocommerce-order-pay' ); + if ( ! isOrderPay ) { + jQuery( function ( $ ) { + let previousPaymentMethod = + $( 'input[name="payment_method"]:checked' ).val() || ''; + + $( 'body' ).on( 'updated_checkout', function () { + previousPaymentMethod = + $( 'input[name="payment_method"]:checked' ).val() || ''; + } ); + + $( 'body' ).on( + 'change', + 'input[name="payment_method"]', + function () { + const currentPaymentMethod = + $( 'input[name="payment_method"]:checked' ).val() || + ''; + + if ( + gatewayHasSurcharge( previousPaymentMethod ) || + gatewayHasSurcharge( currentPaymentMethod ) + ) { + $( 'body' ).trigger( 'update_checkout' ); + } + + previousPaymentMethod = currentPaymentMethod; + } + ); + } ); + } + if ( isOrderPay ) { jQuery( function ( $ ) { let orderId = false; diff --git a/src/Shared/GatewaySurchargeHandler.php b/src/Shared/GatewaySurchargeHandler.php index 8a408de44..c010ae133 100644 --- a/src/Shared/GatewaySurchargeHandler.php +++ b/src/Shared/GatewaySurchargeHandler.php @@ -64,10 +64,44 @@ public function enqueueSurchargeScript(): void [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'gatewayFeeLabel' => $this->gatewayFeeLabel, + 'surchargeGatewayIds' => $this->surchargeGatewayIds(), ] ); } + protected function surchargeGatewayIds(): array + { + if (!function_exists('WC') || !WC()->payment_gateways()) { + return []; + } + + $paymentGateways = WC()->payment_gateways()->payment_gateways(); + $gatewayIds = []; + + foreach ($paymentGateways as $gatewayId => $gateway) { + $gatewayId = (string) $gatewayId; + + if (!$this->isMollieGateway($gatewayId)) { + continue; + } + + $gatewaySettings = $this->gatewaySettings($gatewayId); + + if (!$gatewaySettings) { + continue; + } + + if ( + isset($gatewaySettings['payment_surcharge']) + && $gatewaySettings['payment_surcharge'] !== Surcharge::NO_FEE + ) { + $gatewayIds[] = $gatewayId; + } + } + + return $gatewayIds; + } + public function addSurchargeFeeProductPage($order, $gateway) { $gatewaySettings = $this->gatewaySettings($gateway);