如何使用Google API客户端刷新令牌? [英] How to refresh token with Google API client?

查看:124
本文介绍了如何使用Google API客户端刷新令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩Google Analytics API(V3),并且遇到了som错误。首先,一切都设置正确,并与我的测试帐户一起工作。但是当我想从另一个配置文件ID(Same Google Accont / GA Account)中获取数据时,我收到了403错误。奇怪的是,某些GA帐户的数据会返回数据,而其他数据则会产生此错误。



我已经撤销了该令牌并进行了验证,现在看来就像我可以从所有帐户中获取数据一样。问题解决了?不。由于访问密钥将过期,我将再次遇到同样的问题。



如果我理解正确,可以使用resfreshToken获取新的身份验证。 / p>

问题是,当我运行时:

  $ client-> ; refreshToken(refresh_token_key)

返回以下错误:

 刷新OAuth2令牌时出错,消息:'{error:invalid_grant}'

我检查了refreshToken方法背后的代码,并将请求追踪回apiOAuth2.php文件。所有参数均正确发送。在方法中,grant_type被硬编码为'refresh_token',所以我很难理解错在哪里。参数数组如下所示:

  Array([client_id] => *******  -  uqgau8uo1l96bd09eurdub26c9ftr2io.apps .googleusercontent.com [client_secret] => ******** [refresh_token] => 1 \ / lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY [grant_type] => refresh_token)


程序如下。

  $ client = new apiClient(); 
$ client-> setClientId($ config ['oauth2_client_id']);
$ client-> setClientSecret($ config ['oauth2_client_secret']);
$ client-> setRedirectUri($ config ['oauth2_redirect_uri']);
$ client-> setScopes('https://www.googleapis.com/auth/analytics.readonly');
$ client-> setState('offline');

$ client-> setAccessToken($ config ['token']); //访问JSON对象。

$ client-> refreshToken($ config ['refreshToken']); //这里会返回错误

这是一个错误还是我完全误解了某些内容?

解决方案

所以我终于想出了如何做到这一点。基本的想法是,你有第一次要求认证的令牌。这第一个标记有一个刷新标记。第一个原始令牌在一小时后过期。一小时后,您必须使用第一个令牌中的刷新令牌来获取新的可用令牌。您可以使用 $ client-> refreshToken($ refreshToken)来检索新令牌。我会称之为临时令牌。您还需要存储此临时令牌,因为它在一小时后也会过期,并注意它没有与之关联的刷新令牌。为了获得新的临时令牌,您需要使用之前使用的方法并使用第一个令牌的refreshtoken。

  //从数据库$ b中拉取标记$ b $ tokenquery =SELECT * FROM token WHERE type ='original'; 
$ tokenresult = mysqli_query($ cxn,$ tokenquery);
if($ tokenresult!= 0)
{
$ tokenrow = mysqli_fetch_array($ tokenresult);
提取($ tokenrow);
}
$ time_created = json_decode($ token) - > created;
$ t = time();
$ timediff = $ t- $ time_created;
echo $ timediff。< br>;
$ refreshToken = json_decode($ token) - > refresh_token;


//启动google客户端注释:
$ client = new Google_Client();
$ client-> setApplicationName('');
$ client-> setScopes(array());
$ client-> setClientId('');
$ client-> setClientSecret('');
$ client-> setRedirectUri('');
$ client-> setAccessType('offline');
$ client-> setDeveloperKey('');

//在过期时重置令牌
if(($ timediff> 3600)&&($ token!=''))
{
echo $ refreshToken < / BR> 中。
$ refreshquery =SELECT * FROM token WHERE type ='refresh';
$ refreshresult = mysqli_query($ cxn,$ refreshquery);
//如果刷新标记在那里...
if($ refreshresult!= 0)
{
$ refreshrow = mysqli_fetch_array($ refreshresult);
extract($ refreshrow);
$ refresh_created = json_decode($ token) - > created;
$ refreshtimediff = $ t- $ refresh_created;
echoRefresh Time Diff:。$ refreshtimediff。< / br>;
// if refresh token is expired
if($ refreshtimediff> 3600)
{
$ client-> refreshToken($ refreshToken);
$ newtoken = $ client-> getAccessToken();
echo $ newtoken。< / br>;
$ tokenupdate =更新令牌SET令牌='$ newtoken'WHERE type ='refresh';
mysqli_query($ cxn,$ tokenupdate);
$ token = $ newtoken;
echo再次刷新;
}
//如果刷新标记未过期,则将标记设置为刷新标记
else
{
$ client-> setAccessToken($ token) ;
回声使用刷新的令牌,但不是时间;
}
}
//如果刷新标记不在那里...
else
{
$ client-> refreshToken($ refreshToken);
$ newtoken = $ client-> getAccessToken();
echo $ newtoken。< / br>;
$ tokenupdate =INSERT INTO token(type,token)VALUES('refresh','$ newtoken');
mysqli_query($ cxn,$ tokenupdate);
$ token = $ newtoken;
回声第一次刷新;
}
}

