I have this json object that I want to get the access_token but its refusing i have no idea why . This is the response I want the access_token
{
"access_token": "Alhq74lVl5GAOVAZrprOGSS1Gj73",
"expires_in": "3599"
}
This is the code
function generateToke() {
// $url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
$credentials = base64_encode('qniogqzdbIskIQt9nxgxG1wSBkzgUqN0:XUjxWzQY3WTndqHh');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$result = json_decode($curl_response);
$token = $result->access_token;
echo $token;
}
getting the same error
the above code is still displaying to me the json but i want to get only the Alhq74lVl5GAOVAZrprOGSS1Gj73
You're not accessing the access_token
property of the resulting object, you try to access a property that is named in the not defined variable $access_token;
.
So just remove the $-sign and it shoudl work:
$token = $result->access_token;
Furthermore you're missing a curl option to return the content:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Without this option set to true you're not retrieving the response from the curl_exec
call.
Change:
$token = $result->$access_token;
To (without the $
on access_token):
$token = $result->access_token;
It's not working because PHP has a feature called variable variables which you've accidentally used. PHP is trying to get the property of whatever the value of $access_token
is. E.g. if a variable called $access_token
was set to helloworld
, PHP would run $result->helloworld
and replace $access_token
with it's value.