Google AnalyticsAPI PHP

时间:2015-08-12 11:45:24

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

我想使用Google Analytic API进行查询。我使用Google Developers Guide和其他一些示例。在HelloAnalytics示例中,我必须使用服务帐户登录,它才有效。在另一个例子中,我使用Webapp身份验证。这是我用过的代码

 <?php
// Load the Google API PHP Client Library.
require_once realpath(dirname(__FILE__) . '/GoogleClientApi/src/Google/autoload.php');
$client = new Google_Client();

$app_name = 'API Project';
$analytics_client_id = 'XXXX.apps.googleusercontent.com';
$analytics_client_secret = 'XXXXX';
$analytics_developerToken = 'XXXXX';
$redirect_uri = "http://bh.cylab.cybay-ebox.de/start.php";
$scope = "https://www.googleapis.com/auth/analytics.readonly";

$client->setApplicationName($app_name);
$client->setClientId($analytics_client_id);
$client->setClientSecret($analytics_client_secret);
$client->setDeveloperKey($analytics_developerToken);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array($scope));

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()) {
    $_SESSION['token'] = $client->getAccessToken();
} else {
    $loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s&access_type=%s",$scope,$state,$redirect_uri,$analytics_client_id,$access_type);
    header('Location: '.$loginUrl);
}

$analytics = new Google_AnalyticsService($client);

//get Accounts Hierachien abrufen!

$accounts = $analytics->management_accounts->listManagementAccounts();
$a_items = $accounts->getItems();

echo count($a_items)." Accounts<br>";
if(count($a_items)!=0)
{
    foreach($a_items as $account)
    {
        echo 'Account ID: '.$account->getID().'<br>';
        echo 'Account Name: '.$account->getName().'<br>';
        //get web properties
        $webProperties = $analytics->management_webproperties->listManagementWebproperties($account->getID());
        $w_items = $webProperties->getItems();

        echo count($w_items)." Webproperties<br>";
        if(count($w_items)!=0)
        {
            foreach($w_items as $webproperty)
            {
                echo '*Webproperty ID: '.$webproperty->getId().'<br>';
                echo '*Webproperty Name: '.$webproperty->getName().'<br>';
                //get profiles
                $profiles = $analytics->management_profiles->listManagementProfiles($account->getID(), $webproperty->getId());
                $p_items = $profiles->getItems();

                //get analytics data
            }
        }
    }
}
function getVisits($analytics, $from, $to, $profile_id, $channel)
{
    $optParams = array(
        'dimensions' => 'ga:source,ga:keyword',
        'sort' => '-ga:sessions',
        'filters' => 'ga:medium=='.$channel
    );

    return $analytics->data_ga->get(
        'ga:'.$profile_id,
        $from = '2015-08-10',
        $to = '2015-08-11',
        'ga:sessions',
        $optParams
    );
}

$result = getVisits($analytics, $i, $profile->getId(), $channel);
$rows = getValue($result);
if($rows != null)
{
    foreach($rows as $result)
    {
        echo 'source: '.$result[0].'<br>';
        echo 'keyword: '.$result[1].'<br>';
        echo 'visits:'.$result[2].'<br>';
    }
}
function getValue($results)
{
    if(count($results->getRows())>0)
    {
        $rows = $results->getRows();
        return $rows;
    }
    return null;
}

我用XXXX替换了PW,我在浏览器中收到了这样的失败消息

  

警告:缺少Google_Client :: authenticate()的参数1,名为   在/data/kunden/cylab/BH/produktion/web/htdocs_final/start.php上线   21并定义于   /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Client.php   在第125行

     

致命错误:未捕获的异常&#39; Google_Auth_Exception&#39;与消息   &#39;无效的代码&#39;在   /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Auth/OAuth2.php:88   堆栈跟踪:#0   /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Client.php(128):   Google_Auth_OAuth2-&gt; authenticate(NULL,false)#1   /data/kunden/cylab/BH/produktion/web/htdocs_final/start.php(21):   Google_Client-&gt; authenticate()#2 {main}引入   /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Auth/OAuth2.php   在第88行

我希望你能帮助我。

工作HelloAnalytics

<?php

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

      // Load the Google API PHP Client Library.
    require_once realpath(dirname(__FILE__) . '/GoogleClientApi/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 = 'XXXXXf@developer.gserviceaccount.com';
      $key_file_location = "http://".$_SERVER['HTTP_HOST']."/client_secrets.p12";

      // Create and configure a new client object.
      $client = new Google_Client();
      $client->setApplicationName("HelloAnalytics");
      $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) {
        //Calls the Core Reporting API and queries
        // Gewünschte Metriken hier abfragen! 
       return $analytics->data_ga->get(
           'ga:' . $profileId,
           '2015-08-10',
           '2015-08-11',
           'ga:sessions'
                  );
    }

    function printResults(&$results) {
      // 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 "First view (profile) found: $profileName\n";
        print "Total sessions: $sessions\n";
      } else {
        print "No results found.\n";
      }
    }

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

    ?>

