Access google analytics through nodejs

I am using nodejs and I would like to display some data from Google Analytics.

In google API explorer, I found this url to get my data:

https://www.googleapis.com/analytics/v3/data/ga?ids=ga%XXXXX&start-date=2013-08-17&end-date=2013-09-15&metrics=ga%3Avisits&key={YOUR_API_KEY} 

However, if I access this URL, I get:

 {"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}} 

How can I go through my login via a URL and then access my data?

Thanks!

+6
source share
3 answers

In the Google API console, you need to activate the Google Analytics API and finally configure the service account, then you upload the *.p12 file.

From this *.pem file, you need to convert it to a *.pem file, to do this, do the following:

openssl pkcs12 -in XXXXX.p12 -nocerts -nodes -out XXXXX.pem

You will be given a password, it must be notasecret

Now you have the *.pem file that you need, and the email account is the one that appears in the google api console as EMAIL ADDRESS .

Remember to add this address to your analytics account (see: Google Analytics Google Analytics 403: “User does not have a Google Analytics account” )

You should be ready to go with the following snippet:

 var googleapis = require('googleapis'), JWT = googleapis.auth.JWT, analytics = googleapis.analytics('v3'); var SERVICE_ACCOUNT_EMAIL = ' XXXXXXXXXX@developer.gserviceaccount.com '; var SERVICE_ACCOUNT_KEY_FILE = __dirname + '/key.pem'; var authClient = new JWT( SERVICE_ACCOUNT_EMAIL, SERVICE_ACCOUNT_KEY_FILE, null, ['https://www.googleapis.com/auth/analytics.readonly'] ); authClient.authorize(function(err, tokens) { if (err) { console.log(err); return; } analytics.data.ga.get({ auth: authClient, 'ids': 'ga:XXXXXXXX', 'start-date': '2015-01-19', 'end-date': '2015-01-19', 'metrics': 'ga:visits' }, function(err, result) { console.log(err); console.log(result); }); }); 
+11
source

Are you setting Content-Type to application / x-www-form-urlencoded?

If you're still stuck, it's worth noting that Google has released the nodejs (alpha) client library here: https://github.com/google/google-api-nodejs-client

0
source

@ xavier.seignard I follow your snippet, but with changes, because I use a json file instead of p12 (code below). But I doubt that I am developing a backful backend in nodejs. In this case, is it necessary to introduce the ga.get function in app.use () to get analytics information for each request made?

 var key = require('filename.json'); var authClient = new JWT( key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/analytics.readonly']); 
0
source

Source: https://habr.com/ru/post/953408/


All Articles