Magento 2 API – Authentication Issues and Solutions

apimagento2

I'm new to Magento, and even newer to Magento 2, and am trying to get an output of all sales orders in json.

I followed the following tutorial: http://blog.i13websolution.com/magento-2-rest-api-example/

I can get this to work locally, however when I migrated to my stage server I get the following message:

You did not sign in correctly or your account is temporarily disabled

I've checked, and the account works, I can log into it without an issue via the admin backend. It's restricted to only being able to access the Sales Orders page and this seems to work fine in the backend.

I have also created a user role with the correct permissions identical to my local environment.

The code as it is set up is as follows:

$serverip = $_SERVER['REMOTE_ADDR'];
$adminUrl='http://'.$_SERVER['HTTP_HOST'].'/index.php/rest/V1/integration/admin/token';
$ch = curl_init();
//Stage
$data = array("username" => "username", "password" => "password");

//Local
if($serverip == '127.0.0.1'){
$data = array("username" => "username2", "password" => "password23");
}

$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token=  json_decode($token);

//Use above token into header
$headers = array("Authorization: Bearer $token");

//Call all pending values
$requestUrl='http://'.$_SERVER['HTTP_HOST'].'/index.php/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=status&searchCriteria[filter_groups][0][filters][0][value]=Pending';

$ch = curl_init();
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
print_r($result);

I'm quite stumped as to why the above isn't working on an actual server. Curl is installed, the user is set up… any pointers would be appreciated.

Best Answer

Resolved this issue.

The API would only accept a username without underscores in, may have been a server set up issue.