[SOLVED] How to fetch Analytics details using Google API?
https://www.zyxware.com/sites/default/files/styles/user_image/public/default_images/index.png?itok=2YmREnrP
BY antony.glen
1 year ago
Google-Analytics
0
comments comment

In this article let us see how to use Google API with a simple example. Google API helps working with G-plus, Google Drive, Youtube etc.

Google API files can be downloaded from this link https://github.com/google/google-api-php-client

In this example, let's see how to get total views per URL for a site. First, we need to add the necessary library files to our project folder from the downloaded directory. For our purpose, we need only Google API source file, google-api-php-client/src/Google. Move the 'Google' directory to our project.

Let's begin by adding the required files to our project from the library files.

<?php
 require_once 'Google/autoload.php';
 require_once 'Google/Client.php';
 require_once 'Google/Service/Analytics.php';
?>

By including 'autoload.php' we could eliminate the worries of loading each and every class files individually. The files 'client.php and analytics.php' are the API dependencies. Next we need Google's API key which can be gained from https://console.developers.google.com.

$client = new Google_Client();
 $client->setApplicationName('Analytics Example');
 $client->setClientId('CLIENT ID');
 $client->setClientSecret('CLIENT SECRET');
 $client->setRedirectUri('REDIRECT URL');
 $client->setApprovalPrompt('auto');
 $client->addScope("https://www.googleapis.com/auth/analytics.readonly");

The above creates a client object for our app and adds basic config such as app name, client id, secret key, redirect URL. The setApprovalPrompt carries two values 'force' and 'auto'. Here we have used 'auto' option for this. Google ignores OAuth prompt for users who have been authorized before. We have set OAuth 2.0 scope to read-only mode. You can use scopes such us read-only, write, edit, also can add scope for view and manage permissions for analytics account etc.

We will need an access token to perform the functionalities provided by the API client. Access token can be generated using calling API method 'getAccessToken()' using client object. In our code, we will be storing access token in a session variable for future use. If access token has been generated, let's try implementing API methods, the code will create an object '$gs_analytics' for class 'Google_Service_Analytics'.

if ($client->getAccessToken()) {
      $gs_analytics = new Google_Service_Analytics($client);
      $_SESSION['access_token'] = $client->getAccessToken();

      $ga_properties = $gs_analytics->management_webproperties->listManagementWebproperties("~all");
      // Will return array with values account id, property id, website url etc.
      $ga_items = $ga_properties->getItems();
  }

Now let's check our final code, including the API query to fetch views count along with page URL.

<?php
      session_start();
      require_once 'Google/autoload.php';

      set_include_path("../".PATH_SEPARATOR.get_include_path());
      require_once 'Google/Client.php';

      require_once 'Google/Service/Analytics.php';

      define('GA_CLIENT_ID', 'xxxxx.xxx.xxxx');
      define('GA_CLIENT_SECRET', 'xxxxx-xx-xxxx');
      define('GA_REDIRECT_URL', 'xxxxxxxxxxxx');

      $client = new Google_Client();
      $client->setApplicationName('Analytics Demo');
      $client->setClientId(GA_CLIENT_ID);
      $client->setClientSecret(GA_CLIENT_SECRET);
      $client->setRedirectUri(GA_REDIRECT_URL);
      $client->setApprovalPrompt('auto'); // Approval => [force/auto].
      //Scope set as readonly.
      $client->addScope("https://www.googleapis.com/auth/analytics.readonly");

      if (isset($_REQUEST['logout'])) {
        unset($_SESSION['access_token']);
      }

      if (isset($_GET['code'])) {
          $client->authenticate($_GET['code']);
          // Generates access token.
          $_SESSION['access_token'] = $client->getAccessToken();
          $redirect_url_path = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
          header('Location: ' . filter_var($redirect_url_path, FILTER_SANITIZE_URL));
      }

      if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
          $client->setAccessToken($_SESSION['access_token']);
      } else {
          $auth_url = $client->createAuthUrl();
      }
    ?>

    <?php if (isset($auth_url)): ?>
      <a href='<?php echo $auth_url; ?>'>Authenticate</a>
    <?php endif; ?>

      <?php
      if ($client->getAccessToken()) {
          $gs_analytics = new Google_Service_Analytics($client);
          $_SESSION['access_token'] = $client->getAccessToken();

          $ga_properties = $gs_analytics->management_webproperties->listManagementWebproperties("~all");
          $ga_items = $ga_properties->getItems();
         
          if(is_array($ga_items)){
            foreach ($ga_items as $key => $result) {
                $profile_data = $gs_analytics->management_profiles->listManagementProfiles($result->accountId, $result->id)->getItems();
                echo '<a href="index.php?id=' . $profile_data[0]->id . '&domain=' . urlencode($result->websiteUrl) . '">' . $result->websiteUrl . '</a><br/>';
            }
          }

        if (isset($_GET['id'])){
          $page_results = $gs_analytics->data_ga->get(
              'ga:'. $_GET['id'], //GA Property ID.
              date('Y-m-d',strtotime('-1 year')),
              date('Y-m-d',strtotime('-1 day')), // Restricts the results to specified date.
              'ga:pageviews', //Gives page views count.
              array(
                  'dimensions' => 'ga:pagePath',
                  'sort' => '-ga:pageviews',
                  'max-results' => 50000,
                  'filters' => 'ga:medium==organic',
              ));
          if (is_array($page_results->getRows())) {
            print '<ol>';
            foreach($page_results->getRows() as $page_val) {
                print '<li>';
                print '<b>Pagepath</b> -  ' . $page_val[0] . ', ' . ' <b>Visit</b>: ' . $page_val[1];
                print '</li>';
            }
            print '</ol>';
          }
        }
      }
      ?>