也许我应该结合这两个代码,但我不知道怎么做?

2 个答案:

答案 0 :(得分:0)

服务帐户

在您访问任何Google API之前,您需要先在Google Developers控制台中创建应用程序。如果您创建了服务帐户身份验证,则只能访问自己的Google Analytics帐户。

服务帐户无需提示用户进行访问,因为您必须进行设置。转到要从中检索数据的帐户的“管理”部分中的Google Analytics网站。以用户身份添加服务帐户电子邮件地址。这非常重要,必须在帐户级别,只需给予他们读取权限。

<?php
   require_once 'Google/autoload.php';
   session_start();     
/************************************************   
 The following 3 values an befound in the setting   
 for the application you created on Google      
 Developers console.         Developers console.
 The Key file should be placed in a location     
 that is not accessable from the web. outside of 
 web root.       web root.

 In order to access your GA account you must    
 Add the Email address as a user at the     
 ACCOUNT Level in the GA admin.         
 ************************************************/
    $client_id = '[Your client id]';
    $Email_address = '[YOur Service account email address Address]';     
    $key_file_location = '[Locatkon of key file]';      

    $client = new Google_Client();      
    $client->setApplicationName("Client_Library_Examples");
    $key = file_get_contents($key_file_location);    

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

    $cred = new Google_Auth_AssertionCredentials($Email_address,         
                             array($scopes),        
                             $key);     

    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {        
         $client->getAuth()->refreshTokenWithAssertion($cred);      
    }       

    $service = new Google_Service_Analytics($client);



    //Adding Dimensions
    $params = array('dimensions' => 'ga:userType'); 
    // requesting the data  
    $data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );     
?>

<html>   
Results for date:  2014-12-14<br>
    <table border="1">   
        <tr>     
        <?php    
        //Printing column headers
        foreach($data->getColumnHeaders() as $header){
             print "<td><b>".$header['name']."</b></td>";       
            }       
        ?>      
        </tr>       
        <?php       
        //printing each row.
        foreach ($data->getRows() as $row) {        
            print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";   
        }    
?>      
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>     
</table>     
</html>  

代码从Google Analytics Service account教程

中删除

网络应用

当您希望能够请求用户进行身份验证时,您可以使用Web应用程序凭据来授予您访问该数据的权限。

<?php    

    require_once 'Google/autoload.php';
    session_start(); 

    // ********************************************************  //
    // Get these values from https://console.developers.google.com
    // Be sure to enable the Analytics API
    // ********************************************************    //
    $client_id = '[Your Client Id]';
    $client_secret = '[Your client Secret]';
    $redirect_uri = '[Your Redirect URI]';


    $client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
    $client->setAccessType('offline');   // Gets us our refreshtoken


    //For loging out.
    if ($_GET['logout'] == "1") {
    unset($_SESSION['token']);
       }


    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {

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

    // Step 1:  The user has not authenticated we give them a link to login    
    if (!$client->getAccessToken() && !isset($_SESSION['token'])) {

        $authUrl = $client->createAuthUrl();

        print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }    


    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
        print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";


        print "Access from google: " . $_SESSION['token']."<br>"; 

        $client->setAccessToken($_SESSION['token']);
        $service = new Google_Service_Analytics($client);    

        // request user accounts
        $accounts = $service->management_accountSummaries->listManagementAccountSummaries();


        foreach ($accounts->getItems() as $item) {

        echo "<b>Account:</b> ",$item['name'], "  " , $item['id'], "<br /> \n";

        foreach($item->getWebProperties() as $wp) {
            echo '-----<b>WebProperty:</b> ' ,$wp['name'], "  " , $wp['id'], "<br /> \n";    
            $views = $wp->getProfiles();
            if (!is_null($views)) {
                                // note sometimes a web property does not have a profile / view

                foreach($wp->getProfiles() as $view) {

                    echo '----------<b>View:</b> ' ,$view['name'], "  " , $view['id'], "<br /> \n";    
                }  // closes profile
            }
        } // Closes web property

    } // closes account summaries
    }


?>

代码从Google Analytics Oauth2教程

中删除

答案 1 :(得分:0)

如果您要将Google AnalyticsAPI与您的应用程序集成,则必须拥有Google API控制台项目并启用Analytics API。有关详细信息Google Analytics API Integration & Example

<?php
include 'CustomAnalytcs_class.php';
$service_account_email = 'apinotesdemo@active-future-171705.iam.gserviceaccount.com';
// Service account Email ID
$key_file_location = 'GoogleAnalytics-fa32e1a557ad.p12'; // P12 Format Private Key File
$analytics = new CustomAnalytcs_class($service_account_email, $key_file_location);
$realtimedata = $analytics->getRealtimeData(); // Get Real Time Data
$sessiondata = $analytics->getSessonData();// Get Real Time Session Data
?>
相关问题