【问题标题】:Add a product to cart through api call通过 api 调用将产品添加到购物车
【发布时间】:2019-12-27 21:31:33
【问题描述】:

我已经设置了 wordpress REST api 来创建一个端点来监听特定第三方服务的调用。此第三方服务将发送包含产品数据的 POST 请求。该数据需要可供 woocommerce 使用,以便它可以将产品添加到购物车。问题是我无法访问将返回 woocommerce 实例的 WC() 函数。第三方服务需要一个 json 响应,它可以是任何东西,只要它是 json。收到响应后,它会将用户重定向到购物车。

我尝试为端点添加一个内部回调函数,该函数将依次运行一个将产品添加到购物车的函数。尝试将此函数与几个不同的点挂钩,例如:init、wp、woocommerce_loaded、rest_api_init 和 wp_footer。

我还尝试发送带有类似参数的 cURL 获取请求 ?add-to-cart=".$request->get_param('productId') 这也不起作用。

我无法发布第三方服务,但是 wp rest api 端点只是一个监听 POST 请求的普通端点。

【问题讨论】:

    标签: php wordpress api woocommerce


    【解决方案1】:

    我使用以下代码解决了这个问题:

    add_filter( 'woocommerce_is_rest_api_request', [ $this, 'simulate_as_not_rest' ] );
    /**
    * We have to tell WC that this should not be handled as a REST request.
    * Otherwise we can't use the product loop template contents properly.
    * Since WooCommerce 3.6
    *
    * @param bool $is_rest_api_request
    * @return bool
    */
    public function simulate_as_not_rest( $is_rest_api_request ) {
    if ( empty( $_SERVER['REQUEST_URI'] ) ) {
            return $is_rest_api_request;
    }
    
    // Bail early if this is not our request.
    if ( false === strpos( $_SERVER['REQUEST_URI'], $this->namespace ) ) {
        return $is_rest_api_request;
    }
    
    return false;
    

    }

    我将命名空间设置为 API 路由的命名空间。

    我希望这对某人有所帮助

    【讨论】:

      猜你喜欢
      • 2012-06-09
      • 2019-10-02
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多