Capture Data Google Analytics PHP

Asked

Viewed 538 times

1

Opa,

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

I’m accessing the Analytics API like this ,but, always get the total of 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

And now who can help me?

  • according to the error you have not yet associated your email gmail with the Analytics service user does not have any Google Analytics account.

  • @Rafaelacioly, I understood, but in this case the creation of the service account there on the console was performed by me, the same created the email that is in service_account_email , somewhere in the code or the . P12 should inform the gmail address?

  • Buddy, the correct is correct, as you said failed to add the email created by the console in creating service account to Analytics, by the code above, it informs the total of visits. You can tell me how to inform total visits for a specific page?

1 answer

0


Follow full code for query the API of the Analytcs and return of total visits per url specifies:

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.