Created
July 3, 2015 06:16
-
-
Save Znack/0c3eba2bd147375633a9 to your computer and use it in GitHub Desktop.
Google APIS for node.js OAuth2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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'); | |
var JWT = googleapis.auth.JWT; | |
var analytics = googleapis.analytics('v3'); | |
var SERVICE_ACCOUNT_EMAIL = '846839880765-av8j9skcv3fu31j0gb84gpgq1hbp1ah2@developer.gserviceaccount.com'; | |
var SERVICE_ACCOUNT_KEY_FILE = __dirname + '/AnonymID-0d3161b9e6fa.pem'; | |
var authClient = new JWT( | |
SERVICE_ACCOUNT_EMAIL, | |
SERVICE_ACCOUNT_KEY_FILE, | |
null, | |
['https://www.googleapis.com/auth/analytics'] | |
); | |
authClient.authorize(function(err, tokens) { | |
if (err) { | |
console.log(err); | |
return; | |
} | |
analytics.data.ga.get({ | |
auth: authClient, | |
'ids': 'ga:104704709', | |
'start-date': '2015-07-02', | |
'end-date': '2015-07-02', | |
'metrics': 'ga:visits', | |
}, function(err, result) { | |
console.log(err); | |
console.log(result); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment