7

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!

bugmagnet
  • 7,631
  • 8
  • 69
  • 131
sayam
  • 163
  • 2
  • 14
  • Are you actually putting your API key here? `&key={YOUR_API_KEY}` – datasage Sep 08 '13 at 22:26
  • Yes I did. But seems that I needed token. I use request to call `https://www.googleapis.com/analytics/v3/data/ga?ids=ga:XXXXX88&metrics=ga:visits&start-date=2013-08-17&end-date=2013-09-15&access_token=XXXXXXXX&access_type_token=bearer` and everything works. – sayam Sep 08 '13 at 23:57
  • But when I try to refresh the token, using request on `https://accounts.google.com/o/oauth2/token?client_secret=XXX&grant_type=refresh_token&refresh_token=YYYY&client_id=ZZZZ` I get `error, invalid request.` – sayam Sep 09 '13 at 00:39

4 Answers4

11

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 = '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);
    });
});
Community
  • 1
  • 1
xavier.seignard
  • 11,254
  • 13
  • 51
  • 75
0

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

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

arami
  • 593
  • 2
  • 6
  • 19
  • I finally succeeded, using request.get. But still, I'll have a lookt at this library, thanks. – sayam Dec 06 '13 at 09:36
0

@xavier.seignard I follow your snippet but with modifications because I'm using a json file instead of p12 (code below). But I have a doubt, I'm developing a restful backend in nodejs. In this case, isn't it necessary to put the ga.get function inside the app.use() to obtain analytics information for every request that is made?

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

Below I have mentioned step by step process for Accessing google analytics through nodejs:

For more details : How To Use Google Analytics Reporting API With Nodejs

Install googleapis package

npm i googleapis

Import const { google } = require('googleapis')

This is sample scripts for getting total views in last month:

const { google } = require("googleapis");

const scopes = "https://www.googleapis.com/auth/analytics.readonly";

const jwt = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  process.env.PRIVATE_KEY.replace(/\\n/g, "\n"),
  scopes
);
const view_id = "Your_View_ID";

async function getViews(){
  try {
    await jwt.authorize();

    const response = await google.analytics("v3").data.ga.get({
      auth: jwt,
      ids: "ga:" + view_id,
      "start-date": "30daysAgo",
      "end-date": "today",
      metrics: "ga:pageviews",
    });

    console.log(response);

  } catch (err) {
     console.log(err);
  }
};`
jignesh kumar
  • 409
  • 1
  • 4
  • 6