Magento 2.1 – PHP Curl REST API Token Return False Solution

magento-2.1php-7rest

I'm trying to get an auth token with Magento 2 rest API with following code

$userData = array("username" => "user", "password" => "password");
$ch = curl_init("https://domain/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-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);
var_dump($token);

It works fine on the local server, but $token = false from the test server. I can retrieve token with curl from a console.

curl -X POST "https://domain/index.php/rest/V1/integration/admin/token/" -H "Content-Type:application/json" -d '{"username":"user", "password":"password"}'

Why am I receiving false in a PHP script? Any ideas?

Best Answer

Output of curl_error($ch) give me following error

SSL certificate problem: unable to get local issuer certificate

Easy fix - https://stackoverflow.com/a/31830614/923497. Just duplicate it here

1) Download the latest cacert.pem from https://curl.haxx.se/ca/cacert.pem

2) Add the following line to php.ini (if this is shared hosting and you don't have access to php.ini then you could add this to .user.ini in public_html)

curl.cainfo=/path/to/downloaded/cacert.pem
Related Topic