在 ajax 请求后更新购物车总数

Updating cart totals after ajax request

这是我自定义的 ajax 请求回调。

我将一些数据与 wp_remote_post 一起使用,并获得了关于我自己的 woocommerce 支付网关分期付款的 json 结果。

/**
 * Check avaliblity for installments via WordPress Ajax
 *
 * @return void
 */
function check_installment() {

    if ( isset($_REQUEST) ) {

        $action = data_get($_REQUEST, 'action');
        if($action == 'check_installment')
        {

            $cart_data = WC()->session->get('cart_totals');  
            $binNumber = data_get($_REQUEST, 'bin');

            if(!$binNumber)
            {
                return;
            }
            
            $_initGateway = new Woo_Ipara_Gateway();
            $_initGateway = $_initGateway->checkInstallment($binNumber);
            $data = [
                'cardFamilyName' => data_get($_initGateway, 'cardFamilyName'),
                'supportedInstallments' => data_get($_initGateway, 'supportedInstallments')
            ];
            echo json_encode(getInstallmentComissions(data_get($_initGateway, 'cardFamilyName')));  
            
        }
    
    } 
    die();
}
add_action( 'wp_ajax_check_installment', 'check_installment');
add_action( 'wp_ajax_nopriv_check_installment', 'check_installment');

目前,支付提供商对特定信用卡有不同的佣金。所以这意味着,当用户选择分期付款值时,我想在此请求后更改订单总额。

我也找到了一些过滤器,关于计算总计 woocommerce_calculated_total,但是如何触发这个,在 ajax 请求和用户之后,选择分期付款选项?


add_filter( 'woocommerce_calculated_total', 'custom_calculated_total', 10, 2 );
function custom_calculated_total( $total, $cart ){
    // some magic.
}

有什么帮助吗?谢谢。

首先,过滤方法不对,我想试试woocommerce_calculated_total

一定是,woocommerce_checkout_order_processed

另一个问题是,WC()->cart->add_fee( "text", $fee, false, '' ); 没有真正正常工作。

您应该直接在操作中使用 new WC_Order_Item_Fee() class。

这是我的部分代码;

add_action('woocommerce_checkout_order_processed', 'addFeesBeforePayment', 10, 3);
function addFeesBeforePayment( $order_id, $posted_data, $order ) {

    // some logic about bin verification and remote fetch about installment comissions. 
     
    $cartTotal = WC()->cart->cart_contents_total;
 
    $newCartTotal = $cartTotal + ( $cartTotal * $defaultComission / 100 ); 
    $installmentFee = $cartTotal * ($defaultComission / 100 );   

    $item_fee = new WC_Order_Item_Fee();

    $item_fee->set_name( 'Kredi Kartı Komisyonu ('.$defaultInstallment.' Taksit)' ); // Generic fee name
    $item_fee->set_amount( $installmentFee ); // Fee amount
    $item_fee->set_tax_class( '' ); // default for ''
    $item_fee->set_tax_status( 'none' ); // or 'none'
    $item_fee->set_total( $installmentFee ); // Fee amount 
    $order->add_item( $item_fee ); 
    $order->calculate_totals(); 

    $order->add_order_note( 'Bu sipariş için ödeme '. $defaultInstallment . ' taksit seçeneği seçilerek oluşturuldu. Toplam taksit komisyonu, sipariş tutarına ek olarak ' . $installmentFee. ' TL karşılığında eklendi.' );
}

编码愉快。