Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing google analytics through nodejs

I'm using nodejs, and I would like to display some data from google analytics.

On google API explorer, I've find 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 pass my login through the url and then access my data ?

Thanks!

like image 919
sayam Avatar asked Sep 08 '13 01:09

sayam


People also ask

Does Google work on node JS?

Idiomatic libraries make writing Node. js apps for Google Cloud simple and intuitive. Libraries handle all the low-level details of communication with the server, including authenticating with Google so you can focus on your app.

Does Google Analytics have an API?

The Google Analytics Reporting API v4 provides programmatic methods to access report data in Google Analytics (Universal Analytics properties only). With the Google Analytics Reporting API, you can: Build custom dashboards to display Google Analytics data.

Do you need JavaScript for Google Analytics?

Without JavaScript, there will be no Google Analytics and Google Tag Manager won't be useful.


1 Answers

From the Google API console, you need to activate the Analytics API, and finally setup a Service Account, you'll then download a *.p12 file.

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

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

You'll be asked a password, it should be notasecret

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

Don't forget to add this address to your analytics account (see: Analytics Google API Error 403: "User does not have any Google Analytics Account")

You should be good to go with the following snippet:

var googleapis = require('googleapis'),
    JWT = googleapis.auth.JWT,
    analytics = googleapis.analytics('v3');

var SERVICE_ACCOUNT_EMAIL = '[email protected]';
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);
    });
});
like image 128
xavier.seignard Avatar answered Oct 12 '22 19:10

xavier.seignard