Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate to Google Analytics Reporting API v4

I'm into trouble to authenticate to Google Analytics Reporting API v4 using Node.js client library. I tried all methods, starting with JWT (Service Tokens : JSON & P12), API Keys and OAuth 2.0, but i've never successfully been authenticated.

I activated the API in my developer console, created IDs and granted the rights on my google analytics property and view. I successfully get authorization and an access token for my service account but i don't know how to use it to authenticate to Analytics Reporting API v4.

I'm stuck in front of an 401 error message : "The request does not have valid authentication credentials". I tried using JWT impersonate user, but then the service account is unauthorized.

Using Node.js client library and JWT Authentication :

var google = require('googleapis.js');

var viewID = 'XXXXXXXXX'; // Google Analytics view ID
var key = require('service_account.json'); // Service account

var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/analytics.readonly'], null);
var oauth2Client = new google.auth.OAuth2();

jwtClient.authorize(function(err, result) {
  if (err) {
    console.log('Unauthorize');
    console.log(err);
    return;
  }

  oauth2Client.setCredentials({
    access_token: result.access_token
  });

  //Need to authenticate somewhere near here
  var analytics = google.analyticsreporting('v4');
  //Or here

  var req = {
    reportRequests: [
      {
        viewId: viewID,
        dateRanges: [
          {
            startDate: '2016-05-01',
            endDate: '2016-06-30',
          },],
        metrics: [
          {
            expression: 'ga:users',
          }, {
            expression: 'ga:sessions',
          },],
      },],
  };

  //Maybe here
  analytics.reports.batchGet(req,
    function(err, response) {
      if (err) {
        console.log('Fail');
        console.log(err);
        return;
      }
      console.log('Success');
      console.log(response);
    }
  );
});

Previous releases of Node.js client library seems to have a method to specify the client but it disappeared, maybe deprecated.

withAuthClient(oauth2Client)

I've tried to pass the client or the token in the API call or in the request, but none works.

google.analyticsreporting({ version: 'v4', auth: oauth2Client });
google.analyticsreporting({ version: 'v4', access_token: result.access_token });

Maybe it's a noob question but i don't know how to do it, i don't see anything related to Analytics Reporting v4 authentication in the google api or client library documentation, and most examples i found uses Google Analytics API v3.

If someone managed to successfully authenticate to Analytics Reporting API v4, please help :/

like image 561
belgacea Avatar asked Jun 13 '16 10:06

belgacea


People also ask

How do I authenticate Google Analytics?

Click on Authenticate button to open the authentication popup. Choose or login to your Google account,which you wish to connect with Google Analytics WD plugin. The popup window will ask for relevant permissions. Click Allow, then copy the authentication code which will be provided subsequently.

How do I enable Google Analytics API reporting?

To get started using Analytics API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials. To set up a new service account, do the following: Click Create credentials > Service account key.

How do I find my Google Analytics 4 ID?

Google Analytics 4 has changed recently and doesn't offer a view ID, which is essential in setting up a Google analytics connection in Channable. In order to find your view ID, you will have to revert your Google Analytics to be 'Universally formatted'.


1 Answers

Found out what I was missing :

  • Google APIs Client Library "Options" :

    google.options({ auth: oauth2Client }); //this one is not very optional
    
  • Unlike Google Analytics Reporting API v4 documentation, queries using the client library must have headers to specify a client for each requests (thanks to CVarisco who notice that, client library documentation isn't really accurate..) :

    var request ={
        'headers': {'Content-Type': 'application/json'},
        'auth': oauth2Client,
        'resource': req,
    };
    
like image 197
belgacea Avatar answered Nov 02 '22 00:11

belgacea