I have this basic API script:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);
$usr = [
'username' => 'username',
'password' => 'somePassword'
];
$ch = curl_init('https://magentostore/index.php/rest/V1/integration/admin/token');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($usr));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: '. strlen(json_encode($usr))]);
$token = curl_exec($ch);
echo '<pre>';
print_r($token);
echo '</pre>';
echo '========================';
$ch = curl_init('https://magentostore/index.php/rest/V1/orders/1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer '. json_decode($token)]);
$result = curl_exec($ch);
$result = json_decode($result, 1);
echo '<pre>'. print_r($result) .'</pre>';
but it returns this message:
Array ( [message] => Consumer is not authorized to access %resources [parameters] => Array ( [resources] => Magento_Sales::sales ) )
I'm not sure why, my script should work but I can't figure out why? Is it because of username
account permissions? Shouldn't be as user = admin. Just trying to get array of orders ...
Alternative testing method that yielded same results:
I did:
curl -X POST 'https://magentostore/index.php/rest/V1/integration/admin/token' \
-H 'Content-Type:application/xml' \
-d '<login><username>admin</username><password>password</password></login>'
which got me the Token, which I then used like this:
curl -X GET https://magentostore/index.php/rest/V1/orders/1' -H 'Authorization: Bearer <Token that was returned>'
which gets me the same error as above
Edit:
I've tried with a few different API Endpoints and some work (like getting categories) but /orders
still doesn't. I've tried on 3 separate environments and only 1 works:
Env One - Doesn't Work
- OS: CentOS 7
- PHP Version: 7.1
- Magento Version: 2.2.5
- Hosted outside of LAN
Env Two - Doesn't Work
- OS: CentOS 7
- PHP Version: 7.0
- Magento Version: 2.2.5
- Hosted outside of LAN
Env Three - DOES WORK
- OS: Linux Mint 19
- PHP Version: 7.2
- Magento Version: 2.3-develop
- localhost