如何在没有登录的情况下访问cron作业中的谷歌分析数据?

时间:2015-07-16 11:05:10

标签: php google-analytics

我想访问Google Analytics分析页面视图,并使用cron作业将其存储在数据库中。如何在不登录的情况下访问Google Analytics。

我正在访问cron job中的谷歌帐户。所以我不知道如何离线访问谷歌应用程序。

PLZ PLZ任何人都可以帮助我。

提前致谢。

1 个答案:

答案 0 :(得分:1)

服务帐户将允许您的应用访问您的Google Analytics数据,而不会提示用户访问。

授予访问权限

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

enter image description here

<强>码

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

中删除的代码