Quantcast
Channel: birghtyoursite » php
Viewing all articles
Browse latest Browse all 4

php get google analytics data use oauth 2.0

$
0
0

This article is introduce how to use Google Core Reporting API version 3 and Authorization with oauth 2.0 to get google analytics data with php.

Prepare

  1. You must need have a google account and register to google console
  2. Download google php api client library.

Create a google analytics api project in google console

Go to google console,login with you google account,then it will ask you create project,click create a project to go to the Dashboard,the default project name is ‘API Project’.


then you need go to the services tab to enable the google analytics services.


Last step config your api access.Go to the API Access tab,click the Create an Oauth 2.0 client ID button.

Fill the product name to continue


Add the redirect url,when use my demo package the redirect url should be https://www.yoursite.com/Gaapi/getGatoken.php (If you don’t have ssl make sure you choose http as the screenshot,default it’s https)


Client ID for web applications –This is the final information we need.

Working with google php api client

Download the Latest google php api client library.We need the library under the ‘src’ folder.Let’s create folder Gaapi and copy the fold src there.First we need get the Oauth 2.0 access token,then store it in the session for the next call api.

$a = session_id();
if ($a == '') session_start(); 
require_once  ('src'. DIRECTORY_SEPARATOR.'Google_Client.php'); 
require_once ('src'. DIRECTORY_SEPARATOR .'contrib'. DIRECTORY_SEPARATOR .'Google_AnalyticsService.php'); 
require_once 'config.php';
 
	// Build a new client object to work with authorization.
	$client = new Google_Client();
	$client->setClientId(CLIENT_ID);
	$client->setClientSecret(CLIENT_SECRET);
	$client->setRedirectUri(REDIRECT_URL);
	$client->setApplicationName(APP_NAME);
	$client->setScopes(array(ANALYTICS_SCOPE)); 
	// Magic. Returns objects from the Analytics Service
	// instead of associative arrays.
	$client->setUseObjects(true);  
        try{
	   $accessToken = $client->authenticate();
	}
	catch(exception $e)
	{
	 echo $e;
	}
 
	if($accessToken)
	{
		 echo "<b>Your Token is</b><textarea onfocus='this.select()' style='width:500px;height:60px;'>$accessToken</textarea><a href='sample.php'>View Demo</a>";
		$_SESSION['token']  = ($accessToken);
 
	}

File getGatoken.php ,run this file it will forward to the google permission confirm page

Since got the token save it to the session then we can start grab data from the google through api.

$a = session_id();
if ($a == '') session_start(); 
require_once 'config.php';
require_once 'src'. DIRECTORY_SEPARATOR.'Google_Client.php'; 
require_once ('src'. DIRECTORY_SEPARATOR .'contrib'. DIRECTORY_SEPARATOR .'Google_AnalyticsService.php'); 
 
 
$ga_profile_id = '23138610';
 
// Build a new client object to work with authorization.
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
 
$client->setApplicationName(APP_NAME);
$client->setScopes(array(ANALYTICS_SCOPE));
 
// Magic. Returns objects from the Analytics Service
// instead of associative arrays.
$client->setUseObjects(true); 
 
$accessToken= $_SESSION['token'];
if(empty($accessToken))
{
 header('Location:getGatoken.php');
}
$client->setAccessToken($accessToken);
if($client->isAccessTokenExpired())
{
    $tokenObj = json_decode($accessToken);
	$client->refreshToken($tokenObj->refresh_token);
     $_SESSION['token']=$client->getAccessToken();
} 
 
 
 $analytics = new Google_AnalyticsService($client);
 
 
	 try
	{ 
	  $results=$analytics->data_ga->get(
        'ga:' . $ga_profile_id,
        '2012-01-01',
        '2012-01-31',
        'ga:organicSearches,ga:visits,ga:newVisits,ga:visitors',
        array(
            'dimensions' => 'ga:landingPagePath',
            'sort' => '-ga:organicSearches',
            'filters' => 'ga:medium==organic',
            'max-results' => '25'));
 
			$totals = $results->gettotalsForAllResults();
			$html='';
			foreach ($totals as  $metricName => $metricTotal )
			{
 
 
			  $html .= "Metric Name  = $metricName\n";
			  $html .= "Metric Total = $metricTotal <br />";
 
 
 
			}  ;
			echo $html;
 
		 if (count($results->getRows()) > 0) {
		  $table = '<table>';
 
		  // Print headers.
		  $table .= '<tr>';
 
		  foreach ($results->getColumnHeaders() as $header) {
			$table .= '<th>' . $header->getName() . '</th>';
		  }
		  $table .= '</tr>';
 
		  // Print table rows.
		  foreach ($results->getRows() as $row) {
			$table .= '<tr>';
			  foreach ($row as $cell) {
				$table .= '<td>'
					   . htmlspecialchars($cell, ENT_NOQUOTES)
					   . '</td>';
			  }
			$table .= '</tr>';
		  }
		  $table .= '</table>';
 
		} else {
		  $table = '<p>No results found.</p>';
		}
		 echo    $table;
 
 
	}
	catch(exception $e)
	{
		echo $e; 
	}

It works fast,you also can tracking the requests in your google console project report tab.But you only can send 50K requests per day.

Demo & Download

google analytics api demo Download the zip file, uncompression and upload to the root of your site , add your google console project access information to the config.php then visit http://www.yoursite.com/Gaapi/getGatoken.php to start.


Viewing all articles
Browse latest Browse all 4

Trending Articles