Skip to content Skip to sidebar Skip to footer

Google Analytics Api Access With A Service Account

Can I access Google Analytics data using a service account in a client-side application? If not, are there other ways of achieving the same outcome? Must be entirely client-side, a

Solution 1:

Yes you can in https://code.google.com/apis/console make sure you say that its a Service account it will give you a key file to download. With that you dont need a user to click ok to give you access.

For a service acccount to work you need to have a key file. Anyone that has access to that key file will then be able to access your Analytics data. Javascript is client sided which means you will need to send the key file. See the Problem? You are handing everyone access to your account. Even if you could get a service account to work using javascript for security reasons its probably not a very good idea.

Solution 2:

You can use the official (and alpha) Google API for Node.js to generate the token. It's helpful if you have a service account.

On the server:

npm install -S googleapis

ES6:

import google from'googleapis'import googleServiceAccountKey from'/path/to/private/google-service-account-private-key.json'// see docs on how to generate a service accountconst googleJWTClient = new google.auth.JWT(
  googleServiceAccountKey.client_email,
  null,
  googleServiceAccountKey.private_key,
  ['https://www.googleapis.com/auth/analytics.readonly'], // You may need to specify scopes other than analyticsnull,
)

googleJWTClient.authorize((error, access_token) => {
   if (error) {
      returnconsole.error("Couldn't get access token", e)
   }
   // ... access_token ready to use to fetch data and return to client// even serve access_token back to client for use in `gapi.analytics.auth.authorize`
})

If you went the "pass the access_token back to client" route:

gapi.analytics.auth.authorize({
  'serverAuth': {
    access_token // received from server, through Ajax request
  }
})

Post a Comment for "Google Analytics Api Access With A Service Account"