I have this method below with a curl functionality. I would like the extract the access token from the result using PHP. I have tried echo in three ways as shown in the code below but I am only getting a boolean response or an error. How do I go about it?
$consumer_key = "CONSUMER_KEY";
$consumer_secret = "CONSUMER_SECRET";
$url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
$credentials = base64_encode($consumer_key.":".$consumer_secret);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.$credentials)); //setting a custom header
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$access_token = json_decode($curl_response);
echo "<br><br>---------------Trial 1-------------<br>";
echo $curl_response;
echo "<br><br>---------------Trial 2-------------<br>";
echo $access_token->access_token;
echo "<br><br>---------------Trial 3-------------<br>";
echo $access_token['access_token'];
}```
This is the response I get:
---------------Trial 1-------------
HTTP/1.1 200 OK Date: Fri, 07 May 2021 10:18:40 GMT Content-Type: application/json;charset=UTF-8 Content-Length: 113 Connection: keep-alive Cache-Control: no-store { "access_token": "a6aAK9rdA4MA2ChqVzEDge6DAWTC", "expires_in": "3599" }
---------------Trial 2-------------
A PHP Error was encountered
Severity: Notice
Message: Trying to get property 'access_token' of non-object
Filename: controllers/Lab.php
Line Number: 99
Backtrace:
File: /home2/airduka/public_html/sandbox/application/controllers/Lab.php
Line: 99
Function: _error_handler
File: /home2/airduka/public_html/sandbox/index.php
Line: 315
Function: require_once
---------------Trial 3-------------
Disable response header by setting CURLOPT_HEADER to false.
curl_setopt($curl, CURLOPT_HEADER, false);
Then json_decode will work and you can get the token with this;
$curl_response = curl_exec($curl);
$access_token = json_decode($curl_response, true);
$access_token['access_token']
Use below code to make json object return as array:
$access_token = json_decode($curl_response, true);
Then you can get the access token by following:
$access_token['access_token']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.