如何使用刷新令牌在后台获取授权并获取访问令牌? [英] How to use refresh token to get authorized in background and getting access token?

查看:248
本文介绍了如何使用刷新令牌在后台获取授权并获取访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用refreshToken获取accessToken,下面我发布了我的代码,请别人指导我。



它来自我正在开发的wordpress插件,需要检索pageViews
和pagePath,所以不要使用可用的插件。



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

  if(isset($ this-> options ['authenication_code'])){//插件设置页面设​​置
global $ wpdb;
$ resultset = $ wpdb-> get_row('SELECT`refreshToken` FROM'。$ wpdb-> prefix。'analyticaAnalytics WHERE authenication_code =''。$ this-> options [authenication_code]。' ',ARRAY_A);
var_dump($ resultset ['refreshToken']); ($ client-> isAccessTokenExpired()){// boolean true
$ client-> refreshToken($ resultset ['refreshToken']); //从数据库
中检索refreshToken;
var_dump($ client); //变空白
}
}

../ google-api-php-client / src / Google / Auth / oauth2.php

  private function refreshTokenRequest($ params)
{
if(isset($ params ['assertion'])){

$ this-> client-> ; getLogger() - > info(
'OAuth2访问令牌刷新,带有签名的JWT断言授权。'
);
} else {
$ this-> client-> getLogger() - > info('OAuth2 access token refresh');


$ http = new Google_Http_Request(
self :: OAUTH2_TOKEN_URI,
'POST',
array(),
$ params
);

$ http-> disableGzip();
$ request = $ this-> client-> getIo() - > makeRequest($ http);
// var_dump($ request); exit; //响应400,无效授权
$ code = $ request-> getResponseHttpCode();

$ body = $ request-> getResponseBody();
if(200 == $ code){
$ token = json_decode($ body,true);
if($ token == null){
抛出新的Google_Auth_Exception(不能json解码访问令牌); $!

$ b if(!isset($ token ['access_token'])||!isset($ token ['expires_in'])){
抛出新的Google_Auth_Exception(无效的标记格式);
}

if(isset($ token ['id_token'])){
$ this-> token ['id_token'] = $ token ['id_token']] ;
}
$ this-> token ['access_token'] = $ token ['access_token'];
$ this-> token ['expires_in'] = $ token ['expires_in'];
$ this-> token ['created'] = time();
} else {
抛出新的Google_Auth_Exception(刷新OAuth2令牌时出错,消息:'$ body',$ code);


$ / code>

花了很多时间后,我得到的错误是response code 400 for $ request = $ this-> client-> getIo() - > makeRequest($ http); 并且这是无效授权。



完整代码

$ b $我解决了这个问题,我们需要将refreshToken存储在我们的数据库中,并使用该refreshToken,我们可以得到另一个accessToken。它可以是

 <?php 
$ client = new Google_Client ();
$ client-> setAuthConfigFile(plugin_dir_url(__FILE__)。'/client_secrets.json');
$ client-> setRedirectUri(site_url()。'/wp-admin/admin.php?page=analytica-admin-settings');
$ client-> addScope(Google_Service_Analytics :: ANALYTICS_READONLY);
$ client-> setIncludeGrantedScopes(true);
$ client-> setAccessType('offline');
if(isset($ _GET ['code'])){

if($ client-> isAccessTokenExpired()){

$ client-> ;认证($ _ GET [ '代码']);

$ accessToken = $ client-> getAccessToken();
$ refreshToken = $ client-> getRefreshToken();

$ analytica_tokens = json_encode(array('time'=> current_time('mysql'),'accessToken'=> $ accessToken,'refreshToken'=> $ refreshToken));
update_option('analytica_tokens',$ analytica_tokens);
}
} else {
$ resultset = json_decode(get_option('analytica_tokens'));
$ b $ if($ client-> isAccessTokenExpired()){
if(isset($ resultset)){
$ refreshToken = $ resultset-> refreshToken;
$ client-> refreshToken($ refreshToken);
$ accessToken = $ client-> getAccessToken();
$ analytica_tokens = json_encode(array('time'=> current_time('mysql'),'accessToken'=> $ accessToken,'refreshToken'=> $ refreshToken));
update_option('analytica_tokens',$ analytica_tokens);
} else {
echo'您需要重新授权应用程序以获取分析报告。
}
}
}
$ auth_url = $ client-> createAuthUrl();
?>
< a class =connect-to-google-analyticshref ='<?php echo $ auth_url; ?>'id =loginText>连接到您的Google Analytics帐户< / a>
<?php
if(isset($ accessToken)){
$ _SESSION ['access_token'] = $ accessToken? $ accessToken:$ refreshToken;
$ client-> setAccessToken($ _ SESSION ['access_token']);
//创建一个授权的分析服务对象。
$ analytics =新Google_Service_Analytics($ client);

//获取授权用户的第一个视图(配置文件)ID。
$ profile = $ this-> getFirstProfileId($ analytics);

//从Core Reporting API获取结果并打印结果。
$ this-> results = $ this-> getResults($ analytics,$ profile);
}
?>


I am trying to get accessToken using refreshToken, below I have posted my code please someone guide me.

It is from a wordpress plugin I am developing, I only need to retrieve pageViews and pagePath so not preferring using a available plugin.

Taken reference from Use OAuth Refresh Token to Obtain New Access Token - Google API

 if( isset( $this->options['authenication_code'] ) ){   //plugin setting page settings 
                global $wpdb;
                $resultset = $wpdb->get_row( 'SELECT `refreshToken` FROM ' . $wpdb->prefix . 'analyticaAnalytics WHERE authenication_code ="' . $this->options["authenication_code"] . '"', ARRAY_A );
                var_dump( $resultset['refreshToken'] ); //retrieved refreshToken from database
                if ($client->isAccessTokenExpired()) {              //boolean true
                    $client->refreshToken( $resultset['refreshToken'] ); 
                    var_dump( $client );//getting blank
                }
            }

../google-api-php-client/src/Google/Auth/oauth2.php

private function refreshTokenRequest($params)
  { 
    if (isset($params['assertion'])) {

      $this->client->getLogger()->info(
          'OAuth2 access token refresh with Signed JWT assertion grants.'
      );
    } else {
        $this->client->getLogger()->info('OAuth2 access token refresh');
    }

    $http = new Google_Http_Request(
        self::OAUTH2_TOKEN_URI,
        'POST',
        array(),
        $params
    );

    $http->disableGzip();
    $request = $this->client->getIo()->makeRequest($http);
    //var_dump( $request );exit;//response 400, invalid grant
    $code = $request->getResponseHttpCode();

    $body = $request->getResponseBody();
    if (200 == $code) {
      $token = json_decode($body, true);
      if ($token == null) {
        throw new Google_Auth_Exception("Could not json decode the access token");
      }

      if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
        throw new Google_Auth_Exception("Invalid token format");
      }

      if (isset($token['id_token'])) {
        $this->token['id_token'] = $token['id_token'];
      }
      $this->token['access_token'] = $token['access_token'];
      $this->token['expires_in'] = $token['expires_in'];
      $this->token['created'] = time();
    } else {
      throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
    }
  }

After spending a lot of time I got the error is responsecode 400 for $request = $this->client->getIo()->makeRequest($http); and that is invalid grant.

full code

解决方案

This is how , I solved the problem, We need to store the refreshToken in our database and using that refreshToken, We can get another accessToken .which can be used to get the result and it does not need another authentication .

<?php
        $client = new Google_Client();
        $client->setAuthConfigFile(plugin_dir_url( __FILE__ ) . '/client_secrets.json');
        $client->setRedirectUri( site_url() . '/wp-admin/admin.php?page=analytica-admin-settings');
        $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
        $client->setIncludeGrantedScopes(true);
        $client->setAccessType('offline');
        if ( isset( $_GET['code'] )) {

            if($client->isAccessTokenExpired()){

                $client->authenticate($_GET['code']);

                $accessToken = $client->getAccessToken();
                $refreshToken = $client->getRefreshToken();

                $analytica_tokens = json_encode( array( 'time' => current_time( 'mysql' ),'accessToken' =>  $accessToken, 'refreshToken' => $refreshToken ) );
                update_option( 'analytica_tokens', $analytica_tokens );
            } 
        } else {
            $resultset = json_decode(get_option('analytica_tokens'));

            if ($client->isAccessTokenExpired()) {
                if( isset( $resultset ) ){
                    $refreshToken = $resultset->refreshToken;
                    $client->refreshToken( $refreshToken );
                    $accessToken = $client->getAccessToken();           
                    $analytica_tokens = json_encode( array( 'time' => current_time( 'mysql' ), 'accessToken' =>  $accessToken, 'refreshToken' => $refreshToken ) );
                    update_option( 'analytica_tokens', $analytica_tokens );
                } else {
                    echo 'You need to reauthorize the application to get the analytics report.';
                }
            }
        }
        $auth_url = $client->createAuthUrl();
        ?>
         <a class="connect-to-google-analytics" href='<?php echo $auth_url; ?>'  id="loginText">Connect To Your Google Analytics Account </a>
        <?php
        if( isset($accessToken) ){
            $_SESSION['access_token'] = $accessToken ? $accessToken : $refreshToken;
            $client->setAccessToken($_SESSION['access_token']);
            // Create an authorized analytics service object.
            $analytics = new Google_Service_Analytics($client);

            // Get the first view (profile) id for the authorized user.
            $profile = $this->getFirstProfileId($analytics);

            // Get the results from the Core Reporting API and print the results.
            $this->results = $this->getResults($analytics, $profile);
        }
        ?>

这篇关于如何使用刷新令牌在后台获取授权并获取访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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