Magento – Magento 2 rest API returns false when trying to get a token

apicurlmagento2PHPrest

I am trying to create a web app that gets data from a Magento 2 website thanks to the API, following this tutorial but it returns bool(false) when I do var_dump($token)

I have read other threads on StackOverflow saying it might be linked to an error with SSL, but I have no error when I use curl_error($ch) so I don't think that's the issue.

My code :

  $userData = array("username" => $username, "password" => $password); 
  $ch = curl_init("http://mywebsite/index.php/rest/V1/integration/admin/token"); 
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData)); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Length: " . strlen(json_encode($userData))));

  $token = curl_exec($ch);

Thank you for reading.

EDIT: The account I use has a role with all permission so that shouldn't be the issue either.

EDIT 2: When I change the Magento URL and account to the ones from this demo it returns me a token and the information I want, but not with the Magento I am working on.

Best Answer

Try to do this code which is quite similar:

//API URL
$url = 'http://mywebsite/rest/V1/integration/admin/token';

//create a new cURL resource
$ch = curl_init($url);

//setup request to send json via POST
$data = array(
    'username' => '.....',
    'password' => '.....'
);
$payload = json_encode(array("user" => $data));

//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute the POST request
$result = curl_exec($ch);

//close cURL resource
curl_close($ch);

You can try also to follow the redirect :

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

You can also add these lines in order to debug your CURL request in a custom file.

curl_setopt($handle, CURLOPT_VERBOSE, true);

$verbose = fopen('/tmp/curl.log', 'w+');
curl_setopt($handle, CURLOPT_STDERR, $verbose);

Moreover, first try to test you API thanks to Postman or other software to know if the problem is on the curl / php side.

What is your webserver ? Apache / Nginx ? Do you use the default Magento 2 configuration ?