Create Google Analytics Report On Visualforce Page

Requirement:  Shows Google Analytics Report On Visualforce Page.

To  Shows Google Analytics Report  we  do  Google  Analytics Integration . Before going to the code first we will understand  the basics terms and functionality behind Google Analytics Integration.


To use the Analytics Reporting API v4 to request data, you must construct a ReportRequest object, which has these minimum requirements:

  • A valid view ID for the viewId field.
  • At least one valid entry in the dateRanges field.
  • At least one valid entry in the metrics field.

Here is the sample  ReportRequest Object

      "viewId": "XXXX",
      "dateRanges": [{"startDate": "2014-11-01", "endDate": "2014-11-30"}],
      "metrics": [{"expression": "ga:users"}]

In the above code we passes three variables

viewId: This is Analytics view Id  from which you want to get data . Every ReportRequest within a batchGetmethod must contain the same viewId.

How to get viewId:

You find the view id when you go to the admin section and look at the outer right column (which is labed “views”). Select the view you want to query from the dropdown and go to “view settings”, there you find the id. Or visit the query explorer while you are logged in to Google and select the view from the dropdow, this will also show the view id (and you can start testing queries right away).

dateRanges: Date Range define the time period of which you want to get google analaytics data.

  •  The request can have a maximum of 2 date ranges.
  • If there are two date ranges, there will be two set of metric values, one for the original date range and one for the second date range
  •  If a date range is not provided, the default date range is (startDate: current date – 7 days, endDate: current date – 1 day).

Metrices:  Metrics are quantitative measurements; every request requires at least one Metric object.

Most Common metrices are:







We can send metrices according to our need or type of data we want to  get from google analytics.

Dimensions:  Dimensions are attributes of your data. For example, the dimension ga:city indicates the city, for example, “Paris” or “New York”, from which a session originates.

Now after understanding google analytics  basics we move to the coding part

steps to be followed  : you need to follow the below steps To  Shows Google Analytics Report In VisualForce Page:

  1.  You need to register yourself to and then create an app. here we need to create an app because we need  ID and App Secret .Id and app are available only when you create an app
  2.  save secret keys ,google  credentials to custom setting(donot worry you will get secret keys and credentials after you develop app)  so that we can use it during integration.
  3.  Write Google Analytics  Integartion code in apex and get values from response body.
  4.  Use value or data you get from response in your vf page or  html page or in gauge chart.


  1.  Steps to register yourself to and create an app

1.1. Login to and open Click “Register”.
1.2. Click on My Apps –> Add New App –> Choose Website –> Enter the required details.
1.3. Your app will be listed under the My Apps dropdown. Choose your app. You will be able to see the App ID and App                        Secret. Don’t share these two with anyone.

2.  Save credentials and secret key to custom setting 

3.  Google Analytics  Integration :   Below is the code for google analytics integration 


public class yourcontroller {

public Integer ReportVisitorCount{get;set;}
public Integer WebSessionCount{get;set;}
public Integer WebUniqueVisitorCount{get;set;}
public Integer WebSessionDurationCount{get;set;}
public Integer Bounce{get;set;}
public Integer newUsers{get;set;}
public Integer organicSearches{get;set;}

public void getReportrCount()
    // these are variables we use to store data coming from google analytics
     ReportVisitorCount = 0 ;
     WebSessionCount = 0 ;
     WebUniqueVisitorCount = 0 ;
    WebSessionDurationCount = 0 ;
    Bounce = 0 ;
    newUsers = 0 ;
    organicSearches = 0 ;
        // Google_Analytics__c is custom setting that we are using to store  client secret, client_id and refresh token
        Google_Analytics__c myCS1 = Google_Analytics__c.getValues('getReportsWebSiteVisitorCount');
        String accesstoken='';
  // sending http request for access token 
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        HttpResponse res=new HttpResponse() ;
  res = h.send(req);
        JSONParser parser = JSON.createParser(res.getBody());
  // getting access token from response body by iteration over parser
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {
  // setting start date for next http request  strat date is the mandatory field with id and  metrices 
  Datetime dt =;
        String formattedDate = dt.format('YYYY-MM-dd');
        Datetime startdate=myCS1.Start_Date__c;
        String formatedStartDate=startdate.format('YYYY-MM-dd');
  // send http request to get data from google analytics 
        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setHeader('Authorization','Bearer '+accesstoken);
        HttpResponse res1=new HttpResponse();
            res1= h1.send(req1);
    parser = JSON.createParser(res1.getBody());
    // Iterate over json parser to get google analytics data from parser 
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == myCS1.metrics__c)) {
     if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:sessions'))
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:users')) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:sessionDuration')) {
             if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:bounces')) {
             if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:organicSearches')) {
              if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:newUsers')) {
    Catch(Exception e){
        system.debug('error===== '+e.getMessage()+' : '+e.getLineNumber());

Now you got all the data in the variables you can now use these apex variables  to show data.


4. Use Data in visualforce page.

Now we have google analytics data   in our  apex variable here what we need to insert it  in our Visualforce page  or Html page.

<apex:page controller="yourController" Sidebar="False" showHeader="false" docType="HTML" lightningStylesheets="true" >
        <title> Google Analytics Data </title>
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-12">
          <div class="col-md-3">
            <div class="chartcontainer"> 
            <div >ReportVisitorCount</div>
            // using variables to show data on visualforce pages
            <div id="ReportVisitorCount" class="numbers">{!ReportVisitorCount}</div>
          <div class="col-md-3">
            <div class="chartcontainer">
            <div id="WebSessionCount"  class="numbers">{!WebSessionCount}</div> 
          <div class="col-md-3">
            <div class="chartcontainer">
            <div id="WebUniqueVisitorCount" class="numbers">{!WebUniqueVisitorCount}</div>
          <div class="col-md-3">
            <div class="chartcontainer"> 
              <div id = "WebSessionDurationCount" class="numbers">{!WebSessionDurationCount}	</div>



Hits: 3102

Share Post

You may also like...

10 Responses

  1. kanika rana says:

    can you share your custom setting as well? You can remove the client id and customer secret

  2. Susmita Dabade says:

    Hi Himanshu,

    Can you please provide sample data in Google_Analytics__c custom setting and from where we will get this data.


  3. Rama says:

    Thanks for the great post. Can we get Salesforce FAQ view data in VF page using above ?

  4. sorry i dont have custom setting for now. it is simple you need to go to custom setting in your org after then create your custom setting fields to stores data like secrestkey , value, token after then store the data into the custom setting . it is pretty simple hope this will help you

  5. you need to create your custom setting first by going to custom setting option in your org . after then create fields on custom settings and store your data . you get data like secret key and toekn when you creat your app on google analytics account . i aready describe this at the begining of this post . you can get refrence from there

  6. no this code is only for getting google analytics data on vf page

  7. I just could not depart your web site before suggesting that
    I actually enjoyed the standard information an individual provide in your guests?
    Is gonna be again steadily in order to check up on new posts

  8. negative seo says:

    I will get back to your blog again.

  9. Greetings! I’ve been following your web site for some time now and finally got
    the courage to go ahead and give you a shout out from
    Kingwood Texas! Just wanted to mention keep up the good work!

Leave a Reply

Your email address will not be published. Required fields are marked *