Google Analytics API access with a service account

2019-07-19 03:06发布

问题:

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, and must not require users to authenticate (hence the desire to use a service account).

回答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.



回答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 account

const 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 analytics
  null,
)

googleJWTClient.authorize((error, access_token) => {
   if (error) {
      return console.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
  }
})