Google Analytics(分析)Embed API php服务器端授权

时间:2018-12-09 17:48:30

标签: php api embed analytics server-side

我目前正在管理面板上添加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 :(得分:1)

快速修复为:

string* Split(string ss,char delimeter,int size)
{
    string *nums=new string[size];
    int index_c, index_sw=0;
    for (int i = 0; i < size; i++)
    {
        for(unsigned int j=0;j<ss.length();j++)
        {
            if (ss.at(j) == delimeter)
            {
                index_c = j;
                nums[i] = ss.substr(index_sw, index_c);
                index_sw += index_c;
                i++;
            }
        }
        break;
    }
    return nums;
}