且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用OAuth刷新令牌获取新的访问令牌-Google API

更新时间:2023-02-16 07:46:50

哇,我花了更长的时间才弄清楚这一点,而那里的答案对我来说似乎还很不完整.

Whoa, it took me significantly longer to figure this out, and the answers out there seemed quite incomplete to me.

开始之前,请记住,此答案假设您正在使用最新的 Google API PHP库,截至 2014年5月26日.

Before we start please keep in mind that this answer assumes you are using the latest Google API PHP Library, as of May 26th of 2014.

1-确保您的应用请求的访问类型为offline.否则未提供.来自Google:仅当授权码请求中包含access_type = offline时,此字段才存在.

1 - Make sure the access type your app requests is offline. A refresh_token is not provided otherwise. From Google: This field is only present if access_type=offline is included in the authorization code request.

$gClient->setAccessType('offline');

2-首次授权后,请保留提供的refresh_token以便进一步访问.这可以通过 cookies 数据库等完成.我选择将其存储在数据库中:

2 - Upon the first authorization, persist the provided refresh_token for further access. This can be done via cookies, database, etc. I chose to store in on a database:

$tokens = json_decode($gClient->getAccessToken()); /* Get a JSON object */
setRefreshToken($con, $tokens->refresh_token /* Retrieve form JSON object */);

3-检查AccessToken是否已过期,如果是这种情况,请向Google请求刷新的令牌.

3 - Check if the AccessToken has expired, and request a refreshed token from Google if such is the case.

if ($gClient->isAccessTokenExpired()) {    
  $refreshToken = getRefreshToken($con, $email); 
  $gClient->refreshToken($refreshToken);
}  

getRefreshToken将从数据库中检索先前存储的refresh_token的位置,然后将该值传递给Client的refreshToken方法.

Where getRefreshToken is retrieving the previously stored refresh_token from our database, and then we pass that value to the Client's refreshToken method.

快速说明:请记住,如果您先前已经授权了您的应用,则可能不会在响应中看到refresh_token,因为它仅在我们第一次致电时提供authenticate.因此,您可以转到 https://www.google.com/settings/security ,然后撤消对应用程序的访问权限,或者在创建客户端对象时可以添加以下行:

Quick Note: It's key to remember that if you had previously authorized your app, you probably won't see a refresh_token on the response, since it is only provided the first time we call authenticate. Therefore, you can either go to https://www.google.com/settings/security and Revoke Access to your app or you can add the following line when creating the Client object:

$gClient->setApprovalPrompt('force');

从Google发送:如果该值是强制值,则即使用户先前已同意您对给定范围的一组应用程序,该用户也会看到一个同意页面.这样可确保会在每个授权中提供.

From Google: If the value is force, then the user sees a consent page even if they previously gave consent to your application for a given set of scopes. Which in turn ensures that a refresh_token is provided on each authorization.

完整示例在这里: http://pastebin.com/jA9sBNTk