WooCommerce - woocommerce_rest_cannot_view - Status 401

前端 未结 10 804
眼角桃花
眼角桃花 2021-01-02 00:09

I have generated a consumer key and consumer secret. The website has SSL installed. I have also installed plugins required for JSON and REST services. This is how the url lo

相关标签:
10条回答
  • 2021-01-02 00:27

    You can try Oauth 1.0 with postman:

    0 讨论(0)
  • 2021-01-02 00:31

    Try this, I had the same issue with the automattic/woocommerce library and I just got it working by appending the customer_key and customer_secret to the query.

    $woocommerce->get("customers/$userId?consumer_key={$this->key}&consumer_secret={$this->secret}");
    

    Quick Edit


    The above method works but I found a better solution for the automattic/woocommerce library.

    Set query_string_auth to true

    Had to dig into the code to find this setting.

    Found nothing on it in the docs

    return new Client($this->url, $this->key, $this->secret, [
        "query_string_auth" => true
    ]);
    
    0 讨论(0)
  • 2021-01-02 00:34

    Here is a modified answer to Quickredfox's anwer:

    add_filter('woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4);
    
    function my_woocommerce_rest_check_permissions($permission, $context, $object_id, $post_type) {
        if($_GET['consumer_key'] == 'asdfghj' && $_GET['consumer_secret'] == 'qwerty') {
            return true;
        }
    
        return $permission;
    }
    

    The downside to this is that the flexibility of adding and revoking access for users using a gui is lost. However, if nothing else works and you just can't figure out why, this will work and does not expose the API to the whole world.

    Oh, and this requires passing the key and secret as parameters a la:

    https://foo.bar.com/wp-json/wc/v3/products/123&consumer_key=asdfghj&consumer_secret=qwerty
    

    This will work without https, but if you use it without https, remember that any credentials you send along with your request will be sent in plain text.

    0 讨论(0)
  • 2021-01-02 00:36

    I met same problem.

    Here is how I solve it:

    require "woocommerce_api"
    
    woocommerce = WooCommerce::API.new(
      "https://example.com",
      "consumer_key",
      "consumer_secret",
      {
        wp_json: true,
        version: "wc/v1",
        query_string_auth: true
      }
    )
    

    The key is query_string_auth: true you need to force basic authentication as query string true under HTTPS

    0 讨论(0)
  • 2021-01-02 00:36

    For local development (localhost) you can also use Basic Auth (e.g. for Postman) instead of Consumer Key & Consumer Secret. It works seamlessly.

    0 讨论(0)
  • 2021-01-02 00:40

    The 401 error you are getting is because you are using basic auth even though your website is not secure (does not have https).

    The solution in postman is to use OAuth 1.0. Just add the consumer key and consumer secret and send the request.

    0 讨论(0)
提交回复
热议问题