我之前在访问Youtube的API时遇到Google帐户的问题。所以我创建了一个新的Gmail帐户并设法让它工作。不仅在喜欢一个小时之后。我发现刷新令牌没有刷新。我不知道为什么。这变得令人沮丧,因为我似乎不得不放弃使用Youtube服务。
这是我下面的代码:也许我做错了什么。
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setAccessType('offline');
$client->setApprovalPrompt('force'); // this line is important when you revoke permission from your app, it will prompt google approval dialogue box forcefully to user to grant offline access
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
$_SESSION[$tokenSessionKey] = $manually_stored_token; //$client->getAccessToken();
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if($client->isAccessTokenExpired()) {
$client->refreshToken($refresh_token);
if(!$client->isAccessTokenExpired()) {
// do something
} else {
// refresh access token not granted
}
} else if ($client->getAccessToken()) {
// do something
} else {
// do something
}
我在"登录和安全"下检查了我的帐户 https://myaccount.google.com/u/0/security,以获取对您的Google帐户的授权访问权限,我仍然拥有授权。所以我不知道为什么它不刷新我的令牌。
首次授权时,响应中会同时获得access_token
和refresh_token
。
在那之后,你只会得到一个access_token
回来。必须保存并重复使用refresh_token
。
如果出于某种原因您丢失了它,则必须重置您的授权访问权限。
我遇到了这个问题,不得不进行肮脏的黑客攻击,因为没有人能给我答案。
基本解决方法是"取消授权"用户,然后再次"重新授权"他们。如果你不这样做,你永远不会拿回refresh_token
。
进行测试和检查。打开正在授权的帐户。
进入仪表板并找到"连接到您的帐户的应用程序"部分。
在那里,您将看到您的应用程序,并可以手动将其删除以进行测试。
但是,稍后需要为此编写代码,但足以进行测试。