1

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);
2
  • are You giving the username and password @Ismail Berlin Apr 6, 2018 at 10:01
  • yes, I also check it with Postman and working fine Apr 6, 2018 at 10:04

3 Answers 3

2

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);
0

My problem was in the SSL security, I requested the API without ssl connection and it worked fine. I mean I used : $adminUrl='http://....; instead of $adminUrl='https://....;

0

Following code is working in magento2.3 to get token:

$userData = array("username" => "<username>", "password" => "<password>");
$ch = curl_init("http://<website>/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);
echo $token;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.