Google API Client “refresh token must be passed in or set as part of setAccessToken”

后端 未结 9 1381
Happy的楠姐
Happy的楠姐 2020-12-05 07:55

I am currently facing a very strange problem, indeed I\'ve been following this very same guide (https://developers.google.com/google-apps/calendar/quickstart/php) from Googl

9条回答
  •  长情又很酷
    2020-12-05 08:42

    My advice is save refresh token to .json immediately after get access token and if access token expired use refresh token.

    In my projects work this way:

    public static function getClient()
    {
        $client = new Google_Client();
        $client->setApplicationName('JhvInformationTable');
        $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
    
        // Load previously authorized credentials from a file.
        $credentialsPath = 'token.json';
        $credentialsPath2 = 'refreshToken.json';
        if (file_exists($credentialsPath)) {
            $accessToken = json_decode(file_get_contents($credentialsPath), true);
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            //printf("Open the following link in your browser:\n%s\n", $authUrl);
            //print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));
    
            //echo "";
            //exit;
    
            $authCode ='********To get code, please uncomment the code above********';
    
            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $refreshToken = $client->getRefreshToken();
    
            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
    
            // Store the credentials to disk.
            if (!file_exists(dirname($credentialsPath))) {
                mkdir(dirname($credentialsPath), 0700, true);
            }
            file_put_contents($credentialsPath, json_encode($accessToken));
            file_put_contents($credentialsPath2, json_encode($refreshToken));
            printf("Credentials saved to %s\n", $credentialsPath);
        }
        $client->setAccessToken($accessToken);
    
        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $refreshToken = json_decode(file_get_contents($credentialsPath2), true);
            $client->fetchAccessTokenWithRefreshToken($refreshToken);
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }
    

提交回复
热议问题