Google Analytics Realtime Traffic Viewer using Analytics API

In this tutorial, we are going to develop a complete Google Analytics Realtime Traffic Tracking tool using Analytics API.

Follow this video for complete step by step guidance :

Please follow these steps to develop your own Google Analytics Dashboard for Realtime Traffic tracking :

Step 1 : Create composer.josn file with following code

composer.json

{
    "require": {
        "google/apiclient": "^2.0"
    }
}

Step 2 : Run composer install command

composer install

Step 3 : Go to Google Developers Console and create a new project.

Then, enable Google Analytics API. Under Credentials menu, click on Manage Service Accounts. Now create a new Service Account.
Click on the newly created service account and then navigate to Keys tab and then create new key of type JSON. A JSON file will be downloaded. Place the downloaded JSON file in the root of your project.

Step 4 : Open the JSON file

Find the email address of the service account in it. Now add that email address as the user of the analytics property of which you want to access the realtime data in analytics.google.com

Step 5 : Create a view to show the realtime traffic along with source and devices

index.php

<?php include('functions.php');?>
<html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.1/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <style type="text/css">
      *{
        margin: 0;
        padding: 0;
      }
      body{
        margin-bottom: 20px;
        background: aliceblue;
      }
      .section{
        background: #fff;
      }
      .count{
        font-size: 36px;
      }
      .progress-label {
          text-transform: uppercase;
          font-size: 0.8em;
          font-weight: bold;
          margin: 5px 0 8px;
      }
      .label-success, .label-warning, .label-danger {
          background: transparent;
          color: #444;
          display: inline-block;
          font-size: 1em;
          line-height: 1.1em;
          font-weight: bold;
          font-family: arial;
          padding: 0px 10px;
      }
      .progress-bar-success, .label-success:before {
        background-color: #50b432;
      }
      .progress-bar-warning, .label-warning:before {
        background-color: #ed561b;
      }
      .progress-bar-danger, .label-danger:before {
        background-color: #058dc7;
      }
      .progress-label .label:before{
        content:'';
        width:10px; 
        height:10px;
        float:left; 
        margin-right:3px;
      }
      .progress-label{
        text-transform:uppercase;
        font-size:0.8em; 
        font-weight:bold;
        margin:5px 0 8px;
      }
      .no-pad{
        padding: 0px;
      }
      .open-link:hover{
        cursor: pointer;
        background: #ddd;
      }
      .table{
        margin-bottom: 0px;
      }
    </style>
  </head>


  <body>
    <div class="container mt-3">
      <div class="row">
        <div class="col-md-8">
          <table class="section table table-striped table-bordered">
            <thead>
              <tr>
                <th>Active Pages</th>
                <th>Active Users</th>
              </tr>
            </thead>
            <tbody class="pages-content">

            </tbody>
          </table>
        </div>
        <div class="col-md-4">
          <div class="card">
          		<div class="card-header">
              	Right Now
            	</div>
            	<div class="card-body">
            		<div class="text-center">
                	<h1>
                                  <div class="users-content count" id="active-users">0</div>
                  			</h1>
                  			<small>Active Users on Site</small>
                  		</div>
                  		<div id="devices" class="devices-content mt-4">
                  		</div>
            	</div>
          </div>

          <div class="card mt-3">
            	<div class="card-body no-pad">
            		<table class="table table-bordered">
            			<thead>
            				<tr>
            					<th>Source</th>
            					<th>Users</th>
            				</tr>
            			</thead>
            			<tbody class="sources-content">

            			</tbody>
            		</table>
            	</div>
          </div>

          <div class="card mt-3">
            	<div class="card-body no-pad">
            		<table class="table table-bordered">
            			<thead>
            				<tr>
            					<th>Country</th>
            					<th>Users</th>
            				</tr>
            			</thead>
            			<tbody class="countries-content">

            			</tbody>
            		</table>
            	</div>
          </div>

          <div class="card mt-3">
            	<div class="card-body no-pad">
            		<table class="table table-bordered">
            			<thead>
            				<tr>
            					<th>Browsers</th>
            					<th>Users</th>
            				</tr>
            			</thead>
            			<tbody class="browsers-content">

            			</tbody>
            		</table>
            	</div>
          </div>

          <div class="card mt-3">
            	<div class="card-body no-pad">
            		<table class="table table-bordered">
            			<thead>
            				<tr>
            					<th>OS</th>
            					<th>Users</th>
            				</tr>
            			</thead>
            			<tbody class="os-content">

            			</tbody>
            		</table>
            	</div>
          </div>
        </div>
      </div>
    </div>
    <script type="text/javascript">

      function refreshData(){
        getData('pages');
        getData('users');
        getData('devices');
        getData('sources');
        getData('countries');
        getData('os');
        getData('browsers');
      }

      refreshData();

      //fetch live data every 10 seconds
      setInterval(function(){
        refreshData();
      },10000);

      function getData(action){
        $.ajax({
          url:'ajax.php?action='+action,
          type:'get',
          success:function(res){
            $("."+action+"-content").html(res);
          }
        });
      }

      $(document).on('click','.open-link',function(){
        link = '<?php echo DOMAIN;?>'+$(this).attr('data-link');
        window.open(link, '_blank');
      });
    </script>
  </body>
</html>

 

Step 6 : Create functions.php file

<?php

define('VIEW','194594240');
define('SERVICE_ACCOUNT', 'analytics-325704-1b0be24a12d4.json');
define('DOMAIN','https://reeteshghimire.com.np');


