我无法使用此代码获取离线访问令牌... 为什么?
$client = new Google_Client();
$client->setApplicationName('MyAppName');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$client->setClientId('MyCientID');
$client->setClientSecret('MyClientSecret');
$client->setRedirectUri('http://mydomain.com/googlecallback');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('MyDeveloperKey');
$plus = new Google_Service_Plus($client);
header('Location: '.$client->createAuthUrl());
这是重定向到google登录页面,该页面仅询问1小时访问令牌... 我在黑暗中迷失了......
非常感谢!
编辑:
这是我的登录页面代码:
$client = new Google_Client();
$client->setClientId('qvdsfvqdsf');
$client->setClientSecret('qsdfvqsdf');
$client->setRedirectUri('?a=callback');
$client->setDeveloperKey('qdcQSDCQSD');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new Google_Service_Plus($client);
if($_GET['a'] == 'authorize'){
header('Location: '.$client->createAuthUrl());
}
elseif($_GET['a'] == 'callback' && isset($_GET['code']) && !isset($_GET['error'])){
$client->authenticate($_GET['code']);
if($client->getAccessToken()){
STORE ACCESS TOKEN
}
}
我的API用法:
$client = new Google_Client();
$client->setClientId('qsdfsqd');
$client->setClientSecret('qsdfqsd');
$client->setRedirectUri('qdfq');
$client->setDeveloperKey('sdfvsdf');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new Google_Service_Plus($client);
$client->setAccessToken('STORED ACCESS TOKEN');
$activities = $plus->activities->listActivities('me', 'public', array('maxResults'=>10));
我做错了什么?
答案 0 :(得分:1)
您需要在http://mydomain.com/googlecallback上将“application settings page”网址设置为重定向URI。
$client->createAuthUrl()
方法创建身份验证页面的URL。在转到该页面并授权该应用程序后,Google会使用名为“code”的查询字符串参数将您重定向回/googlecallback
,您应该将其传递给客户端的authenticate()方法。只有这样你才能访问令牌。
这样的事情(假设它在/googlecallback
上):
$client = new Google_Client();
$client->setApplicationName('MyAppName');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$client->setClientId('MyCientID');
$client->setClientSecret('MyClientSecret');
$client->setRedirectUri('http://mydomain.com/googlecallback');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('MyDeveloperKey');
if (empty($_GET['code'])) {
header('Location: '.$client->createAuthUrl());
} else {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
// save the token somewhere so you can use later
// without having to go to the auth page again
}
答案 1 :(得分:0)
终于得到了答案:
使用$client->setApprovalPrompt('force');
阻止了正常的Google令牌刷新过程,而$client->setApprovalPrompt('auto');
则像魅力一样。
感谢。
答案 2 :(得分:0)
如果用户之前已经针对ClientID进行了身份验证而未请求离线模式,然后您请求离线模式,则它不会为您提供刷新令牌。
用户需要从应用程序取消授权,然后在应用程序请求离线模式后重新授权。