Google Analytics Report

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

POST https://analyticsreporting.googleapis.com/v4/reports:batchGet
{
  "reportRequests":
  [
    {
      "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:

ga:users

ga:newusers

ga:sessions

ga:bounces

ga:bounceRate

ga:hits

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 developers.google.com. 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 developer.google.com and create an app

1.1. Login to google.com and open developers.google.com. 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()
{
    try{
        
    // 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();
        req.setEndpoint(myCS1.Token_End_Point_URL__c);
        req.setBody('client_id='+myCS1.client_id__c+'&client_secret='+myCS1.client_secret__c+'&grant_type=refresh_token&refresh_token='+myCS1.refreshToken__c);
        req.setHeader('Content-Type','application/x-www-form-urlencoded');
        req.SetMethod('POST');
        HttpResponse res=new HttpResponse() ;
  res = h.send(req);
       
        system.debug('----------------'+res.getBody());
        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')) {
                parser.nextToken();
                accesstoken=parser.getText();
            }
        }
  
  // setting start date for next http request  strat date is the mandatory field with id and  metrices 
        
  Datetime dt = System.now()+1;
        String formattedDate = dt.format('YYYY-MM-dd');
        system.debug('***'+formattedDate);
        
        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.setEndpoint(myCS1.Analytics_End_Point_URL__c+myCS1.Analytics_Id__c+'&metrics='ga:users,ga:sessions,ga:newusers,ga:sessions,ga:bounces,ga:hits'&end-date='+formattedDate+'&start-date='+formatedStartDate+'&dimensions=ga:city');
        
        req1.setHeader('Authorization','Bearer '+accesstoken);
        req1.SetMethod('GET');
        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)) {
                parser.nextToken();
                ReportVisitorCount=Integer.valueof(parser.getTEXT());
            }
    
     if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:sessions'))
            {
                parser.nextToken();
                WebSessionCount=Integer.valueof(parser.getTEXT());
                
            }
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:users')) {
                parser.nextToken();
                WebUniqueVisitorCount=Integer.valueof(parser.getTEXT());
          
            }
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:sessionDuration')) {
                parser.nextToken();
                WebSessionDurationCount=parser.getTEXT();
          
            }
             if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:bounces')) {
                parser.nextToken();
                Bounce=Integer.valueof(parser.getTEXT());
          
            }
           
             if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:organicSearches')) {
                parser.nextToken();
                Organic_Visitors=Integer.valueof(parser.getTEXT());
          
            }
            
              if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'ga:newUsers')) {
                parser.nextToken();
                newUsers=Integer.valueof(parser.getTEXT());
          
            }
        }
        
     
    }
    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" >
    <head>
        <title> Google Analytics Data </title>
    <body>
    <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>
          </div>
          <div class="col-md-3">
            <div class="chartcontainer">
            <div>WebSessionCount</div>
            <div id="WebSessionCount"  class="numbers">{!WebSessionCount}</div> 
            </div>
          </div>
          <div class="col-md-3">
            <div class="chartcontainer">
            <div>WebUniqueVisitorCount</div>
            <div id="WebUniqueVisitorCount" class="numbers">{!WebUniqueVisitorCount}</div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="chartcontainer"> 
              <div>WebSessionDurationCount</div>
              <div id = "WebSessionDurationCount" class="numbers">{!WebSessionDurationCount}	</div>
            
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</apex:page>

 

 

Hits: 8954

Share Post

By Himanshu Rana

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

10 thoughts on “Create Google Analytics Report On Visualforce Page”
  1. Hi Himanshu,

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

    Thanks
    Susmita

  2. 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

  3. 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

  4. 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

Leave a Reply

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