Parse yii\httpclient\Client Response

I’m trying to use a Rest API by doing

use yii\httpclient\Client;

$client = new Client(['responseConfig' => [
    'format' => Client::FORMAT_JSON
],]);
$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('https://.../oauth2/token/')
    ->setData([
        'client_id' => '...',
        'client_secret' => '...',
    ])
    ->send();
if ($response->isOk) {
    $token = $response->data['access_token'];
}

and that work fine assuming the credential are valid. I receive a response of, so I can get the access token

Array
(
    [access_token] => Zf35fqiixMGk2Xl7zvXwetClPvGa6dUggUc1xsuoGSuVowH-S3ER_lhgfQ..
    [expires_in] => 7200
)

My question is how can I properly manage when things go wrong? Assuming the crendtials are invalid I receive

Array
(
    [error] => Array
        (
            [code] => 400
            [error] => invalid_client_id
            [error_description] => Invalid client_id
            [message] => Invalid client_id
            [details] => Array
                (
                )

        )

)

How can I tell if I’m receiving an access token vs an error?

Try something like

if (isset($response->data['access_token'])) {
    $token = $response->data['access_token'];
} elseif (isset($response->data['error'])) {
    // Process error
}
1 Like