【问题标题】:Google Analytics API PHP谷歌分析 API PHP
【发布时间】:2015-11-05 00:11:57
【问题描述】:

我想通过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 行

致命错误:带有消息的未捕获异常“Google_Auth_Exception” “无效代码”在 /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->验证(NULL,假)#1 /data/kunden/cylab/BH/produktion/web/htdocs_final/start.php(21): Google_Client->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);

    ?>

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

【问题讨论】:

  • 正在尝试构建什么样的应用程序?一个网络应用程序?如果是这样,请使用这个 hello world 示例:goo.gl/vhIUkM 如果您使用的是服务帐户?使用此示例:goo.gl/76hl8c 描述您希望用户如何与您的应用程序交互以及您尝试访问谁的数据,这应该会告知您应该如何进行。
  • 感谢您的回答。很难说,因为我无法看到我的项目的服务帐户和 Webapp 帐户之间的差异。在我的项目中,我应该使用 Google Analytics、Brandwatch、Sistrix、Adwords 等不同的工具自动创建搜索引擎优化报告。目标是创建 1 个界面,我可以在其中插入日期范围和参数以获取所有工具的信息。目前我正在为这个项目编写文档,并想测试参数以了解它们的概况。所以我们可以列出需要哪些以及如何请求它们。
  • 一个关键的区别是Web应用程序通常是面向外部的。外部用户将在哪里访问自己的数据。用户会访问您的网站并授权它访问他们的数据,然后您的应用程序会使用他们的数据运行。服务帐户类型的应用程序用于访问您自己的私人数据。它可以作为后端流程或按需收集数据,然后将这些数据安全地提供给任何类型的系统、CRM、数据库等......

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


【解决方案1】:

服务帐号

在您可以访问任何 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 教程中提取的代码

网络应用程序

当您希望能够请求用户验证您授予您访问那里数据的权限时,Oauth2 会使用 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 教程中提取的代码

【讨论】:

    【解决方案2】:

    如果您想将 Google Analytics API 与您的应用程序集成,您必须有一个 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
    ?>
    

    【讨论】:

      猜你喜欢
      • 2014-08-28
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多