Search code examples
phpgoogle-apigoogle-api-php-client

Undefined index: expires_in /vendor/google/apiclient/src/client.php in 574 using google api


I am using google api and facing below error-

Undefined index: expires_in /vendor/google/apiclient/src/client.php in 574.

I am not sure what this error means when I checked the file it was wriiten-

 if (!isset($this->token['expires_in'])) {
            // if the token does not have an "expires_in", then it's considered expired
            return true;
        }

        // If the token is set to expire in the next 30 seconds.
        return ($created + ($this->token['expires_in'] - 30)) < time();

Can you please let me know what this error means and how I can resolve it.

This is my custom code -

if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }

        file_put_contents($credentialsPath, json_encode($accessToken));
    }

    $client->setAccessToken($accessToken);

    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }

Solution

  • Im curious as to why you are bothering with expire_in? why not just check $client->isAccessTokenExpired()? The client library will tell you if its expired or not. It takes into account clock skew as well.

    Example:

    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
      ...
    

    If you really want to check it try !isset($this->token['expires_in']] because it sounds like it hasn't been set yet. doing a print_r($this->token) on token might shed some light on your issue.

    update

    Wild guess try this, you may be having issues with the parsing of your file.

    if (file_exists(TOKENPATH)) {
       $userCredentials = json_decode(file_get_contents(TOKENPATH), true);
       $client->setAccessToken($userCredentials['refresh_token']);
       $client->refreshToken($userCredentials['refresh_token']);
       $client->fetchAccessTokenWithRefreshToken($userCredentials['refresh_token']);
        }