Capturing Data Google Analytics PHP

0

Opa,

I need to access the google analytics API and import information like visits and origin of the visits, per page.

I'm accessing the analytics API like this, but, I always get total visits 0:

My code:

'

function getService()
{
  // Creates and returns the Analytics service object.

  // Load the Google API PHP Client Library.
  require_once '_files/google-api-php-client-master/src/Google/autoload.php';

  // Use the developers console and replace the values with your
  // service account email, and relative location of your key file.
  $service_account_email = '[email protected]';
  $key_file_location = '_files/File.p12';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Aplic");
  $analytics = new Google_Service_Analytics($client);

  // Read the generated client_secrets.p12 key.
  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
      $service_account_email,
      array(Google_Service_Analytics::ANALYTICS_READONLY),
      $key
  );
  $client->setAssertionCredentials($cred);
  if($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }

  return $analytics;
}

function getFirstprofileId(&$analytics) {
  // Get the user's first view (profile) ID.

  // Get the list of accounts for the authorized user.
  $accounts = $analytics->management_accounts->listManagementAccounts();

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

    // Get the list of properties for the authorized user.
    $properties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

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

      // Get the list of views (profiles) for the authorized user.
      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstPropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();

        // Return the first view (profile) ID.
        return $items[0]->getId();

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

function getResults(&$analytics, $profileId)
{
    $url="Minha-URL";

    $ids = "ga:************";
    $start_date = "2016-09-05";
    $end_date = date("Y-m-d");
    $metrics = "ga:pageviews";
    //$metrics = "ga:uniquePageviews";
    $dimensions = "ga:pagePath";
    $filters = "ga:pagePath==/".$url;
    $optParams = array('dimensions' => $dimensions, 'filters' => $filters);
    return $analytics->data_ga->get($ids,$start_date,$end_date,$metrics,$optParams);

}

function printResults(&$results)
{

    //print_r($results);
    if (count($results->getRows()) > 0)
    {

    $rows = $results->getRows();
    $visits = $rows[0][0];
        echo($visits);
    } else {
        echo 0;
    }

}

$analytics = getService();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);

'

Based on this Google tuto

And now who can help me?

    
asked by anonymous 24.09.2016 / 16:12

1 answer

0

Here is the complete code to query the analytcs API and return total visits per url:

function getService()
{
  // Creates and returns the Analytics service object.

  // Load the Google API PHP Client Library.
  require_once '_files/google-api-php-client-master/src/Google/autoload.php';

  // Use the developers console and replace the values with your
  // service account email, and relative location of your key file.
  $service_account_email = '[email protected]';
  $key_file_location = '_files/arquivo.p12';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("1News");
  $analytics = new Google_Service_Analytics($client);

  // Read the generated client_secrets.p12 key.
  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
      $service_account_email,
      array(Google_Service_Analytics::ANALYTICS_READONLY),
      $key
  );
  $client->setAssertionCredentials($cred);
  if($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }

  return $analytics;
}

function getFirstprofileId(&$analytics) {
  // Get the user's first view (profile) ID.

  // Get the list of accounts for the authorized user.
  $accounts = $analytics->management_accounts->listManagementAccounts();

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

    // Get the list of properties for the authorized user.
    $properties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

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

      // Get the list of views (profiles) for the authorized user.
      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstPropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();

        // Return the first view (profile) ID.
        return $items[0]->getId();

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

function getResults(&$analytics, $url)
{
    $ids = "ga:*********";
    $start_date = "2016-09-05";
    $end_date = date("Y-m-d");
    //$metrics = "ga:pageviews";
    $metrics = "ga:uniquePageviews";
    $dimensions = "ga:pagePath";
    $filters = "ga:pagePath==/".$url;
    $optParams = array('dimensions' => $dimensions, 'filters' => $filters);
    return $analytics->data_ga->get($ids,$start_date,$end_date,$metrics,$optParams);

    /*
    return $analytics->data_ga->get(
       'ga:' . $profileId,
       '30daysAgo',
       'today',
       'ga:sessions');
    */
}

function Conta_Visitas_Analytics(&$results)
{

    if (count($results->getRows()) > 0)
    {
        $rows = $results->getRows();
        $visits = $rows[0][1];
        return $visits;
    } else {
        return 0;
    }

}

$analytics = getService();
$profile = getFirstProfileId($analytics);



    $url="noticia/6/blablablablablabla"; //Sem o dominio
    $results = getResults($analytics, $url);
    Conta_Visitas_Analytics($results);
    
26.09.2016 / 17:56