Authentication using the Google Analytics API with Javascript

This is a first part of tutorial in which I am going to explain how to interact with Google Analytics API, request data and use it in your user interface.

At first I will be looking in all the steps needed to obtain permissions and keys to work with Google Analytics API and I will explain how to do user authentication using the Google APIs Client Library for JavaScript.

To start using any of Google’s provided APIs, you need to create a new project in the Google Developers Console.

Getting permission to use Analytics API is easy, you simply need to activate it. To do this, go to the menu API & AUTH and select APIs under it, find Analytics API in a list and turn it on.

Next select Credentials under API & AUTH and create your own API credentials. These will be needed to do authentication and request data from it.

Click on a Create new Client ID and for the application type choose web application, fill in your website url in javascript origins (if your website is accessible from more than one aliases – e.g. with and without “www”, add both). Authorized redirect url this time won’t be needed. Click on the button Configure consent screen, fill in your site information and finally click on button create Client ID to finish the action.

Consent screen is a screen that will be shown to the users to get their consent prior your site will try to request any data from their Google Analytics accounts.

Next create Public API access key. Choose as key type browser key, put in allowed referrers your site url *example.com and create it.

 

Now we can move on to coding part. This part is based on Hello Analytics API tutorial by Google. So lets dig in. Create a login button in your UI to interact with, create and include a javascript file that will handle authorization named google_analytics_api_v3_auth.js and load the Google APIs Client Library for Javascript, which is required to make authorization and query the Analytics APIs. After the library has finished loading, the callback function specified with the onload parameter is executed to check user status on Google.

<button id="authorize-button" style="visibility: hidden;">Authorize</button>
<script src="google_analytics_api_v3_auth.js"></script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>

And here is the content of google_analytics_api_v3_auth.js file:

var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
// Callback funtion called after the Client Library has finished loading
function handleClientLoad() { 
  // 1. Set the API Key
  gapi.client.setApiKey(apiKey);
  // 2. Call the function that checks if the user  is Authenticated. This is defined in the next section
  window.setTimeout(checkAuth,1);
}
function checkAuth() { 
  // Call the Google Accounts Service to determine the current user's auth status.
  // Pass the response to the handleAuthResult callback function
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) { 
  if (authResult && !authResult.error) { 
// The user has authorized access
// Load the Analytics Client. This function is defined in the next section.
loadAnalyticsClient();
  } else { 
// User has not Authenticated and Authorized
handleUnAuthorized();
  }
}
// Authorized user
function handleAuthorized() { 
  var authorizeButton = document.getElementById('authorize-button');
  // Hide the 'Authorize' button
  authorizeButton.style.visibility = 'hidden';
  // Here you are in and ready to query Analytics API
}
// Unauthorized user
function handleUnAuthorized() { 
  var authorizeButton = document.getElementById('authorize-button');
  // Show the 'Authorize Button'
  authorizeButton.style.visibility = '';
  // When the 'Authorize' button is clicked, call the handleAuthClick function
  authorizeButton.onclick = handleAuthClick;
}
function handleAuthClick(event) { 
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
  return false;
}
function loadAnalyticsClient() { 
  // Load the Analytics client and set handleAuthorized as the callback function
  gapi.client.load('analytics', 'v3', handleAuthorized);
}

Now I will go through the code and explain what is happening there:

1. First – use your newly created values from API credentials to set the authorization config values of Client ID, API Key, and Scopes. The auth scope is https://www.googleapis.com/auth/analytics.readonly.

var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';

2. Next – there is a callback function handleClientLoad that is called after Google APIs JavaScript Client Library has been loaded. Function sets the API key and calls function checkAuth for find out a user status on Google.

// Callback funtion called after the Client Library has finished loading
function handleClientLoad() { 
    // 1. Set the API Key
  gapi.client.setApiKey(apiKey);
  // 2. Call the function that checks if the user is Authenticated. This is defined in the next section
  window.setTimeout(checkAuth,1);
}

3. Function checkAuth uses Client Library function gapi.auth.authorize to query Google Accounts service if user has been authenticated to Google and has given consent to your site to query his Analytics Account data. Results are passed to function handleAuthResult.

function checkAuth() { 
  // Call the Google Accounts Service to determine the current user's auth status.
  // Pass the response to the handleAuthResult callback function
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}

4. Next – there are several functions: handleAuthResult, handleAuthorized, handleUnauthorized, handleAuthClick and loadAnalyticsClient that, based on checkAuth response, does the following:

a) If the user is authenticated and has given authorization to access his data, the function loadAnalyticsClient is called to load the Analytics client and start querying.

b) If the user is not authenticated or has not authorized access, show the ‘Authorize’ button. When user clicks on the button, display Google Login and/or Application Consent screens. After user authenticates and authorizes access to his Analytics data, function loadAnalyticsClient is called to load Analytics client and function handleAuthorized hides “Authorize” button.

function handleAuthResult(authResult) { 
  if (authResult && !authResult.error) { 
    // The user has authorized access
    // Load the Analytics Client. This function is defined in the next section.
    loadAnalyticsClient();
  } else { 
    // User has not Authenticated and Authorized
    handleUnAuthorized();
  }
}
// Authorized user
function handleAuthorized() { 
  var authorizeButton = document.getElementById('authorize-button');
  // Hide the 'Authorize' button
  authorizeButton.style.visibility = 'hidden';
  // Here we are in and ready to query Analytics API
  console.log("Start to query Analytics API");
}
// Unauthorized user
function handleUnAuthorized() { 
  var authorizeButton = document.getElementById('authorize-button');
  // Show the 'Authorize Button'
  authorizeButton.style.visibility = '';
  // When the 'Authorize' button is clicked, call the handleAuthClick function
  authorizeButton.onclick = handleAuthClick;
}
function handleAuthClick(event) { 
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
  return false;
}
function loadAnalyticsClient() { 
  // Load the Analytics client and set handleAuthorized as the callback function
  gapi.client.load('analytics', 'v3', handleAuthorized);
}

That’s it! In the next tutorial I will give an example on how to query Analytics data and update your UI to show the results accordingly.

 

Laura Liekniņa

 
  • Jean

    Real good post, thank you !

  • dogelover

    Awesome! Thank you very much! So is second part ready yet?

  • Shawn Rebelo

    Why is it every time I come back to something Google has, it is always different? This is not even remotely the same to what it is now., Crap like this waste our time. Making users spend hours trying to figure you shit out because you cannot STOP changing things. Stop trying to grow up so damn fast! AND STOP CHANGING SO DAMN MUCH!

  • ɱoĥaɱed Pĥp

    Thank you very much

  • Aruna

    Hello Laura Canu you share next tutorial for how to query Analytics data and update UI?