每小时获取 Google 分析数据(通过 crone)

Get Google analytics data every hour (by crone)

我使用以下 API 代码从 Google 分析中获取数据。 但现在我需要拆分它,因为我需要获得用户授权,然后每小时(无需请求其他许可)从不同的服务器创建一个 crone 作业以获取 GA 数据。

应该做出哪些改变?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <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>



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



<script>
  // Replace with your view ID.
  var VIEW_ID = 'ga:104831427';

  // 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"
          }
        ],
        "dimensions": [
            { "name": "ga:date" }
        ]
          }
        ]
      }
    }).then(displayResults, console.error.bind(console));
  }

 function displayResults(response) {
   
var formattedJson = JSON.stringify(response.result, null, 2);

window.parent.postMessage({formattedJson:(formattedJson)}, "my-domain.com"); 
  }


</script>

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

</body>
</html>

您可以使用 Google SuperProxy 为您获取结果 https://developers.google.com/analytics/solutions/google-analytics-super-proxy

此外,您可以使用以下方法扩展令牌:

https://accounts.google.com/o/oauth2/token?client_id=CLIENT_ID
&client_secret=CLIENT_SECRET
&refresh_token=REFRESH_TOKEN
&grant_type=refresh_token

有关如何操作的更多详细信息,请参见此处:http://thisistony.com/blog/googleanalytics/google-analytics-api-oauth-ever-wondered-how-to-get-the-access_token/