//如果令牌仍然不错。 ($ timediff< 3600)&($ token!=''))

$ client-> setAccessToken($ token);

}

$ service = new Google_DfareportingService($ client);


I've been playing around with the Google Analytics API (V3) and have run into som errors. Firstly, everything is set up correct and worked with my testing account. But when I want to grab data from another profile ID (Same Google Accont/GA Account) I get an 403 Error. The strange thing is that data from some GA accounts will return data whilst other generate this error.

I've revoked the token and authenticated one more time, and now it seems like I can grab data from all of my accounts. Problem solved? Not. As the access key will expire, I will run into the same issue again.

If I have understood things right, one could use the resfreshToken to get a new authenticationTooken.

The problem is, when I run:

$client->refreshToken(refresh_token_key) 

the following error is returned:

Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

I’ve checked the code behind the refreshToken method and tracked the request back to the "apiOAuth2.php" file. All parameters are sent correctly. The grant_type is hard coded to ‘refresh_token’ within the method, so it’s hard for me to understand what’s wrong. The parameter array looks like this:

Array ( [client_id] => *******-uqgau8uo1l96bd09eurdub26c9ftr2io.apps.googleusercontent.com [client_secret] => ******** [refresh_token] => 1\/lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY [grant_type] => refresh_token )

The procedure is as follows.

$client = new apiClient();
$client->setClientId($config['oauth2_client_id']);
$client->setClientSecret($config['oauth2_client_secret']);
$client->setRedirectUri($config['oauth2_redirect_uri']);
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setState('offline');

$client->setAccessToken($config['token']); // The access JSON object.

$client->refreshToken($config['refreshToken']); // Will return error here

Is this a bug, or have I completely misunderstood something?

解决方案

So i finally figured out how to do this. The basic idea is that you have the token you get the first time you ask for authentication. This first token has a refresh token. The first original token expires after an hour. After an hour you have to use the refresh token from the first token to get a new usable token. You use $client->refreshToken($refreshToken) to retrieve a new token. I will call this "temp token." You need to store this temp token as well because after an hour it expires as well and note it does not have a refresh token associated with it. In order to get a new temp token you need to use the method you used before and use the first token's refreshtoken. I have attached code below, which is ugly, but im new at this...

//pull token from database
$tokenquery="SELECT * FROM token WHERE type='original'";
$tokenresult = mysqli_query($cxn,$tokenquery);
if($tokenresult!=0)
{
    $tokenrow=mysqli_fetch_array($tokenresult);
    extract($tokenrow);
}
$time_created = json_decode($token)->created;
$t=time();
$timediff=$t-$time_created;
echo $timediff."<br>";
$refreshToken= json_decode($token)->refresh_token;


//start google client note:
$client = new Google_Client();
$client->setApplicationName('');
$client->setScopes(array());
$client->setClientId('');
$client->setClientSecret('');
$client->setRedirectUri('');
$client->setAccessType('offline');
$client->setDeveloperKey('');

//resets token if expired
if(($timediff>3600)&&($token!=''))
{
    echo $refreshToken."</br>";
    $refreshquery="SELECT * FROM token WHERE type='refresh'";
    $refreshresult = mysqli_query($cxn,$refreshquery);
    //if a refresh token is in there...
    if($refreshresult!=0)
    {
        $refreshrow=mysqli_fetch_array($refreshresult);
        extract($refreshrow);
        $refresh_created = json_decode($token)->created;
        $refreshtimediff=$t-$refresh_created;
        echo "Refresh Time Diff: ".$refreshtimediff."</br>";
        //if refresh token is expired
        if($refreshtimediff>3600)
        {
            $client->refreshToken($refreshToken);
        $newtoken=$client->getAccessToken();
        echo $newtoken."</br>";
        $tokenupdate="UPDATE token SET token='$newtoken' WHERE type='refresh'";
        mysqli_query($cxn,$tokenupdate);
        $token=$newtoken;
        echo "refreshed again";
        }
        //if the refresh token hasn't expired, set token as the refresh token
        else
        {
        $client->setAccessToken($token);
           echo "use refreshed token but not time yet";
        }
    }
    //if a refresh token isn't in there...
    else
    {
        $client->refreshToken($refreshToken);
        $newtoken=$client->getAccessToken();
        echo $newtoken."</br>";
        $tokenupdate="INSERT INTO token (type,token) VALUES ('refresh','$newtoken')";
        mysqli_query($cxn,$tokenupdate);
        $token=$newtoken;
        echo "refreshed for first time";
    }      
}

//if token is still good.
if(($timediff<3600)&&($token!=''))
{
    $client->setAccessToken($token);
}

$service = new Google_DfareportingService($client);

这篇关于如何使用Google API客户端刷新令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