WooCommerce Payment Gateway Based Fees without using plugins

If ever you needed to add fees on checkout based on the chosen payment method, then this is what you are looking for.

Just copy and paste this on your functions.php of the current theme and it should work.

What this would do is in the checkout page, if a customer chooses paypal as payment, additional fee will be calculated…
What you need to do is change the value of $fee to your desired value. Any value. You can also do some calculations and apply it to $fee.
Change ‘paypal’ on line 13 with your payment gateway in mind. No other changes needed on the code except if you really need to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php // <-- be careful when copy pasting..
 
function woocommerce_custom_fee( ) {
	global $woocommerce;
	if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
		return;
 
	$chosen_gateway = $woocommerce->session->chosen_payment_method;
 
	$fee = 2;
	// or calculate your $fee with all the php magic...
 
	if ( $chosen_gateway == 'paypal' ) { //test with paypal method
		$woocommerce->cart->add_fee( 'Paypal fee', $fee, false, '' );
	}
}
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_fee' );
 
function cart_update_script() {
    if (is_checkout()) :
    ?>
    <script>
		jQuery( function( $ ) {
 
			// woocommerce_params is required to continue, ensure the object exists
			if ( typeof woocommerce_params === 'undefined' ) {
				return false;
			}
 
			$checkout_form = $( 'form.checkout' );
 
			$checkout_form.on( 'change', 'input[name="payment_method"]', function() {
					$checkout_form.trigger( 'update' );
			});
 
 
		});
    </script>
    <?php
    endif;
}
add_action( 'wp_footer', 'cart_update_script', 999 );

You may also like...