允许WooCommerce Gateway百分比费用也适用于订单付款

问题描述

我使用这个代码段已经有一段时间了,直到我发现客户可以用信用卡付款而不收取费用为止。他们设法通过“订单付款”页面付款。

谁能告诉我为什么我的代码在订单付款页面上不起作用?在结帐页面上可以正常工作。

// Assign Credit Card Gateway Percentage Fee to Wholesaler Profiles

add_action('woocommerce_cart_calculate_fees','sm_credit_card_fee_role_gateway',10,1);
function sm_credit_card_fee_role_gateway($cart){
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    if (!(is_checkout() && !is_wc_endpoint_url()))
        return;

    if (!is_user_logged_in())
        return;

    $user = wp_get_current_user();
    $roles = (array) $user->roles;
    $roles_to_check = array('administrator','default_wholesaler','wholesaler-non-vat-registered','shop_manager');
    $compare = array_diff($roles,$roles_to_check);

    if (empty($compare)){
        $payment_method = WC()->session->get('chosen_payment_method');
        if ($payment_method == 'cardgatecreditcard'){
            $percentage = 0.085;
            $surcharge = (WC()->cart->cart_contents_total + WC()->cart->shipping_total) * $percentage;
            $cart->add_fee( 'Credit Card Fee (8.5%)',$surcharge,true );
        }
    }
}

解决方法

要使您的代码在订单付款中有效,您可以替换代码:

if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
    return;

作者:

if ( ! ( is_checkout() && ! is_wc_endpoint_url('order-received') ) )
    return;

现在,您的功能代码也将在WooCommerce 订单付款端点上执行...

但是在订单付款端点中,数据被保存到现有订单中,因此在将订单放入结帐时已为此订单保存了费用。挂钩woocommerce_cart_calculate_fees仅影响购物车对象,并且对Order Pay端点中的现有订单没有任何影响

您将不得不重新构建专门针对Order Pay(涉及到Ajax)的复杂得多的东西,以便能够删除或添加现有订单中的自定义费用,从而刷新总额……