Search code examples
google-apigoogle-oauthgoogle-analytics-api

Get Google analytics data every hour (by crone)


I used the following API code to get data from Google analytics. but now I need to split it because I need to get user authorization and then create a crone job every hour (without having to ask another permission) from a different server to get GA data.

What changes should be made?

<!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>

Solution

  • You can use the Google SuperProxy to fetch the results for you https://developers.google.com/analytics/solutions/google-analytics-super-proxy

    Furthermore, you can use the extend the token using the below:

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

    More details on how to do it is available here: http://thisistony.com/blog/googleanalytics/google-analytics-api-oauth-ever-wondered-how-to-get-the-access_token/