Charge Extra Fees Based on Payment Gateway Selected

In this tutorial I will show you how to add extra charges to a specific payment gateway without plugins with the help of woocommerce_cart_calculate_fees filter hook.

charge additional fees for specific WooCommerce payment gateways
We add an additional £2 fee when customer chooses to pay with PayPal. And also displayed it near a payment gateway title.

I can also recommend you a tutorial about creating a custom payment gateway.

1. Create Additional Fee for a Specific Payment Gateway

add_action( 'woocommerce_cart_calculate_fees', 'rudr_paypal_fee', 25 );
function rudr_paypal_fee( $cart ) {

	if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
		return;
	}
	// if "PayPal" is the selected payment method, we add the fee
	if( 'paypal' == WC()->session->get( 'chosen_payment_method' ) ) {
		WC()->cart->add_fee( 'PayPal fee', 2 );
		// you can also use: $cart->add_fee( 'PayPal fee', 2 );
	}

}

2. Refresh the Checkout on Payment Method Change

It is also a crucial step. When a customer changes payment methods, we must show the fee in checkout immediately.

You can do it with JavaScript.

jQuery( function( $ ) {
	$( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
		$( 'body' ).trigger( 'update_checkout' );
	});
});

You can insert this code to your custom .js file or use wp_footer hook as an option. Another option is to add the following code into your current theme functions.php:

add_action( 'woocommerce_checkout_init', 'rudr_checkout_refresh' );
function rudr_checkout_refresh() {
    wc_enqueue_js( "jQuery( function( $ ){
        $( 'form.checkout' ).on( 'change', 'input[name^=\"payment_method\"]', function(){
            $( 'body' ).trigger( 'update_checkout' );
        });
    });");
}

3. Display Fee Amount Next to Payment Method Title (Optional)

How to add extra fees to payment gateways in WooCommerce

Code for your current or child theme functions.php:

add_filter( 'woocommerce_gateway_icon', 'rudr_display_method_fee', 25, 2 );

function rudr_display_method_fee( $icon_html, $gateway_id ) {

	if( 'paypal' === $gateway_id ) {
		return '<span class="custom-gateway-fee">' . wc_price( 2 ) . '</span>';
	}

}

And CSS:

.custom-gateway-fee {
	padding: 2px 6px;
	border-radius: 2px;
	margin-left: 10px;
	background-color: #ddd;
	float: right;
	font-size: 0.8em;
}
Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 13 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me

Follow me on Twitter