如何在PHP中添加带有服务器端授权的Google Analytics信息中心?

时间:2016-03-05 22:50:11

标签: javascript php google-analytics google-analytics-api

我想在我的网站上显示Google Analytics数据。我已经用我的脚本加载了php库,现在它返回"总会话数:94" (这实际上是正确的答案)。快速简便的示例仅显示几行代码,以显示带有图表和格式的格式化小部件。图,但它是JAVASCRIPT而不是PHP。

PHP部分现在正在验证并返回正确的信息,但它不能很好地显示。

  

如何让API在a上显示格式化的图表和图形   网站?

     

有没有办法只返回大量数据然后解析它?

<?php
//-------- Embed API Dashboard with Server-Side Authorization
//-------- https://ga-dev-tools.appspot.com/embed-api/basic-dashboard/

/*
//-------- Load the Google API PHP Client Library.
    require_once '/src/Google/autoload.php';

//-------- Set variables
    $client_id = 'BIG-LONG-SERVER-API-KEY';
    $email_address = 'SERVER-API-KEY@ACCOUNT.gserviceaccount.com';
    $key_file_location = 'client_secrets.p12';
    $key = file_get_contents($key_file_location);
*/


//-------- Start a session to persist credentials
    session_start();

//-------- Create the Google client
    $client = new Google_Client();
    $client->setApplicationName('GA Analytics API Sample');

//-------- Separate additional scopes with a comma
    $scopes ="https://www.googleapis.com/auth/analytics.readonly";

//-------- Server Side Auth
    $cred = new Google_Auth_AssertionCredentials(
        $email_address,
        array($scopes),
        $key
    );
    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $client->setClientId($client_id);

    // Create an authorized analytics service object.
    $analytics = new Google_Service_Analytics($client);

    // Get the first view (profile) id for the authorized user.
    $profile = getFirstProfileId($analytics);

?>
<!DOCTYPE html>
<html>
<head>
  <title>Embed API Demo</title>
</head>
<body>
<?php
//-------- Get the results from the Core Reporting API and print the results

    $results = getAnalyticsData($analytics, $profile);
    // Parses the response from the Core Reporting API and prints
    // the profile name and total sessions.
    if (count($results->getRows()) > 0)
    {
        // Get the profile name.
        $profileName = $results->getProfileInfo()->getProfileName();
        // Get the entry for the first entry in the first row.
        $rows = $results->getRows();
        $sessions = $rows[0][0];
        // Print the results.
        print "<p>First view (profile) found: $profileName</p>";
        print "<p>Total sessions: $sessions</p>";
    } else {
        print "<p>No results found.</p>";
    }
?>

<!-- Step 1: Create the containing elements. -->
<section id="auth-button"></section>
<section id="view-selector"></section>
<section id="timeline"></section>

<!-- Step 2: Load the library. -->
<script>
(function(w,d,s,g,js,fjs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
  js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>

<script>
gapi.analytics.ready(function() {

  // Step 3: Authorize the user.
  // This is for "OAuth Client" NOT Server-Side Authorization
  var CLIENT_ID = 'BIG-LONG-GOOGLE-API-KEY';

  gapi.analytics.auth.authorize({
    container: 'auth-button',
    clientid: CLIENT_ID,
  });

  // Step 4: Create the view selector.
  var viewSelector = new gapi.analytics.ViewSelector({
    container: 'view-selector'
  });

  // Step 5: Create the timeline chart.
  var timeline = new gapi.analytics.googleCharts.DataChart({
    reportType: 'ga',
    query: {
      'dimensions': 'ga:date',
      'metrics': 'ga:sessions',
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
    },
    chart: {
      type: 'LINE',
      container: 'timeline'
    }
  });

  // Step 6: Hook up the components to work together.
  gapi.analytics.auth.on('success', function(response) {
    viewSelector.execute();
  });

  viewSelector.on('change', function(ids) {
    var newIds = {
      query: {
        ids: ids
      }
    }
    timeline.set(newIds).execute();
  });
});
</script>

</body>
</html>

<?php
/*
    //----- Built-in Methods?

    // Visits by date
        $visits = $analytics->getVisitsByDate();

    // Get visits by Operating Systems and return max 100 results
        $visitsByOs = $analytics->getVisitsBySystemOs(array('max-results' => 100));

    // Get referral traffic
        $referralTraffic = $analytics->getReferralTraffic();

    // Get visits by languages
        $visitsByLanguages = $analytics->getVisitsByLanguages();
*/

//----------------------------------------------------//
// Function - Query the "public Google_Service_Analytics_GaData" API
// https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
//----------------------------------------------------//
function getAnalyticsData($analytics, $profileId)
{
    $tableid    = 'ga:'.$profileId;
    $startDate  = '7daysAgo';
    $endDate    = 'today';
    $metrics    = 'ga:sessions';

    // Define optional parameters (dimensions, sort, filters, max-results, )
    $optParams = array(
        //'dimensions' => 'ga:source,ga:keyword',
        'sort' => '-ga:sessions',
        'filters' => 'ga:medium==organic',
        'max-results' => '25'
    );

    // Calls the "Core Reporting API" with query
    $service = $analytics->data_ga->get( 
        $tableid,
        $startDate,
        $endDate,
        $metrics,
        $optParams
    );
    return $service;
/*  
//-------- Query Submitted to GA
$analytics->data_ga->get( 
        'ga:PROFILEID',
        '7daysAgo',
        'today',
        'ga:sessions',
        'ga:source,ga:keyword',
        '-ga:sessions,ga:source',
        'ga:medium==organic',
        '25'
    );
*/
}

//----------------------------------------------------//
// Function - Return first authorized view
//----------------------------------------------------//
function getFirstProfileId($analytics)
{
    // Get the list of accounts for the authorized user
    $accounts = $analytics->management_accounts->listManagementAccounts();

    // Get the user's first view (profile) ID
    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');
    }
}

//----------------------------------------------------//
// END
//----------------------------------------------------//

?>

参考网址:

<?php
"DataChart component of the Embed API queries the Core Reporting API"
https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

"Embed API Dashboard with Server-Side Authorization"
https://ga-dev-tools.appspot.com/embed-api/basic-dashboard/

"Google_Service_Analytics_GaData API"
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide

"Core Reporting API reference guide"
https://developers.google.com/analytics/devguides/reporting/core/v3/reference

"Dimensions and metrics reference page"
https://developers.google.com/analytics/devguides/reporting/core/dimsmets
?>

0 个答案:

没有答案