我终于找到了问题,想详细说明是什么原因,说不定别人会派上用场。因此,我按照官方文档 https://developers.google.com/youtube/v3/guides/auth/server-side-web-apps#obtainingaccesstokens 中的描述创建了所有内容。
我使用了此代码,但无法获取刷新令牌。
$googleClient = new \Google_Client();
$redirectUrl = url('***');
$googleClient->setClientId(config('services.google_api_key.client_id'));
$googleClient->setClientSecret(config('services.google_api_key.client_secret'));
$googleClient->setScopes(config('services.google_api_key.scopes'));
$redirect = filter_var($redirectUrl);
$googleClient->setRedirectUri($redirect);
$googleClient->setAccessType('offline');
$googleClient->setApprovalPrompt('force');
if ($request->has('code')) {
$googleClient->authenticate($request->get('code'));
$token = $googleClient->getAccessToken();
dd($token);
}
官方文档是这样说的:
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access,you can omit this.
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
注意这部分:
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access,you can omit this.
$client->setApprovalPrompt("consent");
这就是我设法找到的
$client->setApprovalPrompt('force'); // works
$client->setApprovalPrompt('consent'); // doesn't work
$client->setPrompt('consent'); // works
For 'consent' setApprovalPrompt()
不起作用,但我在官方文档中找不到它。并从这里 https://github.com/googleapis/google-api-php-client/issues/1795 发现了这个错误。
我的最终代码看起来像这样工作正常并返回一个刷新令牌:
$redirectUrl = url('my_callback_url');
$client = new \Google_Client();
$client->setClientId(config('services.google_api_key.client_id'));
$client->setClientSecret(config('services.google_api_key.client_secret'));
$client->addScope(config('services.google_api_key.scopes'));
$client->setState(substr(md5(time()),15));
$client->setRedirectUri($redirectUrl);
$client->setAccessType('offline');
$client->setPrompt('consent');
$client->setIncludeGrantedScopes(true);
return $client->createAuthUrl();
感谢stvar的回答,之后我又开始重新阅读文档并寻找原因。
本文链接:https://www.f2er.com/931814.html