-1

Trying to access 'access_token' from this PHP cURL response. None of my attempts have been able to access the JSON data so I can append it to the header 'Authorization: Bearer $accessToken'

Here is my PHP cURL (Username and password redacted)

<?php 

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://atreemosandbox.atreemo.com/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"grant_type=password&username=[USERNAME]&password=[PASSWORD]");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',

    // Here is where I want to use the $accessToken. 

    'Authorization: Bearer ' . $accessToken.    <---------

));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec ($ch);

//Trying to access $accessToken here.    

$accessToken = $response["access_token"]  <--------

//This had no response to get data.

echo $response;

?>

$response:

{"access_token":"ahpdhwpibdb3iv1v21dv33dp13udv3","token_type":"bearer","expires_in":86399,"userName":"[USERNAME]",".issued":"Sun, 28 Mar 2021 22:43:30 GMT",".expires":"Mon, 29 Mar 2021 22:43:30 GMT"}

Also tried:

$accessToken = $response.access_token
//No Response
$accessToken = $response->access_token
//No Reponse
 

Is this the wrong syntax to access data in PHP?

danielrhodesy
  • 47
  • 1
  • 5
  • 1
    You'll want to do a json_decode() on the server response ($response). $response is just a string of the server's response - json_decode() will transform it to an array variable from which you should then be able to reference ["access_token"] – Craig Mar 28 '21 at 23:04
  • Thank you for the responses. I followed directions from @Cyborgs answer – danielrhodesy Mar 28 '21 at 23:14
  • Mark his answer as a valid one then. – biesior Mar 28 '21 at 23:24

1 Answers1

2

Use:

$data = json_decode($response, 1);
echo $data['access_token'];
Cyborg
  • 1,437
  • 19
  • 40