简体   繁体   English

Google Analytics API PHP

[英]Google Analytics API PHP

I want to make querys with the Google Analytic API . 我想使用Google Analytic API进行查询。 I work with the Google Developers Guide and some other examples. 我使用《 Google开发人员指南》和其他一些示例。 With the HelloAnalytics example i have to use the Service Account login and it works. 在HelloAnalytics示例中,我必须使用服务帐户登录名,并且它可以工作。 In another example I use the Webapp authentication. 在另一个示例中,我使用Webapp身份验证。 This is my used code 这是我用过的代码

 <?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;
}

I replaced the PW's with XXXX i get a Failure Message in the Browser like this 我用XXXX替换了PW,在浏览器中收到了这样的失败消息:

Warning: Missing argument 1 for Google_Client::authenticate(), called in /data/kunden/cylab/BH/produktion/web/htdocs_final/start.php on line 21 and defined in /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Client.php on line 125 警告:缺少Google_Client :: authenticate()的参数1,该参数在第21行的/data/kunden/cylab/BH/produktion/web/htdocs_final/start.php中调用,并在/ data / kunden / cylab / BH / produktion /中定义第125行的web / htdocs_final / GoogleClientApi / src / Google / Client.php

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Invalid code' in /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Auth/OAuth2.php:88 Stack trace: #0 /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Client.php(128): Google_Auth_OAuth2->authenticate(NULL, false) #1 /data/kunden/cylab/BH/produktion/web/htdocs_final/start.php(21): Google_Client->authenticate() #2 {main} thrown in /data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Auth/OAuth2.php on line 88 致命错误:/data/kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Auth/OAuth2.php:88堆栈跟踪:#0 / data中未捕获的异常“ Google_Auth_Exception”,消息为“无效代码” /kunden/cylab/BH/produktion/web/htdocs_final/GoogleClientApi/src/Google/Client.php(128):Google_Auth_OAuth2-> authenticate(NULL,false)#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

I hope you can help me. 我希望你能帮助我。

The working HelloAnalytics is 工作正常的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);

    ?>

Maybe I should combine the two codes but I don't know how? 也许我应该将这两个代码结合起来,但是我不知道怎么做?

Service account 服务帐号

Before you can access any of the Google APIs you need to first create your application in the Google Developers console. 您需要先在Google Developers控制台中创建应用程序,然后才能访问任何Google API。 If you create a service account authentication you will only be able to access your own Google Analytics account. 如果您创建服务帐户身份验证,则只能访问自己的Google Analytics(分析)帐户。

A service account doesn't need to prompt a user for access because you have to set it up. 服务帐户不需要提示用户访问权限,因为您必须进行设置。 Go to the Google Analytics website in the Admin section for the Account you want to retrieve data from. 转到您要从中检索数据的帐户的“管理”部分中的Google Analytics(分析)网站。 Add the service account email address as a user. 将服务帐户的电子邮件地址添加为用户。 This is very important it must be at the account level just give them read access. 这一点非常重要,必须在帐户级别授予他们读取权限。

<?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>  

code ripped from Google Analytics Service account tutorial Google Analytics(分析)服务帐户教程中窃取的代码

Web application Web应用程序

A web application credentials are used for Oauth2 when you want to be able to request a user authenticate you giving you permission to access there data. 当您希望能够请求用户身份验证并授予您访问那里的数据的权限时,Web应用程序凭据将用于Oauth2。

<?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
    }


?>

code ripped from Google Analytics Oauth2 tutorial Google Analytics(分析)Oauth2教程中摘录的代码

If you want to integrate the Google Analytics API with your application, you must have a Google API console project and enable Analytics API. 如果要将Google Analytics(分析)API与应用程序集成,则必须具有Google API控制台项目并启用Analytics(分析)API。 For more details Google Analytics API Integration & Example 有关更多详细信息, Google Analytics API集成和示例

<?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
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM