3600秒后获取新的acess_token

时间:2018-12-05 17:45:45

标签: google-analytics google-api google-analytics-api google-api-php-client service-accounts

我正在尝试使用Google Analytics(分析)API。我已经将创建的服务帐户电子邮件添加到相关Google Analytics(分析)帐户的用户列表中。

我得到了access_token和refresh_token。但是我不知道如何在3600秒后获得新的access_token,而无需客户端重新授权。

oauth2callback.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

index.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);

print_r($_SESSION['access_token']);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

允许访问后,令牌会正常生成。但是我想在3600秒后自动获得新的access_token,而客户端无需再次授予权限。

这可能吗?

print_r($_SESSION['access_token']);


Array
(
    [access_token] => ya29.GltpBl_Dkmt-uT9Z6t5aTSzKLmzsWP3xZCcVtRt8kLIOJj5M_TpLg-0x4Sm0eNxOLpdCahFy6Ec41nHnF-vhh-m3tbj7ecR-QHaR8vkP3ImYjuo_WPBLXBKMXCna
    [expires_in] => 3600
    [scope] => https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/plus.me
    [token_type] => Bearer
    [id_token] => eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ2M2ZlNDgwYzNjNTgzOWJiYjE1ODYxZTA4YzMyZDE4N2ZhZjlhNTYiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiI5NzI5NDE4MzY0MzctZ2o2ZmtxNHZ1NjU3dDkyMzhucDVyajY5NjRqZ3NyMWouYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI5NzI5NDE4MzY0MzctZ2o2ZmtxNHZ1NjU3dDkyMzhucDVyajY5NjRqZ3NyMWouYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDM3NzMzMDA1MzYwNTk3MzI0OTAiLCJlbWFpbCI6ImZhYnJpY2lvdmllaXJhLnN0ckBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6IndQcVUxc1I4c3Z6bFBBSWRUSjZoNGciLCJpYXQiOjE1NDQwMjg2MjEsImV4cCI6MTU0NDAzMjIyMX0.g_3w66FxAGViuXxFDGR2oErlo1yIMk376iDdOpgv8EfVz764hBywc-DuNXPE2y5p4nTd_y6oWbH7mK2DvFIGd7b_BLsNJJaZjJBFBHNk9Q1Z5VrpeZ9T1-0gQiXu0xS0pBdRnEtDwZN7qlL4_op6ojfHT02HbmyrlpdCbnp57LN5zJkufnL4VhQYp3Rqsui4ttL1VT0KBaHjzIzL6zWMuuMBdXKk9Ug6J1KuR0xCuWGytjb2y-YpsHVrgqvOfMEeAnxcpv6-ilUEpc-Mo4ZL4NGsDjK2BGFVCwfxZctzgERwSzYyH9P6g_raIJpqyXGvASOvkPJ7xHGI1wWO4QGsxA
    [created] => 1544028621
    [refresh_token] => 1/ifyxSjTnwv5kFMPcPEENx8kRWNSFmTYZUjMxcHJl8spoQqWdmaNh1ZjV3W2qR16W
)
1

2 个答案:

答案 0 :(得分:0)

您使用的代码不是服务帐户的代码。如果您将代码用于服务帐户,则无需担心刷新任何内容,因为它没有刷新令牌,它始终可以访问。

require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

ServiceAccount.php

答案 1 :(得分:0)

排序:

<?php
require_once __DIR__ . '/vendor/autoload.php';
$KEY_FILE_LOCATION = __DIR__ . '/service-account.json';
$client = new Google_Client();
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setAccessType('offline');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->refreshTokenWithAssertion();
$analytics = new Google_Service_Analytics($client);
$token = $client->getAccessToken();
?>
<!DOCTYPE html>
<html>
<head>
  <title>Embed API Demo</title>
  <style>
  body{
    overflow: hidden;
  }
  </style>
</head>
<body>

<!-- Step 1: Create the containing elements. -->

<div id="chart-1-container"></div>
<div id="chart-2-container"></div>

<!-- Step 2: Load the library. -->

<script>
(function(w,d,s,g,js,fs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
  js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>

<script>

gapi.analytics.ready(function() {

  /**
   * Authorize the user with an access token obtained server side.
   */
  gapi.analytics.auth.authorize({
    'serverAuth': {
      'access_token': '<?php echo $token['access_token']; ?>'
    }
  });


  /**
   * Creates a new DataChart instance showing sessions over the past 30 days.
   * It will be rendered inside an element with the id "chart-1-container".
   */
  var dataChart1 = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': 'ga:171325437', // <-- Replace with the ids value for your view.
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
      'metrics': 'ga:sessions,ga:users',
      'dimensions': 'ga:date'
    },
    chart: {
      'container': 'chart-1-container',
      'type': 'LINE',
      'options': {
        'width': '100%'
      }
    }
  });
  dataChart1.execute();


  /**
   * Creates a new DataChart instance showing top 5 most popular demos/tools
   * amongst returning users only.
   * It will be rendered inside an element with the id "chart-3-container".
   */
  var dataChart2 = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': 'ga:171325437', // <-- Replace with the ids value for your view.
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
      'metrics': 'ga:pageviews',
      'dimensions': 'ga:pagePathLevel1',
      'sort': '-ga:pageviews',
      'filters': 'ga:pagePathLevel1!=/',
      'max-results': 7
    },
    chart: {
      'container': 'chart-2-container',
      'type': 'PIE',
      'options': {
        'width': '100%',
        'pieHole': 4/9,
      }
    }
  });
  dataChart2.execute();

});
</script>
</body>
</html>