Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

php - Add a custom fee for a specific payment gateway in Woocommerce

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...