首页 文章

谷歌分析嵌入API php服务器端授权

提问于
浏览
0

我目前正致力于在管理员面板上添加Google Analytics图表 . 在console.developers.google.com上设置了服务帐户并下载了json密钥文件 . 问题是我收到“无效凭据”错误 .

预览错误:https://i.gyazo.com/7037c8ce12b6c18ff2c1a83f153891b6.png

PHP:

$credentials_file = BASE_PATH.'cms/xxxxxx-224915-f1a6ced8529f.json';
$client = new Google_Client();
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->setAuthConfig($credentials_file);
$client->useApplicationDefaultCredentials();
$client->fetchAccessTokenWithAssertion();
$accesstoken = $client->getAccessToken();
echo '<pre>';
print_r($accesstoken);
echo '</pre>';
$accesstoken = $accesstoken['access_token'];

print_r的结果:

Array
(
[access_token] => ya29.c.ElltBmCiGHIaslfJVEh1RYQ6xl5hpDs4IPDa-Lfqiv4VRMNUDYmZB97m7TXdmwe4fcM7XnepK2TLv5o10Jtopy1jvWRV769QG7hNoPU4nqWrkzsAVsxBgmb8nQ
[expires_in] => 3600
[token_type] => Bearer
[created] => 1544375409
)

javascript html:

<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>
    <div id="chart-1-container"></div>
    <div id="chart-2-container"></div>
<script>

gapi.analytics.ready(function() {

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


  /**
   * 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:186343526', // <-- 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:186343526', // <-- 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>

在下面的url上测试了访问令牌,它似乎工作正常 . https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=

{
  "issued_to": "105249894857195252623",
  "audience": "105249894857195252623",
  "scope": "https://www.googleapis.com/auth/analytics.readonly",
  "expires_in": 3127,
  "access_type": "offline"
}

1 回答

  • 0

    快速修复是:

    gapi.analytics.auth.authorize({
        'serverAuth': {
          'access_token': '<?php echo $accesstoken["access_token"]; ?>'
        }
      });
    

相关问题