5

我在应用中的实现就像我的 WooCommerce 网站一样。我想在计算运费时达到以下几点:

  1. 检查是否需要地址来计算送货地址?
  2. 如果地址是用户输入的,如何检查该地址是否在运输方式标准之间?如果输入的地址根据运输方式无效,则向用户提供错误。
  3. 一旦用户输入有效地址,计算所有运输方式的成本。
  4. 在应用程序中向用户显示所有运输方式,并选择默认方式。
  5. 当用户在运输方式之间切换时,它也应该保存并与网站同步,并根据所选方式获取购物车总数。

到目前为止,我实现的是第 4 点。我可以通过网站计算所有运输方式,但如果不是通过网站计算,那么它会在那里返回 null。

这是我的 API 代码:

function register_get_cart_shipping() {

    register_rest_route(
        'custom-plugin', '/getCartShipping/',
        array(
            'methods'  => ['GET'],
            'callback' => 'getCartShipping',
        )
    );

        function getCartShipping() {
            $chosen_methods = WC()->session->get('chosen_shipping_methods');
            $count = 0;
            foreach( WC()->session->get('shipping_for_package_0')['rates'] as $method_id => $rate ){

                $data[$count]->rate_id        = $rate->id;
                $data[$count]->method_id      = $rate->method_id;
                $data[$count]->instance_id    = $rate->instance_id;
                $data[$count]->label          = $rate->label;
                $data[$count]->cost           = $rate->cost;
                $data[$count]->taxes          = $rate->taxes;
                $data[$count]->chosen         = $chosen_methods['rate_id'];

                if($chosen_methods['rate_id'] == $rate->id ){
                    $data[$count]->isSelected  = true;
                } else {
                    $data[$count]->isSelected  = false;
                }
                $count++;
            }
            return $data;
        }
}

同样对于第 5 点,当用户在运输方式之间切换时,我正在使用此代码,但它不会更新网站上选择的运输方式。这是代码:

function updateCartShipping($request) {
            $rate_id["rate_id"] = "table_rate:10:4";
            // $rate_id["rate_id"] = "table_rate:9:3";
            // $rate_id["rate_id"] = $request['shippingID'];
            WC()->session->set('chosen_shipping_methods', $rate_id);
            return "OK";
}

我也不知道将哪个方法 id 设置为运输方式。这对我来说似乎很神秘。

任何帮助将不胜感激。谢谢!

4

0 回答 0