php - Google API Oauth 2.0 cron 作业?

标签 php cron google-api google-oauth google-api-php-client

我已经创建了一个使用 Google Analytics API 的 php 脚本,我想每小时用一个 cron 作业运行它。它在我的浏览器中运行良好,但我需要不时使用我的 gmail 帐户登录并授予访问权限。

如何在 php 脚本中保存我的 gmail 登录数据,以便它自动登录?此脚本将仅使用我的登录数据,因此可以进行硬编码。

<?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 = 'xxxxxxxx';
    $client_secret = 'xxxxxxxx';
    $redirect_uri = 'http://example.com/xxxx';


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




//Adding Dimensions
$params = array('dimensions' => 'ga:pagePath', 'metrics' => 'ga:timeOnPage,ga:uniquePageviews');
// requesting the data
$data = $service->data_ga->get("ga:xxxxxxxx", date("Y-m-d"),  date("Y-m-d"), "ga:users,ga:sessions", $params );


?><html>
<?php echo date("Y-m-d") . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){  
    print "<td>".$header['name']."</td>";   
}
?>
</tr>
<?php




//printing each row.
foreach ($data->getRows() as $row) {   



if($row[1]<7.0 && $row[2]>100 ){


 $length =  strlen($row[0]);

 if($length<12){

    $row[0] = substr($row[0], 3);

    print $row[0];







$short_url=$row[0];
$blocked=1;


//PDO 
// configuration
$dbhost     = "localhost";
$dbname     = "xxxxxxxxx";
$dbuser     = "xxxxxxxxx";
$dbpass     = "xxxxx";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// query
$sql = "UPDATE urls SET blocked = :blocked WHERE short_url = :short_url";
$q = $conn->prepare($sql);
$q->execute(array(':short_url'=>$short_url,
                  ':blocked'=>$blocked ));















 }


    print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td><td>".$row[3]."</td></tr>";  

}
}







//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>


?>

最佳答案

使用 service account相反。

服务帐户不需要提示用户访问,因为您必须对其进行设置。转到您要从中检索数据的帐户 的“管理”部分中的 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 Service account Php 中提取的代码

关于php - Google API Oauth 2.0 cron 作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32390956/

相关文章:

linux - 每次程序终止时运行的 cron 中的 Bash 程序

Python crontab - 如何检查 cron 是否正在运行?

javascript - 为什么 Google 的 API 响应对象的属性键是随机的两个字符的字符串?

javascript - 如何将选择的值回显到文本框

php - 如何将带有数据的 http header 发送到 rest Api codeigniter?

php imap 获取连接失败错误

ruby - 如何使用服务帐户从 google drive api 下载文件?

php - 在 foreach() 迭代期间修改数组

php - 似乎 Cron 工作在停止后仍在工作

google-api - 谷歌分析 API 错误