I am trying to call api to retrieve token but it’s not working. I have tried diff. ways to pass parameters but curl request returns nothing.
This is my code that i am trying. But it returns nothing.
$xurl = 'https://test-api.authtest.com/oauth2/token';
$userName = '76556789000023';
$password = '1hjgtyudkportd4451test';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $xurl,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'grant_type' => 'password'
],
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
CURLOPT_USERPWD => $userName . ':' . $password,
CURLOPT_HTTPHEADER => array( "Content-Type: application/json" ),
));
$response_received = curl_exec($curl);
if(curl_errno($curl))
$response_received=curl_error($curl);
else
curl_close($curl);
var_dump($response_received);
echo "<br><br>";
print_r("<b>response_received</b><br>".$response_received);
2
Answers
It's working for me. This is solution. I have used http_build_query() and CURLOPT_USERPWD
It looks like you are trying to do a OAuth2 Password Grant (which is deprecated) and from you explicitly setting the
Content-Type
toapplication/json
I assume the endpoint wants a JSON.In this case, you need to adjust your code as follows:
This has the following changes:
Basic-Auth
, as the server wont understand thisCURLOPT_HEADER
setting to make sure we see the HTTP response headers in the response fromcurl_exec()
$xurl
to httpbin.org, just change those values backIf you need more docs on the OAuth2 Password Grant, this might be helpful: https://www.oauth.com/oauth2-servers/access-tokens/password-grant/