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,8298 gold badges74 silver badges143 bronze badges
asked Sep 8, 2013 at 1:20
3
  • Are you actually putting your API key here? &key={YOUR_API_KEY} Commented Sep 8, 2013 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. Commented Sep 8, 2013 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. Commented Sep 9, 2013 at 0:39

4 Answers 4

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 = '[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);
 });
});
answered Jan 20, 2015 at 0:24
Sign up to request clarification or add additional context in comments.

Comments

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

answered Dec 5, 2013 at 1:50

1 Comment

I finally succeeded, using request.get. But still, I'll have a lookt at this library, thanks.
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']);
answered Jun 14, 2016 at 19:02

Comments

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);
 }
};`
answered Sep 17, 2022 at 14:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.