WooCommerce - woocommerce_rest_cannot_view - Statu

2020-03-13 08:33发布

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 looks like:

https://<url>/wp-json/wc/v1/products

When I am trying to get(GET) the product details using Basic Auth by using POSTMAN, a Chrome plugin, I get a JSON response like:

{
  "code": "woocommerce_rest_cannot_view",
  "message": "Sorry, you cannot list resources.",
  "data": {
    "status": 401
  }
}

I have both the READ and WRITE permissions corresponding to the Consumer key.

8条回答
相关推荐>>
2楼-- · 2020-03-13 09:09

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
]);
查看更多
迷人小祖宗
3楼-- · 2020-03-13 09:10

This is how i stopped worrying and moved on.

In short, the woocommerce rest controllers pretty much all have a SOMEWPRESTCLASS::get_item_permissions_check() method which in turn calls wc_rest_check_post_permissions() to decide if it returns that error;

So you hook into that and validate whichever way you want:

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  ){
  return true;
}
查看更多
Deceive 欺骗
5楼-- · 2020-03-13 09:11

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

查看更多
甜甜的少女心
6楼-- · 2020-03-13 09:15

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

查看更多
淡お忘
7楼-- · 2020-03-13 09:16

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.

查看更多
登录 后发表回答