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);
});
});