如何使用刷新令牌在后台获得授权并获取访问令牌?

How to use refresh token to get authorized in background and getting access token?

我正在尝试使用 refreshToken 获取 accessToken,下面我发布了我的代码,请有人指导我。

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

参考自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);
    }
  }

花了很多时间后,我得到的错误是 $request = $this->client->getIo()->makeRequest($http); 的响应代码 400,这是无效授权。

full code

就是这样,我解决了这个问题,我们需要将 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->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);
        }
        ?>