Sharing solution for payment method depended fee

Hey all,

Not sure if this is the best place to post this but wanted to share a solution I found for a payment type depended user fee.

I like users to choose the local payment methods, but credit card payments can be pretty costly as they charge a % + a fixed fee. I want to users to have the option, but pay it themselves, something you see a lot on web shops.

Below a snippet that takes a % of the total price.

/**
 * Add fee to bank transfer payment method
 */
add_action( 'woocommerce_cart_calculate_fees', function() {
	if ( is_admin() ) {
		return;
	}
	$payment_method = WC()->session->get( 'chosen_payment_method' );


	// Change bacs to another payment method ID where necessary
	if ( $payment_method === 'stripe' ) {
		$amount = WC()->session->get('cart_totals')['total'] * 0.1 ; // How much the fee should be
		$tax = ''; // empty value equals to Standard tax rate
		$title = 'Creditcard fee';
	
		WC()->cart->add_fee( $title, floatval( $amount ), true, $tax );
	}
}, 10, 0 );

/**
 * By default WooCommerce doesn't update checkout when changing payment
 * method so we need to trigger update here
 */
add_action( 'wp_head', function() {
?>
	<script type="text/javascript">
		jQuery(document).ready(function($) {
			/**
			 * Trigger checkout update when changing payment method
			 */
			$( document.body ).on( 'change', 'input[name="payment_method"]', function() {
				$( document.body ).trigger( 'update_checkout' );
			} );
		});
	</script>
<?php
}, 10, 0 );
1 Like

Thanks for sharing!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.