Skip to content

Instantly share code, notes, and snippets.

@lbdremy
Created February 25, 2013 17:50
Show Gist options
  • Save lbdremy/5031747 to your computer and use it in GitHub Desktop.
Save lbdremy/5031747 to your computer and use it in GitHub Desktop.
Using OAuth 2.0 for Server to Server Applications and the Google Analytics API with node.js.
/**
* Module dependencies
*/
var GA = require('googleanalytics'),
jwt = require('jwt-sign'),
request = require('superagent'),
fs = require('fs'),
privateKey = fs.readFileSync(process.env['GA_PATH_PRIVATE_KEY'] || __dirname + '/key/private.pem','utf8');
// Configuration
var PROFIL_ID = process.env['GA_PROFIL_ID'] || '49870159';
var EMAIL_ADDRESS = process.env['GA_EMAIL_ADDRESS'] || '[email protected]';
// JWT payload
var payload = {
'iss': EMAIL_ADDRESS,
'scope': 'https://www.googleapis.com/auth/analytics.readonly',
'aud':'https://accounts.google.com/o/oauth2/token',
'exp': ~~(new Date().getTime() / 1000) + (30 * 60),
'iat': ~~(new Date().getTime() / 1000 - 60)
};
// Sign the payload with the private key
var signed = jwt.sign(payload,privateKey);
// Request the access token
request.post('https://accounts.google.com/o/oauth2/token')
.set('Content-Type','application/x-www-form-urlencoded')
.set('Accept','application/json')
.send({
'grant_type' : 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' : signed
})
.end(function(err, res){
if(err) return console.error(err);
var accessToken = res.body.access_token;
if(!accessToken) throw new Error('access token is empty!');
// Google analytics client
var ga = new GA.GA({
'token' : accessToken
});
var options = {
'ids': 'ga:' + PROFIL_ID,
'start-date': '2013-02-01',
'end-date': '2013-02-25',
'dimensions': 'ga:hostname', //ga:customVarValue(n)
'metrics': 'ga:visitors,ga:newVisits,ga:visits,ga:pageviews'
//'sort': ''
};
// Request the report
ga.get(options, function(err, entries) {
if(err) return console.error(err);
console.log(JSON.stringify(entries,null,'\t'));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment