Knowledge Base

Hi, How can we help?

Add extra fee on payment gateway selection

This document explains how you can add an extra fee to the payment gateway selection.

For this, first, you need to enable deposit on the checkout page.
Go to Dashboard-> Deposits-> General Settings.

Then add the following code to your theme/child-theme functions.php file.

add_action('woocommerce_cart_calculate_fees', 'wpsh_add_handling_fee');
function wpsh_add_handling_fee($cart)
{
   if (is_admin() && !defined('DOING_AJAX')) return;

   $chosen_payment_id = WC()->session->get('chosen_payment_method');
   if (empty($chosen_payment_id)) return;

   $subtotal = $cart->subtotal;

   // Here you can set up your fees (fixed or percentage)
   $targeted_payment_ids = array(
      'cod' => 2, // Fixed fee
      'cheque' => 2.6 * $subtotal / 100, // Percentage fee
      'ppcp-gateway' => 2.9 * $subtotal / 100, // Percentage fee
   );
   
   // Loop through defined payment Ids array
   foreach ($targeted_payment_ids as $payment_id => $fee_cost) {
      if ($chosen_payment_id === $payment_id) {
         $cart->add_fee(__('Handling fee', 'woocommerce'), $fee_cost, true);
      }
   }
}

// Update checkout on payment method change
add_action('woocommerce_checkout_init', 'wpsh_refresh_checkout_page');
function wpsh_refresh_checkout_page()
{
   wc_enqueue_js("jQuery( function($){
                     $('form.checkout').on('change', 'input[name=payment_method]', function(){
                        $(document.body).trigger('update_checkout');
                     });
                  });");
}

This sample code will work on the checkout page. It adds an extra value to each payment method specified in the code. You can use or modify the above code snippet with other payment method parameters also.
‘cod’ => 2 is a fixed fee for cash on delivery. You can change the value to your desired value. Similarly, you can add your payment methods and their value other than what we added in our code as your needs.

There is a text Handling fee which will be shown as a label when adding an extra fee to the payment gateway. You can edit this text in this code if you need.

Below is an example of the execution of the above code. First, add products to the cart. You can see the payment methods in checkout. If you have selected the payment method cod, you can see a handling fee of 2(as we give in the code).

If you have selected check payments, then the handling fee will be changed.

Customer Support

If you have questions about our plugin(s), are experiencing issues with any of our plugin