3
votes

How can I add a percentage to the total amount when choosing a payment (credit card)?

For example: If the customer pays for cash on delivery, then the base price, and if I chose online payment, then the percentage charged by me is added to the total amount?

Gateway ID for cash payment on delivery is set out: cod Gateway ID for online payment is set out: tinkoff

add_action( 'woocommerce_after_calculate_totals', 'custom_fee_for_tinkoff' );

function custom_fee_for_tinkoff( $cart ) {

 if ( is_checkout() || defined('WOOCOMMERCE_CHECKOUT') ) {

  $payment_method = WC()->session->get( 'chosen_payment_method' );

   if ($payment_method == 'tinkoff') {
    $percentage = 0.025;
    $surcharge = ( $cart->cart_contents_total + $cart->tax_total ) * $percentage;

    $cart->add_fee( 'Комиссия банка', $surcharge, true, '' );
  }
   else { return; }
 }
}

Image with problem

1

1 Answers

4
votes

Try the following revisited code instead that should do the trick:

// Add a custom fee based o cart subtotal
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_for_tinkoff', 20, 1 );
function custom_fee_for_tinkoff ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page

    $payment_method = WC()->session->get( 'chosen_payment_method' );

    if ( 'tinkoff' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.025;
        $cart->add_fee( 'Комиссия банка', $surcharge, true );
    }
}

// jQuery - Update checkout on methode payment change  
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('form.checkout').on('change', 'input[name="payment_method"]', function(){
            $(document.body).trigger('update_checkout');
        });
    });
    </script>
    <?php
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.