WP remote get results in 401 error

Is there a reason as to why this happens?

401 Unauthorized means the bearer token is incorrect. Try generating a new token from https://build.envato.com/my-apps/ and make sure you’re passing $args in the second argument of wp_remote_get().

1 Like

the token is correct, it just trows a 401 when I used wp_remote_get instead of a flat $response etc
I’m still in a learning process, can u tell me why $args is needed?

can’t I just do a normal array?

The second parameter of wp_remote_get takes an array of options (full details here), which can include headers. You’ll need to specify your bearer token in the headers, and the only way to send that info to wp_remote_get is by passing it into the second argument.

You can pass an array directly like this:

$response = wp_remote_get($url,
    array(
        'headers' => array(
            'Authorization' => "Bearer KEY_HERE"
        )
    )
);

Or you can use a variable like this:

$args = array(
    'headers' => array(
        'Authorization' => "Bearer KEY_HERE"
    )
);

$response = wp_remote_get($url, $args);

If you call wp_remote_get without this second parameter, it only sends default headers, which will not include your bearer token and thus will result in 401 Unauthorized.

1 Like

omg no wonder I couldn’t get it to work then.
I’ll try again when I get home & post my results.
Thank you so much for your help, I really appreciate it!

1 Like

that seemed to have solved my 401 error, now gives a proper 200 code.
Now I have to try and extract item name, sales, price etc from the json.
My brain hurts haha, been trying this for 2 days straight.
Hope I can work this out.

If anyone has tips on how to output the info it’s more then welcome <3

PHP has a built-in function for parsing JSON strings and turning them into objects or arrays. http://php.net/manual/en/function.json-decode.php

Should look something like this:

$parsed = json_decode($response['body']);
$itemId = $parsed->id;
$itemName = $parsed->name;
$itemSales = $parsed->number_of_sales;

The names of the parsed fields will match the results found on https://build.envato.com/api/.

1 Like

You are amazing buddy thankyou.
I’m quite new to the PHP scene.
Tried to do my own thing for once, it’s alot of fun but wow it is a brainer sometimes.
I’ll post my results again after a coffee break.

$response = wp_remote_get('https://api.envato.com/v3/market/catalog/item?id='. $id .'.json', array('headers' => array(
                'Authorization' => "Bearer AH6qreWAIBj9Nz1sXXXXXMYKEY"
            	)
       		 		)
    					);
    			
    			$result = json_decode( wp_remote_retrieve_body( $response ) );
return $data->item;

Now I’m trying to call <?php echo $item->number_of_sales; ?> etc in a span.
but it doesn’t seem to work.

Looks like it should be return $result->item instead.

Everything works now, lots of code changes but I did it

1 Like