我请求使用以下PHP代码块访问用户的Google课堂数据:
public function getGoogleClassroomToken(){
if($this->user==null){
return ["result"=>"error","message"=>"You need to log in to do that!"];
}
if ($this->user['gc_token']) {
return ["result"=>"error","message"=>"User already has access token!"];
}
$client = new Google_Client();
$client->setApplicationName('example.com');
$client->setAuthConfig('/var/www/client_secret.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$client->addScope(Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS);
$client->addScope(Google_Service_Classroom::CLASSROOM_COURSES_READONLY);
$client->addScope(Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY);
$redirect_uri = 'https://example.com/gc.php';
$client->setRedirectUri($redirect_uri);
$authUrl = $client->createAuthUrl();
return ["result"=>"success","authUrl"=>$authUrl];
}
..似乎工作正常。然后,我使用以下代码块实例化Google Client:
public function getGoogleClassroomClient(){
if($this->user==null){return false;}
if (!$this->user['gc_token']) {return false;}
$client = new Google_Client();
$client->setAuthConfig('/var/www/client_secret.json');
$client->setAccessToken((array)json_decode($this->user['gc_token']));
if ($client->isAccessTokenExpired()) {
if ($client->getRefreshToken()) {
$token = $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
var_dump($token);
}
}
return $client;
}
..可以正常工作,除非令牌已过期,在这种情况下,$ token变量将输出:
array(2) { ["error"]=> string(13) "invalid_grant" ["error_description"]=> string(11) "Bad Request" }
有人知道这是怎么回事吗?
答案 0 :(得分:0)
根据the Google APIs Client Library for PHP,刷新令牌不能为空,而不会抛出this exception 必须将刷新令牌传递或设置为setAccessToken的一部分,因为调用$client->getRefreshToken()
并返回2个选项:the refresh token or null。
如果您查看Google Identity Platform: Using OAuth 2.0 to Access Google APIs > Refresh token expiration,看来您的刷新令牌已过期,则可能存在一些情况:
Google Identity Platform: Using OAuth 2.0 to Access Google APIs