WooCommerce 通过 REST API 计算运费

And*_*diM 5 php android woocommerce woocommerce-rest-api shipping-method

我在应用程序中的实现就像我的 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;
        }
}
Run Code Online (Sandbox Code Playgroud)

同样对于第 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";
}
Run Code Online (Sandbox Code Playgroud)

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

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