tumelo tumelo - 1 month ago 26
Node.js Question

google analytics api node.js

I'm trying to call the google analytics api in node. Can anybody tell me what I'm doing wrong? I'm getting 'path.replace is not a function' in node_modules/mime/mime.js, but I'm certain the problem is with my auth. (my log is not being hit btw)

const
gapi = require ("googleapis"),
profileid = '000000000',
key = require ('./key.json'),
email = 'email@email.com',
scopes = ['https://www.googleapis.com/auth/analytics', 'https://www.googleapis.com/auth/analytics.readonly'],
jwt = new gapi.auth.JWT (email, key, null, scopes, null);

gapi.analytics ('v3').data.ga.get ({
'auth': jwt,
'ids': 'ga:' + profileid,
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:pageviews'
}, function (err, result) {
console.log (err, result);
});


UPDATE: I tried to use an API key instead like so. In this case my log does get hit. But I get a 'Login Required' error.

const
gapi = require ("googleapis"),
API_KEY = 'IzaSyDbIBVkt5kia3CJ3w2Y3-nsLHDpSruERkw';

gapi.analytics ('v3').data.ga.get ({
'auth': API_KEY,
'ids': 'ga:' + profileid,
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:pageviews'
}, function (err, result) {
console.log (err, results);
});


this oauth playground https://developers.google.com/oauthplayground/ leads me to believe you need a google analytics login and scope to get an authorization code. And with the authorization code you can get an access token. And once you have that you can simply make the request with parameters to get what you need. The problem is getting it in code.

The code snippets I've seen that involve getting the Authorization code do it in a way that has the user get it from a consent page (like here https://github.com/google/google-api-nodejs-client#retrieve-authorization-code), but I'm just trying to do a server to server app, and I'm not getting user data so I shouldn't need permission from a user.

Answer

I got the first method to work with the following changes.

  1. flipped the 2nd and 3rd arguments in the JWT function
  2. passed in the private_key from the json file instead of the entire file
  3. used the email from the json file instead of my google email
  4. made new user in google analytics with the given email

    const
      gapi      = require ("googleapis"),
      profileid = '000000000',
      key       = require ('./key.json'),
      scopes    = 'https://www.googleapis.com/auth/analytics.readonly',
      jwt       = new gapi.auth.JWT (key.client_email, null, key.private_key, scopes);
    
    jwt.authorize (function (err, response) {
    
      gapi.analytics ('v3').data.ga.get ({
        'auth': jwt,
        'ids': 'ga:' + profileid,
        'start-date': '30daysAgo',
        'end-date': 'today',
        'metrics': 'ga:pageviews'
      }, function (err, result) {
        console.log (err, result);
      });
    
    });
    
Comments