Node: Google Analytics data via service account

2019-04-02 02:05发布

Update: I've since turned the code into an NPM module.

I've worked my way through created a JWT token for a service account, and I can access user data, but I want to get to my analytics data to use it to drive content on my website.

Note: I don't know if there is a better way than this, but the the existing npm tools seem to require that you enter your password. As a result I end up using REST calls rather the gapi tools.

This is the error I get

{ error: 
   { errors: [ [Object] ],
     code: 403,
     message: 'User does not have any Google Analytics account.' } }

Here is the code I am using which is working for user data.

var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

var scopes = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/analytics.readonly'
];

var d = new Date();
var seconds = d.getTime() / 1000 + 60*59;

var SERVICE_CLIENT_ID = "xxxxxxx-0h21osagsg02eqk45me6ts7jn3kf0vfr.apps.googleusercontent.com";
var SERVICE_EMAIL     = "xxxxxxx-0h21osagsg02eqk45me6ts7jn3kf0vfr@developer.gserviceaccount.com"

var claim_set = {
    "iss": SERVICE_EMAIL,
    "scope": 'https://www.googleapis.com/auth/analytics.readonly',
    "aud": 'https://www.googleapis.com/oauth2/v3/token',
    "exp":seconds,
    "iat":seconds
};

var algorithm = {"alg":"RS256","typ":"JWT"};
var private_key = fs.readFileSync('privatekey.pem');

var signature = jwt.sign(claim_set, private_key, { algorithm: algorithm.alg});

var post_obj = {
    grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
    assertion: signature
};

request.post({
    url:'https://www.googleapis.com/oauth2/v3/token',
    form: post_obj
}, function(err, data) {
    if (err) throw err;
    var body = JSON.parse(data.body);
    var token = body.access_token;
    // console.log(token);
    console.log("Token: ",token);


    var auth_obj = {
        'auth': {
            'bearer': token
        }
    };
    // THIS CODE DOES RETURN INFORMATION
    // request.get('https://www.googleapis.com/plus/v1/people/me', auth_obj, function(err, data) {
    //  if (err) throw err;
    //  console.log(JSON.parse(data.body));
    // });

    var report = {
        'ids': 'ga:78624107',
        'start-date': '2014-10-01',
        'end-date': '2014-12-31',
        'metrics': 'ga:sessions,ga:bounces'
    };
    var report2 = 'metrics=ga%253Ausers&start-date=2015-02-24&end-date=2015-03-10&max-results=50'
    var report3 = 'ids=ga:78624107&start-date=2015-02-24&end-date=2015-03-10&metrics=ga:users'

    request.get('https://www.googleapis.com/analytics/v3/data/ga?'+report3, auth_obj, function(err, data) {
        if (err) throw err;
        console.log(JSON.parse(data.body));
    });
});

1条回答
聊天终结者
2楼-- · 2019-04-02 02:50

A service account by default does not have a Google Analytics account.

Go into Google Analytics website the Admin section add the Service account email address as a user at the ACCOUNT level, it must be at the account level. Then the service account will have access to read your Google analytics data.

查看更多
登录 后发表回答