function getActivePages($analytics){
  $optParams = array(
          'dimensions' => 'rt:pageTitle,rt:pagePath',
          'sort' => '-rt:activeVisitors',
          'max-results' => '16'
      );
      $result = $analytics
          ->data_realtime
          ->get('ga:' . VIEW, 'rt:activeVisitors', $optParams);
      
      $table = '';
      if($result){
    		$rows = $result->getRows();
    		if($rows){
    			foreach($rows as $row){
    				$table .= '<tr class="open-link" data-link="'.$row[1].'">';
    				$table .= '<td>'.htmlspecialchars($row[0],ENT_NOQUOTES).'</td>';
    				$table .= '<td>'.htmlspecialchars($row[2],ENT_NOQUOTES).'</td>';
    				$table .= '</tr>';
    			}
    		}else{
    			$table .= '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
    		}
    		return $table;
    	}else{
    		return '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
    	}
  }

  function getActiveUsers($analytics){
      $active_users = $analytics
                        ->data_realtime
                        ->get('ga:' . VIEW, 'rt:activeVisitors');
      $active_users = (isset($active_users->rows[0][0]))?$active_users->rows[0][0]:0;
      return $active_users;
  }

  function getDevices($analytics){
      $optParams = array(
          'dimensions' => 'rt:deviceCategory',
          'sort' => '-rt:activeVisitors',
      );

      $devices = $analytics
          ->data_realtime
          ->get('ga:' . VIEW, 'rt:activeVisitors', $optParams);
      $html = '';
      if($devices->rows){
      	$total = 0;
      	$class = array('warning','success','danger');
      	foreach($devices->rows as $row){
      		$total += $row[1];
      	}
      	$loop = 0;
      	$html .= '<div class="progress-label">';
      	foreach($devices->rows as $row){
      		$percent = round(($row[1]/$total)*100);
 				$html .= '<div class="label label-'.$class[$loop].'">';
                $html .= '<span>'.$row[0].'</span>';
                $html .= '<span> : '.$row[1].'</span>';
                $html .= '</div>';
                $loop++;
            }  
            $html .= '</div>'; 
            $loop = 0;
            $html .= '<div class="progress" style="width:100%!important;">';
            foreach($devices->rows as $row){
            	$percent = round(($row[1]/$total)*100);
                $html .= '<div class="progress-bar progress-bar-'.$class[$loop].'" style="width: '.$percent.'%"></div>';
                $loop++;
            }
            $html .= '</div>';
      }
      return $html;
  }

  function getFormattedData($result){
    	$table = '';
    	if($result){
    		$rows = $result->getRows();
    		if($rows){
    			foreach($rows as $row){
    				$table .= '<tr>';
    				foreach($row as $cell){
    					$table .= '<td>' . htmlspecialchars($cell, ENT_NOQUOTES) . '</td>';
    				}
    				$table .= '</tr>';
    			}
    		}else{
    			$table .= '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
    		}
    		return $table;
    	}else{
    		return '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
    	}
    }

  function getTrafficSources($analytics){
      $optParams = array(
          'dimensions' => 'rt:source',
          'sort' => '-rt:activeVisitors',
          'max-results' => '5'
      );

      $result = $analytics
          ->data_realtime
          ->get('ga:' . VIEW, 'rt:activeVisitors', $optParams);
      return getFormattedData($result);
  }
  function getCountries($analytics){
    $optParams = array(
      'dimensions'=>'ga:country',
      'sort' => '-rt:activeVisitors',
      'max-results' => '10'
    );
    $result = $analytics
          ->data_realtime
          ->get('ga:' . VIEW, 'rt:activeVisitors', $optParams);
      return getFormattedData($result,'Country','Users');
  }

  function getOS($analytics){
    $optParams = array(
      'dimensions'=>'ga:operatingSystem',
      'sort' => '-rt:activeVisitors',
      'max-results' => '10'
    );
    $result = $analytics
          ->data_realtime
          ->get('ga:' . VIEW, 'rt:activeVisitors', $optParams);
      return getFormattedData($result,'OS','Users');
  }

  function getBrowser($analytics){
    $optParams = array(
      'dimensions'=>'ga:browser',
      'sort' => '-rt:activeVisitors',
      'max-results' => '10'
    );
    $result = $analytics
          ->data_realtime
          ->get('ga:' . VIEW, 'rt:activeVisitors', $optParams);
      return getFormattedData($result,'Browser','Users');
  }

Step 7 : Create ajax.php file

<?php

  include('functions.php');

  //initialize analytics
  require_once __DIR__ . '/vendor/autoload.php';
  $client = new Google_Client();
  $client->setApplicationName("Realtime Analytics");
  $client->setAuthConfig(SERVICE_ACCOUNT);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_Analytics($client);


  if(isset($_GET['action'])){
    $action = $_GET['action'];
    if($action=='pages'){
      echo getActivePages($analytics);
    }
    elseif($action=='users'){
      echo getActiveUsers($analytics);
    }
    elseif($action=='devices'){
      echo getDevices($analytics);
    }
    elseif($action=='sources'){
      echo getTrafficSources($analytics);
    }
    else if($action=='countries'){
      echo getCountries($analytics);
    }
    else if($action=='os'){
      echo getOS($analytics);
    }
    else if($action=='browsers'){
      echo getBrowser($analytics);
    }
  }

That’s it. Now browse your project from your browser and track realtime traffic in your site.

 

CHEERSSSS

Recommended For You

About the Author: Ritesh Ghimire

Ritesh is a Computer Engineer, Web Developer and an active cricket follower.