SOLVED – API Token Request Curl Returns NULL in Magento 2

apicurlmagento2rest apitoken

I am trying to get a token from my Magento 2 API, my script returns NULL, the call is working fine in Postman and generating a token :

$adminUrl='https://www.xxxxxxx.com/rest/V1/integration/admin/token';
$ch = curl_init();
$data = array("username" => "myusername, "password" => "mypassword");
$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);
var_dump($token);

Best Answer

You have to add this line to your code

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);

like this

$adminUrl='https://www.xxxxxxx.com/rest/V1/integration/admin/token';
$ch = curl_init();
$data = array("username" => "myusername, "password" => "mypassword");
$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_SSL_VERIFYPEER , false); // add this line
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token=  json_decode($token);
var_dump($token);