WooCommerce: Add Checkout Fee for a Payment Gateway (e.g. PayPal)

Here’s a simple PHP snippet to add a fee to the checkout for every payment or for a specific payment gateway.

Please do remember that for certain payment gateways such as PayPal, adding checkout fees is currently against their Terms of Service so make sure to check this first.

As usual, this needs to be copied and pasted in your child theme’s functions.php file. Enjoy!

Add fee/surcharge to the WooCommerce Cart/Checkout

PHP Snippet #1: Add fee to checkout for all payment gateways – WooCommerce

/**
 * @snippet       WooCommerce add fee to checkout
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 5.1
 * @community     https://businessbloomer.com/club/
 */
 
add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee' );
 
function bbloomer_add_checkout_fee() {
   // Edit "Fee" and "5" below to control Label and Amount
   WC()->cart->add_fee( 'Fee', 5 );
}

PHP Snippet #2: Add fee to checkout for a specific payment gateway – WooCommerce

/**
 * @snippet       WooCommerce add fee to checkout for a gateway ID
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.7
 * @community     https://businessbloomer.com/club/
 */
 
add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
 
function bbloomer_add_checkout_fee_for_gateway() {
 	$chosen_gateway = WC()->session->get( 'chosen_payment_method' );
  	if ( $chosen_gateway == 'paypal' ) {
		WC()->cart->add_fee( 'PayPal Fee', 5 );
	}
}

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

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]
  • WooCommerce: Disable Payment Method If Product Category @ Cart
    Today we take a look at the WooCommerce Checkout and specifically at how to disable a payment gateway (e.g. PayPal) if a specific product category is in the Cart. There are two tasks to code in this case: (1) based on all the products in the Cart, calculate the list of product categories in the […]
  • WooCommerce: Add Privacy Policy Checkbox @ Checkout
    Here’s a snippet regarding the checkout page. If you’ve been affected by GDPR, you will know you now need users to give you Privacy Policy consent. Or, you might need customer to acknowledge special shipping requirements for example. So, how do we display an additional tick box on the Checkout page (together with the existing […]
  • WooCommerce: Redirect to Custom Thank you Page
    How can you redirect customers to a beautifully looking, custom, thank you page? Thankfully you can add some PHP code to your functions.php or install a simple plugin and define a redirect to a custom WordPress page (as opposed to the default order-received endpoint). This is a great way for you to add specific up-sells, […]
  • WooCommerce: Disable Payment Gateway by Country
    You might want to disable PayPal for non-local customers or enable a specific gateway for only one country… Either way, this is a very common requirement for all of those who trade internationally. Here’s a simple snippet you can further customize to achieve your objective. Simply pick the payment gateway “slug” you want to disable/enable […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

117 thoughts on “WooCommerce: Add Checkout Fee for a Payment Gateway (e.g. PayPal)

  1. I’ve tried this but I can’t seem to get it to work for Woocommerce_payments only – when I change to Bank Transfer it doesn’t update

    1. I see. What did you use for $chosen_gateway?

  2. Hello,

    Too bad it doesn’t work with the version of PayPal I currently have.

    https://fr.wordpress.org/plugins/woocommerce-paypal-payments/

    1. Try to find out if they use a different payment gateway ID (other than “paypal”). It could be “paypal-payments” for example, in which case you need to change the code a little.

      1. It’s ‘ppcp-gateway’ now

  3. 27th July 2022 still working like a charm ;

  4. Hi, what if I am using multicurrency on my web? with this snippet amount does not convert. I it possible to solve somehow?

    1. Hi Alex, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  5. Hi,

    I find a problem with the function, if the payment fails, the checkout page is shown but cash on delivery charge doesnโ€™t show up even after changing methods. Iโ€™m using Flatsome and WooCommerce.
    If you add any product to cart and paying via online payment method, cancel the transaction and then once youโ€™re redirected youโ€™ll be able to see no COD charges are being applied. Is it any other hook which “run” in this page?
    Can Youโ€™ll please have a look at it?

    1. Not 100% sure, did you try with no other plugin than Woo and a default theme already?

      1. Hi, I have the same problem. It happens when the payment does not go thru the cart, but for example I send out a payment link for an order. It has a bit of a different checkout so the manual page update applied to “woocommerce_after_checkout_form” is not happening there. Any idea how can I trigger the same function in the payment link page?

        1. So you mean the “Order Pay” page?

  6. I would like to apply 1.95% of processing fee, if customer pays via any credit card. I have saferpay and twint setup as payment gateways. Could you please confirm if the code below needs any changes. Please suggest. Thanks!

    **
     * @snippet       WooCommerce Add fee to checkout for a gateway ID
     * @how-to        Get CustomizeWoo.com FREE
     * @author        Rodolfo Melogli
     * @testedwith    WooCommerce 3.7
     * @community     https://businessbloomer.com/club/
     */
      
    // Part 1: assign fee
      
    add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
      
    function bbloomer_add_checkout_fee_for_gateway() {
        $chosen_gateway = WC()->session->get( 'chosen_payment_method' );
         if ( $chosen_gateway == 'Saferpay_creditcard'||'Twint_creditcard' ) {
          WC()->cart->add_fee( 'Saferpay Fee', $amount * 0.0195 );
       }
    }
      
    // Part 2: reload checkout on payment gateway change
      
    add_action( 'woocommerce_review_order_before_payment', 'bbloomer_refresh_checkout_on_payment_methods_change' );
      
    function bbloomer_refresh_checkout_on_payment_methods_change(){
        ?>
        <script type="text/javascript">
            (function($){
                $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
                    $('body').trigger('update_checkout');
                });
            })(jQuery);
        </script>
        <?php
    }
    
    1. Mystery Solved! It worked.

      // * @snippet       WooCommerce Add fee to checkout for a gateway ID
      // * @how-to        Get CustomizeWoo.com FREE
      // * @author        Rodolfo Melogli
      // * @testedwith    WooCommerce 3.7
      // * @community     https://businessbloomer.com/club/
      
         
      // Part 1: assign fee
         
      add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
      function bbloomer_add_checkout_fee_for_gateway() {
          $amount = WC()->cart->cart_contents_total;
       
          $chosen_gateway = WC()->session->get( 'chosen_payment_method' );
           if ( $chosen_gateway == 'Paypal' ) {
            WC()->cart->add_fee( 'Paypal fee', $amount * 0.0195 );
         }
      }  
      
      
      // Part 2: reload checkout on payment gateway change
         
      add_action( 'woocommerce_review_order_before_payment', 'bbloomer_refresh_checkout_on_payment_methods_change' );
         
      function bbloomer_refresh_checkout_on_payment_methods_change(){
          ?>
          <script type="text/javascript">
              (function($){
                  $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
                      $('body').trigger('update_checkout');
                  });
              })(jQuery);
          </script>
          <?php
      }
      
  7. Hi Rodolfo,
    i tried Snippet #1 – works perfectly
    tried Snippet #2 – doesnt work ๐Ÿ™
    Theme: Vantage

    1. Hi Serg, did you change anything in the snippet?

  8. Rodolfo you need to put a disclaimer because that practice is not legal in Europe and Italy. In rest of the world is legally.

    1. Ehm, it’s in the second paragraph of this same article already ๐Ÿ˜€

      1. That is not true. You can add a reasonable fee for Klarna, Paypal and a few others. Not for Credit cards. And the fee cannot exceed the actual costs.

        1. Well, I guess all plane companies do that for example, so there must be a way to go around the rules. But the rules clearly state (at least for PayPal), that you can’t charge fees:

          You agree that you will not impose a surcharge or any other fee for accepting PayPal as a payment method. You may charge a handling fee in connection with the sale of goods or services as long as the handling fee does not operate as a surcharge and is not higher than the handling fee you charge for non-PayPal transactions.

  9. Hello,
    I have a delivery fee based on the payment method (COD and CARD), which i’ve added using this plugin: “Payment Gateway Based Fees and Discounts for WooCommerce “, but if the client buys over 300 in total cart i want to remove this fees and delivery to them freely.

    So after a quick inspect i saw that the plugin insert the tax with the class of “fee” so i’ve tried to edit the snippet to remove all fees when the total in cart is over 300. I’ve added it into the child theme in function.php but nothing happens.

    This is the code:

    // Part 1: assign fee
      
    add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
      
    function bbloomer_add_checkout_fee_for_gateway() {
        $chosen_gateway = WC()->session->get( 'chosen_payment_method' );
         if ( $chosen_gateway == 'cod' && $woocommerce->cart->total > 300  ) {
           WC()->cart->remove_all_fees();
       }
    }
      
    // Part 2: reload checkout on payment gateway change
      
    add_action( 'woocommerce_review_order_before_payment', 'bbloomer_refresh_checkout_on_payment_methods_change' );
      
    function bbloomer_refresh_checkout_on_payment_methods_change(){
        ?>
        <script type="text/javascript">
            (function($){
                $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
                    $('body').trigger('update_checkout');
                });
            })(jQuery);
        </script>
        <?php
    }

    Any ideas where i was wrong ?:D

    Thanks.

    1. Hi Fildiroi, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  10. Thanks for all the great snippets!

    The majority works great, and usually the easiest and most straight forward solution available.

    You really make woocommerce better by a lot!

    Thanks again for everything!!!

    1. Thanks! Which one didn’t work great?

  11. Hi there,
    thanks for sharing it with us.

    I should add 5โ‚ฌ extra as fee for Cod payment, I’ve got Envo Shop Pro theme.

    Does it suit with this code? What should pu instead of Paypal?

    1. Enter ‘cod’ instead of ‘paypal’

  12. Thank you!

    If you want to take a fee of 5% of the cart’s total, use this:

    function bbloomer_add_checkout_fee_for_gateway() {
        $amount = WC()-&gt;cart-&gt;cart_contents_total;
    
        $chosen_gateway = WC()-&gt;session-&gt;get( 'chosen_payment_method' );
         if ( $chosen_gateway == 'paypal' ) {
          WC()-&gt;cart-&gt;add_fee( 'ืขืžืœืช PayPal', $amount * 0.05 );
       }
    }
    
    1. Thanks

  13. Hello Rodolfo,

    Thank you very much for your outstanding work.

    I use your code, but I would need to exclude the charge on some products, example :

    – Product A: $20
    – Product B: $35
    – Product C: $40

    Total: $95

    I would like to exclude product A in the fee calculation, so I would like the fee to apply only on product B and C, i.e. on $75 and not $95.

    Is this possible?

    I use a translator, sorry if I am misunderstood.

    Thank you very much and good to you.

    1. Hi Nico, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  14. really thank you for sharing knowledge

    i add the code to function php, but it show the fee in each currency with the same amount

    i use wocomeerce multilangula to change the currency based on location and according to conversion rate

    but at current time, it show 5 USD, 5 SAR, 5 EGP, 5 EUR ….etc

    1. Hi Mohamed, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  15. Hi,
    Nice your artical!!!!
    I want to ask one question, When select cash on delivery option on checkout page this function should be remove. Because We want to apply processing fee when user pay payment by paypal or other payment gateway. We do not want add processing fees on cash on delivery method. How To help me,

    1. Hi Satyam, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  16. Any idea where I can find the right ID from other gateways to fill in this part of the code?
    if ( $chosen_gateway == ‘paypal’ ) {

    1. Already find out by looking into the Chrome inspector. Other question, how can I add the fee to the second payment method?
      Thanks for the help.

      1. Exactly, there was a helpful screenshot here: https://www.businessbloomer.com/disable-payment-gateway-specific-country-woocommerce/

        For the second method, just add another “if { }” statement to the same function

        1. Hello Rodolfo,

          Can your explain where I have to add the โ€œif { }โ€ statement in the code of part 1? I just added it (see code below) to the code but then I got an error.

          /**
           * @snippet       WooCommerce Add fee to checkout for a gateway ID
           * @how-to        Get CustomizeWoo.com FREE
           * @author        Rodolfo Melogli
           * @testedwith    WooCommerce 3.7
           * @community     https://businessbloomer.com/club/
           */
            
          // Part 1: assign fee PayPal
            
          add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
            
          function bbloomer_add_checkout_fee_for_gateway() {
              $chosen_gateway = WC()->session->get( 'chosen_payment_method' );
               if ( $chosen_gateway == 'mollie_wc_gateway_creditcard' ) {
                WC()->cart->add_fee( 'Creditcard cost', 2,25 );
             }
          }
            
          
          function bbloomer_add_checkout_fee_for_gateway() {
              $chosen_gateway = WC()->session->get( 'chosen_payment_method' );
               if ( $chosen_gateway == 'paypal' ) {
                WC()->cart->add_fee( 'Paypal', 2,25 );
             }
          } 
            
          add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
          
          1. e.g.

            if ( $chosen_gateway == 'mollie_wc_gateway_creditcard' ) {
               WC()->cart->add_fee( 'Creditcard cost', 2,25 );
            } elseif ( $chosen_gateway == 'WHATEVER' ) {
               WC()->cart->add_fee( 'WHATEVER cost', 6 );
            }
            
            1. Hello Rodolfo, somehow I got en error again when I change the code with the example, I tried several payment method names, but they all gave me an error. Any idea?

              // Part 1: assign fee PayPal
                
              add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
                
              function bbloomer_add_checkout_fee_for_gateway() {
                  $chosen_gateway = WC()->session->get( 'chosen_payment_method' );
                   if ( $chosen_gateway == 'mollie_wc_gateway_creditcard' ) {
                    WC()->cart->add_fee( 'Creditcard kosten', 2,25 );
                    } elseif ( $chosen_gateway == 'paypal' ) {
                       WC()->cart->add_fee( 'Paypal kosten', 6 );
                    }
              
              1. What error do you get? There is a missing “}” to close the function for example

  17. Thanks !!

    1. Welcome!

  18. Hi Rodolfo,

    Do you have a solution as follows:

    Add a gateway fee (percentage) for a specific gateway (credit card) for a specific user role (wholesaler)?

    Regards,

    Michael

    1. This is what I need. Did you find a solution Michael?

  19. Thanks for the snippet and this awesome site.

    I’m experiencing something weird though… your code works, but I’m using it inside a payment gateway class and when I try to use it inside the payment gateway class it shows while the cart updates and after the site finishes loading it is removed!

    I need to do it there because i’m getting the fee from the plugins settings :/

     
    // constructor function
    // ...
    // Set custom fees
    		add_action( 'woocommerce_cart_calculate_fees', array( $this, 'pagalo_add_fee' ) );
    }
    
    /**
    	 * Adds the fee based on selected cuotas.
    	 */
    	public function pagalo_add_fee() {
    
    		WC()->cart->add_fee( 'Fee2', 53 );
    
    		return; 
    	}
    
    
    1. Hi Hounw, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  20. Hi,

    The snippet works, but I am wondering if it’s possible to make the fees VAT-taxable.
    We enter our prices including VAT.

    Thanks.

    Best regards,
    Jonas

    1. Hi Jonas, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  21. Hello, Thank you for sharing the code!

    It works fine for me BUT I didn’t receive any payment on paypal. (that’s no good ๐Ÿ™‚ ) I checked the logs, nothing went through and It didn’t give me any hint on why.

    I’m suspecting that’s because of the Terms.

    Your post specifically says adding checkout fees is currently against their Terms of Service. And I’m sure you’re right, however after spending a long time reading those terms, I cannot find anything on this topic. Would you be able to share a link/source from paypal? Their support is un-reachable (du to the current covid19 situation).

    Hope this message will reach you!

    1. No, the surcharge won’t stop your website from functioning, so you’ve got another problem. It could be anything. To troubleshoot, disable all plugins but WooCommerce and also switch temporarily to “2020” theme (load the snippet there in functions.php) – does it work? If yes, you have a problem with your current theme or one of the plugins.

      For the PayPal User Agreement, you find it here: https://www.paypal.com/us/webapps/mpp/ua/useragreement-full, and it says:

      You agree that you will not impose a surcharge or any other fee for accepting PayPal as a payment method. You may charge a handling fee in connection with the sale of goods or services as long as the handling fee does not operate as a surcharge and is not higher than the handling fee you charge for non-PayPal transactions.

  22. Hello,

    Doesn’t work on Woocommerce 4.0 (for all payments) – nothing shows.

    1. Sorry, I just tried snippet #1 and it works perfectly

      1. Still works perfectly with 4.7+. Probably the commenter has some plugin active, which interferes. This can be virtually ANYTHING – even if you dont use it, and its just active, plugins can and WILL garble up your system :-/

        Had that happening to me with a custom shipping plugin (not written by me, but a colleague) and a “premium” plugin for adding additional custom fields to the product. It was just active, no custom fields added or anything, but was upsetting / jumbling up the shipping calculation all the time. Even worse, it did take us 2 weeks until we got to the point to figure this out (why would a plugin, that is not in use AT ALL, but active, do anything to that calculation process ..? yeah well, now we know).

        cu, w0lf.

  23. Hello Rodolfo,
    Thanks for sharing this great post. I have a problem about this script.
    Checkout does not update. I tried for cod payment method. If customers complete checkout with cod payment method, they can see extra fee on order mail. But it doesn’t update checkout on payment method changes.
    I have a code in fucntions.php as below
    function child_enqueue_styles() {
    wp_dequeue_script( ‘wc-checkout’ );
    }
    add_action( ‘wp_enqueue_scripts’, ‘child_enqueue_styles’, 1000 );
    Probably this code prevents update. Am I right ? But I have to use this code. Can you suggest any other way ?

    1. If you disable that code, does it work? If yes, then you must re-enable it.

  24. Hello

    I am looking for Fixed Amount + Percentage Of Total for PayPal fee

    Do you have that code?

    Waiting for reply

    1. Hi Fakhrul, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  25. Hello there, Rodolfo,

    thank you for your hard work throughout your blog. It has helped me many times, so kudos!

    I wanted to ask – does this solution support multiple currencies? As I have implemented it (both with your code snippet and before that with plugin) and I am getting the same currency for both CZK and EUR currencies, which is indeed a problem. ๐Ÿ™‚

    I am using https://cs.wordpress.org/plugins/woocommerce-currency-switcher/ if that makes any difference – should be fine multi-currency plugin.

    Thank you very much in advance and keep up the splendid work!
    Mirek

    1. Hi Mirek, you would need to modify the snippet in order to change the “amount” based on currency conversion. So, yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

      1. Hello there, Rodolfo, I totally understand (and as a freelancer, too, I agree), but my client has closed his budget on this project. So I will have to figure this out (should not be that hard) myself. However, thank you for your answer and awesome blog!

        1. No problem!

  26. Hi,

    Does this PHP Snippet #2 work for Cash on Delivery option at the latest version of WooCommerce (3.8.0)?

    Thank you in advance!

    1. It should, yes. Let me know

  27. Thank you so much found exactly what I was looking for.

    Thank you so much again

    1. Great!

  28. Howdy Rodolfo.

    Thanks for all of your amazing work with your site – just brilliant.

    It would appear that with the latest update of WooCommerce and perhaps my Square plugin, that this is no longer working – I did have a percentage fee only for credit card payments with Square previously, but since the updates, they no longer appear on the site.

    Code was and still is in the child theme functions php file, so I’m not sure what has occurred.

    Cheers,
    Phil.

    1. Snippet updated just today – give it a go

  29. Hi Rodolfo,

    Thank you for your Snippet.

    Since the update Woocommerce 3.7 the snippet no longer works. The cart isn’t updated if I choose another payment gateway. (Error : Can’t find variable: jQuery)

    Regards.

    1. Hey Connor, thanks for your comment! I just tested this again with Storefront theme and it works perfectly. Maybe your theme (or another plugin) is messing/conflicting with my snippet?

      To troubleshoot, disable all plugins but WooCommerce and also switch temporarily to “Twentyseventeen” theme (load the snippet there in functions.php) – does it work? If yes, you have a problem with your current theme or one of the plugins.

      Hope this helps!

      R

  30. This is fantastic. The only thing I can’t figure out is what to I set the “Chosen_Gateway” to if I want to apply a fee when using Square. Can you help?

    1. Hello Matthew, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  31. Nice post, but how can i add a fix feed only if the total cart amount is under 50 euros?

    1. Hello Florian, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  32. Hi,

    Great snippet!
    How can i add the ‘fee’ outcome on the invoice?

    Thanks in advance.

    Regards,
    David

    1. Hi David, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  33. Even though not documented at https://docs.woocommerce.com/document/add-a-surcharge-to-cart-and-checkout-uses-fees-api/ it turns out WooCommerce passes the cart into the woocommerce_cart_calculate_fees function as a parameter. Hence, you could do something like this:

    function add_checkout_fee_for_paypal($cart)
    {
        global $woocommerce;
    
        if (is_admin() &amp;&amp; !defined('DOING_AJAX')) {
            return;
        }
    
        $chosen_gateway = $woocommerce-&gt;session-&gt;chosen_payment_method;
    
        // it's either 'paypal' or 'ppec_paypal' for PayPal Express Checkout
        if (strpos($chosen_gateway, 'paypal') !== false) {
            $percentage = 0.029;
            $surcharge = (($cart-&gt;cart_contents_total + $cart-&gt;shipping_total) * $percentage) + 0.30;
            // 'Fee' is the GUI label
            $cart-&gt;add_fee(__('Fee', 'woocommerce'), $surcharge);
        }
    }
    
    1. Nice!

    2. This worked great after changing the HTML codes (& and >) to the appropriate symbols! Thanks!

  34. For the PHP Snippet #1, how can I make it optional? I mean the customer can choose to tick a checkbox to add on the additional fee.

    1. Hi Wilfred, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  35. Hi,

    I have added the above snippet for COD method and it was working fine but the tax amount is not updating when the cart amount gets updated.

    For Example if my cart amount is 103 inclusive of 3% tax.

    Then when I add Rs 50 for COD method

    the cart amount goes to 153 but the tax amount is still Rs 3. Any solution for this?

    1. Hello Toukir, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  36. Hello,
    Thanks for the snippet… Wondering how I can make it that it charged per item?

    Any idea how…

    Cheers

    1. Hey Juanito, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  37. Hi, thanks a lot for your awesome work and snippets! Works fine on my test website, on which i’ve added the Coinbase plugin to let customers pay by crypto (and adding a handling fee of USD2 in that case). Any easy way to add the fee based on a % of the basket?

    Best

    1. Hey Topraf, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  38. Hi Rodolfo.
    I tried your snippet, but I encountered an issue.
    Say that you have two shipping method, free_shipping and local_pickup.
    If I choose COD payment method, ok your snippet add a fee correctly. But if I switch from free_shipping to local_pickup… well, there’s no way to update cart by removing unwanted additional fee.
    Do you think there is a way to clear it?

    1. Hey Alessandro – thanks so much for your comment! Well, this snippet applies a fee when you switch payment methods, not when you change shipping rates – it will need to be customized accordingly ๐Ÿ™‚

  39. Hi Rodolfo,
    The second snippet for a specific payment gateway isn’t working. The cart isn’t updated if I choose another payment gateway. Is it because the payment gateways are after the cart?

    I found this and it works for me. The cart is updated when I choose a different payment gateway. Is this the right way to do it or…. ?

    function woocommerce_custom_fee( ) {
     
    	if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
    		return;
     
    	$chosen_gateway = WC()->session->chosen_payment_method;
    	$fee = 2;
    
    	if ( $chosen_gateway == 'cheque' ) { //test with paypal method
    		WC()->cart->add_fee( '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 );
    

    Kind regards!

    1. Hey Mieke, thanks for your comment. You’re totally right, so I revised my snippet and from now on you should use the latest version ๐Ÿ™‚

  40. Hello. When I select a certain country and choose COD where the fee is set, it is correctly showed in cart.
    Then, when I change a country for which isn’t available COD and so the default method (card payment) is automatically set, the fee for COD still stays in cart, although it isn’t calculated in total price when I try to pay. Don’t you know why? Thanks

    1. Hey Rad, thanks for your comment! You might need to “Ajaxify” the snippet in order to refresh the checkout fees when the country is selected. Unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  41. Sharing this with anyone who needs it.

    This is a customised code for those who are using PayPal Express Checkout.

    To know the gateway code, on checkout simply right on the payment gateway, click Inspect (Chrome) and
    just get whatever it is after the _method then edit: if ( $chosen_gateway == ‘CODE HERE’ )

    Hope this helps ๐Ÿ™‚

    
    add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
     
    function bbloomer_add_checkout_fee_for_gateway() {
      
      global $woocommerce;
      
      $chosen_gateway = $woocommerce->session->chosen_payment_method;
       
      if ( $chosen_gateway == 'ppec_paypal' ) {
       
       
        $percentage = 0.05;
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;    
      $woocommerce->cart->add_fee( 'PayPal Fee', $surcharge, true, '');
      
      }
      
    }
    
    
    1. Very nice, thanks a lot ๐Ÿ™‚

      1. Very nice!

        I changed it slightly so that you can set it for a specific user role.

        Any idea how to set it for two users?

         
        // Assign Credit Card Gateway Percentage Fee
        
        add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
          
        function bbloomer_add_checkout_fee_for_gateway() {
        	if ( ! current_user_can('default_wholesaler'))
        	return;
          
          global $woocommerce;
          
          $chosen_gateway = $woocommerce->session->chosen_payment_method;
           
          if ( $chosen_gateway == 'cardgatecreditcard' ) {
              
            $percentage = 0.085;
            $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;   
          $woocommerce->cart->add_fee( 'Credit Card Fee (8.5%)', $surcharge, true, '');
          
          }
          
        }
        
        1. Well done! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

    2. ppec_paypal is not wroking with PayPal Express Checkout for WooCommerce developed by wpgateways . Any Idea ?

  42. Hi Rodolfo, thank you so much for sharing great snippets with us. I have been following your blog for a while and perhaps cut-copy-paste some of them in my work ๐Ÿ˜›

    So I wrote a piece of code which adds a custom fee depending on the distance between seller’s & buyer’s locations. It was working great until woocommerce 3.1.2. Once I have update to 3.2.1 or 3.2.4, it’s no longer adding any fee.

    Here’s the code: (only if you have time)

    Just tell me if I did anything wrong or its the latest update that causes the code not working.
    Thank you very much for your time.

    1. Mahdy, thanks so much for your comment! Unfortunately this is custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R

  43. Hi
    Great snippets, great work!
    I am trying to find a way to hide a shipping method in the cart, when a flat rate postcode has been input’d by the user.
    For a Guest shopper they are shown a flat rate shipping fee.
    I have set up postcodes in the flat rate method.
    Once the matching postcode is entered the new rate appears.
    However the original cheaper rate still shows and is selectable.
    It is this cheaper rate I need to remove.

    If its not possible to unset this other rate on postcode entry, could I add a fee and take that to the checkout?
    I hope this is not too confusing and that you may be able to point me in the right direction.
    Cheers
    Andy

    1. Andy, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  44. Hello there,

    I cant seem to get the snippet working with a theme I’ve purchased. When I add the code into my functions.php it just kills the site – with a 500 error.

    Any chance I could give you access to a clone of my site and you could adjust it?

    1. Hello Ray! I just added the code to my test website and it doesn’t give error – try again ๐Ÿ™‚ Unfortunately I can’t offer free support to blog readers, thanks for your understanding!

  45. hi there,
    THANK YOU FOR YOUR BLOG, it really helped me!
    I want to share a snippet to add a custom fee based on percentage. Check this out

     add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_add_checkout_fee_for_gateway' );
    
    
    function bbloomer_add_checkout_fee_for_gateway() {
     
      global $woocommerce;
     
      $chosen_gateway = $woocommerce->session->chosen_payment_method;
      
      if ( $chosen_gateway == 'paypal' ) {
      
      
     	$percentage = 0.02;
     	$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;	
      $woocommerce->cart->add_fee( 'Commissioni', $surcharge, true, '');
     
      }
     
    } 
    1. Awesome, thank you so much Luca! Much appreciated ๐Ÿ™‚

    2. Hello,
      Thank you very much for your code.

      I am looking to add the commission for payment with paypal.
      However, in paypal they charge fixed commission of 0.34 โ‚ฌ + percentage.
      So, how can I add that fixed commission too?

      1. Nerea, adding extra commission for PayPal payments is against their terms.

    3. I would like to add 2 payment gateways here .. What would be sytanx ?

      $chosen_gateway == ‘PG1’ or ‘PG2’

      is not working .
      Pl help. thanks

  46. Hello,
    congratulations for the site !! I’ve had so many great ideas.
    I write because I am improving the site for my small farmhouse.
    After the guest has chosen the days of stay and goes in the cart I need to be added automatically the cost for final cleaning that is always fixed euro 50 for all apartments.
    Do you think I can use this here?
    Thank you

    1. Ciao Silvia, thanks so much for your comment! Of course you can use this snippet, and you can even rename the fee into “Pulizia Finale” ๐Ÿ™‚ Let me know!

  47. Hi,

    This is a nice snippet. But it would be even nicer if there was a way to only add a fee to a selected payment.

    For example: payment type paypal is 5 dollar fee. But if you choose another payment types, there is no fee. I hope we will see such snippet from you. Thanks!

    Regards,
    Jake

    1. Hey Jake, thanks for your comment! I added a possible solution to the blog, only thing is that it doesn’t update if you switch payment but ony when you change something in the checkout fields ๐Ÿ™‚ Let me know!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

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