Access to Google analytics without a consent page using JavaScript

I am creating a toolbar using Atlasboard .

I need to access Google Analytics data, such as pageviews, etc., where I will run some of the queries shown here .

Is there a way to access my Google Analytics data without this consent page? enter image description here

I am using google-api-nodejs-client api.

I found this post where someone mentions using a service account. But I still can't find work in JavaScript.

Any help would be great!

+8
javascript google-analytics dashboard atlasboard
source share
3 answers

I finally managed to find a solution to this problem !!! Here is the solution :)

It is assumed that you already have a Google Analytics account that has site data such as submissions, and request and googleapis .

First you need to create a Google console account at console.developers.google.com .

In the Google console:

  • Create a project with a suitable name, for example. dashboard1.
  • Open the API and Auth from the menu on the left -> Open the API API tab -> enable analytics API.
  • Open the credentials tab -> create a new customer ID -> select a service account
  • The key should be loaded automatically β†’ click on the key and follow the instructions β†’ the default password is β€œnotasecret" β†’ it gives the .pem file
  • The service account will have an email address, for example. 123434234324f34f5fd4ww5f@developer.gserviceaccount.com

Now go to your Google Analytics account at www.google.com/analytics :

In the control panel task (server side using nodejs):

Use this code:

var fs = require('fs'), crypto = require('crypto'), request = require('request'); // This is an external module (https://github.com/mikeal/request) var authHeader = { 'alg': 'RS256', 'typ': 'JWT' }, authClaimSet = { 'iss': '#######SERVICE ACCOUNT EMAIL GOES HERE#######', // Service account email 'scope': 'https://www.googleapis.com/auth/analytics.readonly', // We MUST tell them we just want to read data 'aud': 'https://accounts.google.com/o/oauth2/token' }, SIGNATURE_ALGORITHM = 'RSA-SHA256', SIGNATURE_ENCODE_METHOD = 'base64', GA_KEY_PATH = '#######DIRECTORY TO YOUR .PEM KEY#######', //finds current directory then appends private key to the directory gaKey; function urlEscape(source) { return source.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''); } function base64Encode(obj) { var encoded = new Buffer(JSON.stringify(obj), 'utf8').toString('base64'); return urlEscape(encoded); } function readPrivateKey() { if (!gaKey) { gaKey = fs.readFileSync(GA_KEY_PATH, 'utf8'); } return gaKey; } var authorize = function(callback) { var self = this, now = parseInt(Date.now() / 1000, 10), // Google wants us to use seconds cipher, signatureInput, signatureKey = readPrivateKey(), signature, jwt; // Setup time values authClaimSet.iat = now; authClaimSet.exp = now + 60; // Token valid for one minute // Setup JWT source signatureInput = base64Encode(authHeader) + '.' + base64Encode(authClaimSet); // Generate JWT cipher = crypto.createSign('RSA-SHA256'); cipher.update(signatureInput); signature = cipher.sign(signatureKey, 'base64'); jwt = signatureInput + '.' + urlEscape(signature); // Send request to authorize this application request({ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, uri: 'https://accounts.google.com/o/oauth2/token', body: 'grant_type=' + escape('urn:ietf:params:oauth:grant-type:jwt-bearer') + '&assertion=' + jwt }, function(error, response, body) { if (error) { console.log(error); callback(new Error(error)); } else { var gaResult = JSON.parse(body); if (gaResult.error) { callback(new Error(gaResult.error)); } else { callback(null, gaResult.access_token); console.log(gaResult); console.log("Authorized"); ###########IF IT REACHES THIS STAGE THE ACCOUNT HAS BEEN AUTHORIZED############## } } }); }; var request = require('request'), qs = require('querystring'); authorize(function(err, token) { if (!err) { // Query the number of total visits for a month ############requestConfig################ var requestConfig = { 'ids': 'ga:#######PROJECT ID GOES HERE#######', 'dimensions': 'ga:country', 'metrics': 'ga:users', 'sort': '-ga:users', 'start-date': '2014-04-08', 'end-date': '2014-04-22', 'max-results': '10' }; request({ method: 'GET', headers: { 'Authorization': 'Bearer ' + token // Here is where we use the auth token }, uri: 'https://www.googleapis.com/analytics/v3/data/ga?' + qs.stringify(requestConfig) }, function(error, resp, body) { console.log(body); var data = JSON.parse(body); console.log(data); }); } }); 

REMEMBER TO LOG IN TO YOUR OWN EMAIL ACCOUNT, GA_KEY_PATH AND IDS

Google Analytics data can be modified by modifying requestConfig. I used this Google Analytics query tool to help me: http://ga-dev-tools.appspot.com/explorer/

Then the data should be displayed on the console.

Hope this helps :)

+10
source share

In addition to smj2393's answer, and for those who want to create a specific URL to receive the JSON provided by the Google Analytics API, an example Node Express route is provided. You need to install the official Node npm API package ( https://www.npmjs.org/package/googleapis ).

 var google = require('googleapis'); var analytics = google.analytics('v3'); var ENV = process.env; //get key.p12 in Google Developer console //Extract it with : openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem //Get GOOGLE_API_EMAIL in Google Developer console (Service Account) //Get GOOGLE_ANALYTICS_VIEW_ID in Google Analytics Console : Admin -> View -> View Parameters -> View ID //Add GOOGLE_API_EMAIL in the Google Analytics account users var authClient = new google.auth.JWT( ENV.GOOGLE_API_EMAIL, './keys/googlekey.pem', //path to .pem null, // Scopes can be specified either as an array or as a single, space-delimited string ['https://www.googleapis.com/auth/analytics.readonly']); module.exports = function(req, res, next) { var startDate = (req.query.start_date) ? req.query.start_date : '7daysAgo'; var endDate = (req.query.end_date) ? req.query.end_date : 'yesterday'; authClient.authorize(function(err, tokens) { if (err) { console.log(err); return; } // Make an authorized request to list analytics files. // list of dimensions and metrics : https://developers.google.com/analytics/devguides/reporting/core/dimsmets analytics.data.ga.get({ auth: authClient, "ids":'ga:'+ENV.GOOGLE_ANALYTICS_VIEW_ID, "start-date":startDate, "end-date":endDate, "metrics":"ga:sessions,ga:pageviews", "dimensions":"ga:deviceCategory" }, function(err, result) { console.log(err); console.log(result); if(!err){ res.json(result); } else{ next(); } }); }); } 

This route will show JSON representing the number of sessions and pageViews on the device (desktop, mobile phone and tablets). You can pass start_date or end_date with GET parameters.

I hope for this help.

+4
source share

Check out the google-analytics job in the Atlasboard Atlassian package. It uses the Google Node.js Client API npm package:

https://bitbucket.org/atlassian/atlasboard-atlassian-package/src/master/jobs/google-analytics/google-analytics.js?at=master&fileviewer=file-view-default

You can use it to communicate with both the regular and the classic Google Analytics APIs.

0
source share

All Articles