Our API could send total request of 50,000 per day. It is also restricted to 10 requests in a minute. This will list total views for a website, per page basis. Please contact for more information.


RELATED ARTICLE

more_horiz
close

on 13th December 2011 / by sujith.s
Google Analytics is an invaluable tool if you are a web developer, blogger or if you simply own a website. Few other tools come close to the volume of information  offered by Google Analytics. Besides it is also free of charge which certainly adds to its popularity. However utilizing this huge amount of data offered by Google Analytics is a challenge and if done carefully, the data can be converted into intelligence that alerts you to possibilites of increasing the effectiveness of your website and makes sure that it reaches out t the right audience.  In this tutorial, we are going to show you how to make the best use of Google analytics from a web developers perspective. What is Google Analytics? Google, in its attempt to help you make the best out of your website, offers you state-of-the-art monitoring and analytics services for your websites, free of cost, under the banner Google Analytics. Google Analytics - What is it for? Why do you need it? To increase the traffic to your website, you should first know what makes people come to your website, how they come to you, and what you can do to improve it. Further, you need to know how these visitors interact with your site, and what you can do to make them stay longer and keep coming back. A clear knowledge of such basic factors helps you make intelligent decisions regarding your site’s business. What does Google Analytics’ offerings look like? Here’s a quick screenshot of what the basic Google Analytics Dashboard offers you: Google Analytics by default provides you valuable insights on number of visits number of pageviews bounce rate visitor demographics traffic sources How GoogleAnalytics works The following block diagram represents the process flow that takes place: Google Analytics requires you to add a small piece of Javascript code (called the Google Analytics Tracking Code) to your site’s pages. The data collection process begins when a visitor’s web browser requests a page from the webserver. The server responds by sending the requested page back to the browser. When the visitor’s browser starts to execure the Tracking Code present in the webpage source, the script identifies various attributes regarding the visitor and the browsing environment, such as time spent on the site, where the user is from (location), etc. While the data is being collected, the browser actively and asynchronously downloads a script by the name ga.js from the geo-loadbalanced servers of Google. Once the ga.js script has been fully downloaded and starts executing, the collected data is sent to Google’s servers. The server stores the received data into a temporary log file. These log files are processed at regular intervals (of approximately 3 hours), and the processed data is available as reports in 24 hours. Advanced Google Analytics Features - Event Tracking and Custom Variables The event tracking feature of Google Analytics allows you to track events (also called “actions” or “conversions”) on your website. An action occurs when a visitor clicks on something, perhaps a PDF white paper download. The event tracking code is a basic line of JavaScript that you add to a hyperlink. The tracking code should look something like this: _trackEvent(category, action, opt_label, opt_value, opt_noninteraction)Parameters: category (required) : The name you supply for the group of objects you want to track. action (required) : A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object. label (optional) : An optional string to provide additional dimensions to the event data. value (optional) : An integer that you can use to provide numerical data about the user event. non-interaction (optional) : A boolean that when set to true, indicates that the event hit will not be used in bounce-rate calculation. Eg: Play Custom Reports in Google Analytics using Custom Variables Google Analytics allows custom data monitoring and reporting by allowing you to play with Custom Variables. This allows us to monitor custom data such as tracking popular authors on your site, which does not otherwise come under the default set of reports in Google Analytics. Each custom variable basically has a name-value pair. The full declaration structure may have: Name Value Slot or index - to organize our custom variables, ranging 1 through 5 Scope - 3 levels - page, visitor, visit Google Analytics primarily deals with three levels of scope: Page Level - persists as long as the visitor is viewing a particular page. Visitor Level - persists on the visitor’s browser as a cookie, for 24 months or till the cookie gets deleted. Visit Level - persists for an entire visit session. Scope and Index work in tandem to decide how many custom variables you have available at any given time. How to implement a new Google Analytics Custom Variable The first step is to write a line of _gaq.push command for the same. The next step is to place this in your page source according to your tracking requirement. The standard asynchronous javascript code snippet for implementing custom variables in Google Analytics is of the following syntax: _gaq.push(‘_setCustomVar’, index, ‘name’, ‘value’, scope); where index is a number from 1 through 5, scope is a number from 1 through 3, {1=&gt;visitor, 2=&gt;visit, 3=&gt;page}, name, value are just plain text._gaq.push makes sure that all what you enter in this command gets pulled into Google Analytics. Now that you have this part done, where do you place this code? The following example cases would illustrate this good: You may want to categorize all of the pages on your site using a page level custom variable. In this case you might place the custom var code in the standard GA code snippet, like this: //&lt;![CDATA[ var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXX-1']); _gaq.push(['_setCustomVar',1,'PageCategory','Sports', 3]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:'== document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); // ]]&gt; Or, if you’re going to identify someone as a ‘member’ of your site, you might place the code on a page after the visitor logs in. Like this: //&lt;![CDATA[ var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXX-1']); _gaq.push(['_setCustomVar',1,'VisitorType','Member', 1]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); // ]]&gt; These should give you a pretty good headstart on making the best out of Google Analytics. Web Development SEO Google Analytics Leave a reply Your email address will not be published. Required fields are marker * Anonymous (not verified) access_time 22 Feb 2019 - 05:31 The Contents of this site are really very good. I hope We will get this type of contents and information from this blog in future days too. You certainly have some agreeable opinions and views. Your blog provides a fresh look at the subject. Add new comment
close

