API 实时 Google 分析无法在客户端使用 js

API realtime Google analytics is not working on client side with js

我试过使用 API 密钥和 OAuth 2.0。

结果我有这个错误:http://prntscr.com/lov2pz

我应该使用哪个 API 键?我犯了什么错误?

<script>

    function start() {
        // 2. Initialize the JavaScript client library.
        gapi.client.init({
            'apiKey': 'XXXXXX',
            // clientId and scope are optional if auth is not required.

        }).then(function() {

            return gapi.client.request({
                'path': 'https://www.googleapis.com/analytics/v3/data/realtime?ids=ga%3A185730557&metrics=rt%3AactiveUsers&fields=totalsForAllResults',
            })
        }).then(function(response) {
            console.log(response.result);
        }, function(reason) {
            console.dir(reason);

            console.log('Error: ' + reason.result.error.message);
        });
    };
    gapi.load('client', start);

</script>

首先您需要了解私有数据和 public 数据之间的区别。 Public 数据是不为任何人所有的数据。例如,任何人都可以在 Youtube api 中搜索 YouTube 视频

Google 另一方面,分析数据是私有的,它归用户所有。 Api 密钥用于访问 public 数据而非私人数据。为了访问私人 google 分析数据,您需要以有权访问该数据的用户身份登录。

教程quickstart js 将向您展示如何使用 JS 访问 google anlaytics 数据,您必须实时更改它 api 我不是 js 开发人员,所以无法提供帮助,但您应该能够理解登录过程使用此示例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics Reporting API V4</title>
  <meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
  <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>

<h1>Hello Analytics Reporting API V4</h1>

<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>

<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>

<script>
  // Replace with your view ID.
  var VIEW_ID = '<REPLACE_WITH_VIEW_ID>';

  // Query the API and print the results to the page.
  function queryReports() {
    gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com/',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [
              {
                startDate: '7daysAgo',
                endDate: 'today'
              }
            ],
            metrics: [
              {
                expression: 'ga:sessions'
              }
            ]
          }
        ]
      }
    }).then(displayResults, console.error.bind(console));
  }

  function displayResults(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  }
</script>

<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>

</body>
</html>