How to Add Custom Fee / Transaction Fee in WooCommerce?

I am using WooCommerce in my website. When customers make payments using payment gateways like PayPal or Stripe, these payment companies charge a transaction fee. I want to include this fee in the total cart price displayed on the checkout page. I want customers to see the total amount they need to pay, including the transaction fee, before making the payment. Can someone guide me on how to achieve this?

You can use woocommerce_cart_calculate_fees hook and WC()->cart->add_fee() to add custom fee to the checkout page. Here is few example.

1. Adding a Fixed Fee:

add_action('woocommerce_cart_calculate_fees', function() {
	if (is_admin() && !defined('DOING_AJAX')) {
		return;
	}
	WC()->cart->add_fee(__('A small fee', 'txtdomain'), 5);
});

2. Adding a Percentage-based Fee:

add_action('woocommerce_cart_calculate_fees', function() {
	if (is_admin() && !defined('DOING_AJAX')) {
		return;
	}
	
	$percentage = 0.05;  // 5% fee
	$percentage_fee = (WC()->cart->get_cart_contents_total() + WC()->cart->get_shipping_total()) * $percentage;
 
	WC()->cart->add_fee(__('A small fee', 'txtdomain'), $percentage_fee);
});

3. Adding a fee based on cart totals:

add_action('woocommerce_cart_calculate_fees', function() {
	if (is_admin() && !defined('DOING_AJAX')) {
		return;
	}
 
	$cart_total = WC()->cart->get_cart_contents_total();
	if ($cart_total < 500) {
		WC()->cart->add_fee(__('Fee for small transactions', 'txtdomain'), 50);
	}
});

4. Adding a fee based on shipping location:

add_action('woocommerce_cart_calculate_fees', function() {
	if (is_admin() && !defined('DOING_AJAX')) {
		return;
	}
 
	$shipping_country = WC()->customer->get_shipping_country();	
	if ($shipping_country == 'NO') {
		WC()->cart->add_fee(__('Fee for shipping to Norway', 'txtdomain'), 50);
	}
});

5. Adding a fee based on chosen shipping method:

add_action('woocommerce_cart_calculate_fees', function() {
	if (is_admin() && !defined('DOING_AJAX')) {
		return;
	}
 
	$chosen_shipping_method = WC()->session->get('chosen_shipping_methods');
 
	if (strpos($chosen_shipping_method[0], 'flat_rate') !== false) {
		WC()->cart->add_fee(__('Fee for flat rate shipping', 'txtdomain'), 50);
	}
});

6. Adding a fee based on chosen payment method:

add_action('woocommerce_cart_calculate_fees', function() {
	if (is_admin() && !defined('DOING_AJAX')) {
		return;
	}
 
	$chosen_payment_method = WC()->session->get('chosen_payment_method');
	if ($chosen_payment_method == 'paypal') {
		WC()->cart->add_fee(__('Paypal Fee', 'txtdomain'), 50);
	}
});

add_action('woocommerce_review_order_before_payment', function() {
    ?><script type="text/javascript">
        (function($){
            $('form.checkout').on('change', 'input[name^="payment_method"]', function() {
                $('body').trigger('update_checkout');
            });
        })(jQuery);
    </script><?php
});

Use the code based on your need.