on 12th November 2012 / by webmaster
Many Drupal users have reported that after they had successfully installed the Google Analytics module on their website, the Google Analytics admin page reported a "Tracking code not detected" error. The status reports page of Google Analytics also indicated a "Tracking Not Installed" error. If you are facing the same situation with the Google Analytics module in your Drupal site then read on. Here is the fix. Many users had resolved it by adding a trailing "/" to their site hostname in the profile page in Google Analytic's settings. For example. "example.com" DID NOT WORK "example.com/" WORKED So check if it has a trailing '/' in the settings page of Google Anaytics. Hope that helps. The easiest way to solve a Drupal issue is to hand it to the Drupal experts. Do you need professional help in building your Drupal site? We can provide a wide range of Drupal services to help you deploy your Drupal site easily and quickly. Get in touch with us to know more. Reference: http://drupal.org/node/518640 Drupal Google Analytics Drupal Issues Leave a reply Your email address will not be published. Required fields are marker *
more_horiz
close

on 01st February 2013 / by tiju.thomas
Google Analytics is a service offered by google which is mainly used to analyze the traffic of drupal/non drupal websites. This module gives statistical information such as number of people who viewed a drupal page. average time visitors stayed on a drupal website. average number of pages viewed per visit etc. Thus, to watch over the statistical growth of a website, this module is a must. To ensure the working, the module must be tested after configuring it with the drupal/non-drupal site. Here I have documented on how to test a Google Analytics module configured on a website. Test cases/ Checklists against Google Analytics module Open the pages you want to check Google Analytics Take the source code by pressing Ctrl + u Search Google Analytics by pressing Ctrl + f Enter 'googleanlaytics' in the search form Verify whether the Google Analytics details is displayed in the source code. For example; if Google Analytics is enabled you will see the following code We can test this as both anonymous and logged in user.For admin users, follow the steps below: Login as admin into the site. Click on 'Modules' dispayed in the admin menu bar   Enter 'Modules' page and Search google analytics by pressing Ctrl + f Enter google anlaytics in the search form Verify whether the google analytics module is enabled for the site. If the developers give the credentials of google analytics account, then we can simply check the traffic of our site. For that, Open the site http://www.google.co.in/analytics/ Login to the site by using the credentials of google analytics account Enter the home page and check the traffic of our site From this page the number of Visits, Unique Visitors, Average Visit Duration, Bounce Rate, % of New Visits etc can be viewed. These ways help a user to check Google Analytics on a site. SEO Google Analytics Software Testing Leave a reply Your email address will not be published. Required fields are marker *
Leave a reply
Your email address will not be published. Required fields are marker *

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type='1 A I'> <li> <dl> <dt> <dd> <h2 id='jump-*'> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
The content of this field is kept private and will not be shown publicly.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.