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

Posted

技术标签:

【中文标题】在 Woocommerce 中为特定支付网关添加自定义费用【英文标题】:Add a custom fee for a specific payment gateway in Woocommerce 【发布时间】:2018-11-15 03:07:18 【问题描述】:

在选择付款方式(信用卡)时,如何在总金额中添加一个百分比?

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

货到付款的网关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】:

尝试以下重新访问的代码,它应该可以解决问题:

// 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 文件中。经过测试并且可以工作。

【讨论】:

谢谢!帮助并获得!上帝保佑你!

以上是关于在 Woocommerce 中为特定支付网关添加自定义费用的主要内容,如果未能解决你的问题,请参考以下文章

如何在 WooCommerce 中为未登录用户禁用特定插件?

根据支付网关和国家/地区对 WooCommerce 自定义费用征税

在 WooCommerce 中为特定产品类别自定义“添加到购物车”按钮

在 WooCommerce 中更改特定的支付网关标题

如何在 woocommerce 上制作特定的支付网关以免费送货

添加一个复选框作为禁用支付网关的 WooCommerce 管理产品选项