Answer a question

I'm building an e-shop on WordPress + WooCommerce and Android app that retrieving data from WooCommerce REST API. I'm using WooCommerce's REST API with JWT to get information about products, categories, etc. also make orders, adding to cart, etc.

It's good, if you have admin's OAuth 1.0a credentials, but, I'm using customer's JWT. I made WordPress accept this auth method (by my plugin).

If I make request to http://SERVER/wp-json/wc/v3/products/categories, I will get this error:

{
    "code": "woocommerce_rest_cannot_view",
    "message": "Вы не можете просматривать список ресурсов.",
    "data": {
        "status": 403
    }
}

I'm passing Authentification: Bearer "JWT" and WordPress accept it, but WooCommerce don't give me any info.

How I made WordPress accept my JWT:

function test_rest_user($result, $th, $request){
    $secret_key = defined('JWT_AUTH_SECRET_KEY') ? JWT_AUTH_SECRET_KEY : false;

    $auth = $request->get_header_as_array("Authorization");
    if ($auth){
        $token = explode(" ", $auth[0])[1];

        $user = api::exchange_token_to_wp_user($token, $secret_key);
        if ($user){
            set_current_user($user->data->ID);
        }
    }
}
add_filter("rest_pre_dispatch", "test_rest_user", 10, 3);

The main topic of this question is that WooCommerce not accepting JWT. This is response from WordPress REST API with customers's JWT (http://SERVER/wp-json/wp/v2/users/me):

{
    "id": 7,
    "name": "test",
    "url": "",
    "description": "",
    "link": "http://SERVER/author/test/",
    "slug": "test",
    "avatar_urls": {},
    "meta": [],
    "_links": {
        "self": [
            {
                "href": "http://SERVER/wp-json/wp/v2/users/7"
            }
        ],
        "collection": [
            {
                "href": "http://SERVER/wp-json/wp/v2/users"
            }
        ]
    }
}

Answers

So, I'd temporal solution. I made function, that hooks WooCommerce REST API permissions, you can Google how to do that. It hooks from woocommerce_rest_check_permissions filter. Just check is user logged in and provide access to methods. It's so easy!

Logo

WooCommerce社区为您提供最前沿的新闻资讯和知识内容

更多推荐