在Woocommerce中为特定支付网关添加自定义费用

如何在选择付款(信用卡)时为总金额添加百分比?

例如:如果客户支付货到付款,那么基本价格,如果我选择在线支付,那么我收取的百分比会加到总金额中吗?

交付时的现金支付的网关ID列出:用于在线支付的cod网关ID列出: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)

2 years ago

尝试以下重新访问的代码,而不是应该做的伎俩:

// 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
}

代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .