[SOLVED] How to fetch Analytics details using Google API?

December 12, 2017 - 15:47

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.

Post your comments / questions