Google Product Forums

Hello Analytics API tutorial, newbi

isaania Jun 20, 2012 12:35 AM
Posted in group: Google Analytics

Categories: Asynchronous Tracking Code Snippet :

Hi
I recently worked through the - Google analytics API tutorial "Hello Analytics API" https://developers.google.com/analytics/resources/tutorials/hello-analytics-api

All went well to a point , I created the PHP in a file called googlestats.php and used require_once command to call it from my index.php page.

The Index page loads fine gives the button "Connect Me!" , which when clicked takes be to the 0auth2 require permission page on accounts.google.com

When i click this i get "This web page is not available screen - The connection to www.mywebsite.com was interrupted."

cant work out where the code is wrong ??  the redirect URL is that of the PHP script, ie www.mywebsite.com/googlestats.php as it is set up on the API console.

I know this doesnt give a lot to work on - but any thought much appreciate!  


code;

<html>
<body>

<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiAnalyticsService.php';

$client = new apiClient();
$client->setApplicationName('Hello Analytics API Sample');

$client->setClientId('myclid.apps.googleusercontent.com');
$client->setClientSecret('mysecret');
$client->setDeveloperKey('my dev key');

// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);

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

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if (!$client->getAccessToken()) {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";

} else {
  $analytics = new apiAnalyticsService($client);
  runMainDemo($analytics);
}

function runMainDemo(&$analytics) {
  try {

    // Step 2. Get the user's first profile ID.
    $profileId = getFirstProfileId($analytics);

    if (isset($profileId)) {

      // Step 3. Query the Core Reporting API.
      $results = getResults($analytics, $profileId);

      // Step 4. Output the results.
      printResults($results);
    }

  } catch (apiServiceException $e) {
    // Error from the API.
    print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();

  } catch (Exception $e) {
    print 'There was a general error : ' . $e->getMessage();
  }
}

function getFirstprofileId(&$analytics) {
  $accounts = $analytics->management_accounts->listManagementAccounts();

  if (count($accounts->getItems()) > 0) {
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    $webproperties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

    if (count($webproperties->getItems()) > 0) {
      $items = $webproperties->getItems();
      $firstWebpropertyId = $items[0]->getId();

      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstWebpropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();
        return $items[0]->getId();

      } else {
        throw new Exception('No profiles found for this user.');
      }
    } else {
      throw new Exception('No webproperties found for this user.');
    }
  } else {
    throw new Exception('No accounts found for this user.');
  }
}

function getResults(&$analytics, $profileId) {
   return $analytics->data_ga->get(
       'ga:' . $profileId,
       '2012-03-03',
       '2012-03-03',
       'ga:visits');
}

function printResults(&$results) {
  if (count($results->getRows()) > 0) {
    $profileName = $results->getProfileInfo()->getProfileName();
    $rows = $results->getRows();
    $visits = $rows[0][0];

    print "<p>First profile found: $profileName</p>";
    print "<p>Total visits: $visits</p>";

  } else {
    print '<p>No results found.</p>';
  }
}
?>

</body>
</html>