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
43
<?php // <-- be careful when copy pasting..
 
function woocommerce_custom_fee( ) {
 
	if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
		return;
 
	$chosen_gateway = WC()->session->chosen_payment_method;
 
	$fee = 2;
	// or calculate your $fee with all the php magic...
        // $fee = WC()->cart->cart_contents_total * .025; // sample computation for getting 2.5% of the cart total.
 
	if ( $chosen_gateway == 'paypal' ) { //test with paypal method
		WC()->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...

6 Responses

  1. Fayzaan says:

    Thanks so much for the script. It will save money buying a plugin. However is it possible to do so, only on selected categories? Like category 1 will have 10% fees while category 2 will have 5% category 3 will have no fees for a specific payment gateway? Thank you of much.

    • Reigel Gallarde says:

      yes… you can… depends on how you do it.. you can use WC()->cart->get_cart() to get the items on the cart. Then loop each to check the category.

      • Fayzaan says:

        Sorry but i am not an expert in php. I know very basic. Can you please give me the snippet? Thanks.

  2. Daniel says:

    Thank you Reigel! You’re a lifesaver.

  3. Really thanks for this !, i try it, with my custom funciton plugin, and work well !

  4. Ryan says:

    Awesome solution Reigel, can’t express how grateful I am that you put together this.

Leave a Reply

Your email address will not be published. Required fields are marked *