mardi 30 mai 2023

Cannot use object of type GuzzleHttp\Psr7\Response as array in file

I am new in laravel, I am getting an error when I am trying to access elements of json response in this case being access_token

details of the error:

'Cannot use object of type GuzzleHttp\Psr7\Response as array in file /home/chefane/myProjects/paylesotho/app/Http/Controllers/Api/EletricityController.php on line 34'

below I created a function that returns data in json format, now the trick is how to access one of the elements. below is what I did:

 public function getToken(Request $request){

        $url = Config('api.url');

        $client = new \GuzzleHttp\Client();
        $headers = [
        'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        
        $response = $client->request('POST', $url, [$headers,
        'form_params' => [
            'client_id' => Config('api.client_id'),
            'client_secret' => Config('api.client_secret'),
            'username' => Config('api.username'),
            'password' => Config('api.password'),
            'grant_type' => 'password',
            'scope' => 'read write openid'
            ]  
        ]);
      
        $data = json_decode($response->getBody(),true);
        $key_value =   $response['access_token'];
        return $key_value;
    }

below is what the function returns:

{
 "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJlUktVWG10TFhKMHBBNkxBS29aWko1ZlU0VDhCdmxKdERCb3pXanFFdnhjIn0.eyJleHAiOjE2ODU0ODUzOTMsImlhdCI6MTY4NTQ0OTM5MywianRpIjoiYWYxNTI5ZjAtNTdmYS00MjgyLWIzYTEtZWNlMzZlNjY4MzU2IiwiaXNzIjoiaHR0cHM6Ly9leHRhdXRoLmZpbmNsdWRlLmNvLnphL2F1dGgvcmVhbG1zL2ZpbmNsdWRlIiwic3ViIjoiZDNhNTNiZTgtZDgyOS00ZmU4LWI4ZmUtNGQzNDVkNzAzNWY4IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiQjJCX0FQSSIsInNlc3Npb25fc3RhdGUiOiJlNjE3MjdjNi03ZjdhLTQ4NDItODg0ZC1lNTdhY2UyYjczMDEiLCJhY3IiOiIxIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSByZWFkIHdyaXRlIiwicHJlZmVycmVkX3VzZXJuYW1lIjoicGF5bHNhcGkif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return only the access_token



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/YZHoWNT
via IFTTT

Aucun commentaire:

Enregistrer un commentaire