英文:
Gmail API with PHP
问题
我正在使用Gmail API来读取邮件并添加/删除标签。
我已经成功进行了身份验证,获得了3600秒有效期的访问令牌。
问题开始出现在这里...当我尝试刷新令牌时,我得到了一个null值,所以我无法刷新它。
一些代码示例:
$this->client = new Client();
$this->client->setApplicationName('App');
$this->client->setClientId('xxxxxxx');
$this->client->setClientSecret('xxxxxxx');
$this->client->setRedirectUri('xxxxxxx/oauth/gmail/callback');
$this->client->setScopes([GoogleGmail::GMAIL_READONLY, GoogleGmail::GMAIL_MODIFY]);
$this->client->setPrompt('select_account consent');
$this->client->setAccessType('offline');
在回调中,我执行以下操作:
$this->client->fetchAccessTokenWithAuthCode($code);
输出:
{
"access_token":"xxxxxxxxxx",
"expires_in":3599,
"scope":"https:\/\/www.googleapis.com\/auth\/gmail.readonly https:\/\/www.googleapis.com\/auth\/gmail.modify",
"token_type":"Bearer",
"created":7374384324
}
我保存了访问令牌、过期时间和所有相关数据。但是我没有获取到刷新令牌。
我尝试了以下代码:
$this->client->getRefreshToken(); // null
并且如果我执行以下操作:
$this->client->isAccessTokenExpired()
我总是得到true
,即使我刚刚进行了身份验证5秒钟之前。
我正在使用google/apiclient v2.15.0
和PHP 8.1
。
英文:
I'm using the Gmail API for reads emails and just add/remove labels.
I authenticated correctly, I get my access token with 3600 seconds of life.
And here starts the problems... When I try to Refresh Token, I got a null, so I can't refresh it.
Some code:
$this->client = new Client();
$this->client->setApplicationName('App');
$this->client->setClientId('xxxxxxx');
$this->client->setClientSecret('xxxxxxx');
$this->client->setRedirectUri('xxxxxxx/oauth/gmail/callback');
$this->client->setScopes([GoogleGmail::GMAIL_READONLY, GoogleGmail::GMAIL_MODIFY]);
$this->client->setPrompt('select_account consent');
$this->client->setAccessType('offline');
In the callback I do:
$this->client->fetchAccessTokenWithAuthCode($code);
Output:
{
"access_token":"xxxxxxxxxx",
"expires_in":3599,
"scope":"https:\/\/www.googleapis.com\/auth\/gmail.readonly https:\/\/www.googleapis.com\/auth\/gmail.modify",
"token_type":"Bearer",
"created":7374384324
}
I saved the Access Token, Expired time, and all data really. But I don't get the refresh token.
I try with:
$this->client->getRefreshToken(); // null
And If I do
$this->client->isAccessTokenExpired()
I always get true
, inclusive if I auth 5 seconds ago.
I'm using google/apiclient v2.15.0
, PHP 8.1
Thanks
答案1
得分: 1
只有在用户首次验证您的应用程序时,才会获得刷新令牌。您需要将其存储在应用程序中,同时存储用户的名称,以便在需要请求新的访问令牌时发送。
Web应用程序中的访问令牌刷新不会返回新的刷新令牌。再次请求授权也不会导致生成新的刷新令牌。
英文:
You only get a refresh token with the first time the user has authenticated your application. You need to store that in your application along with the users name so that you can then send that when you would like to request a new access token.
A refresh of an access token in a web app will not return a new refresh token. Requesting authorization again will also not result in a new refresh token.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论