2015-09-04 2 views
3

Я создал скрипт php, который использует API Google Analytics, я хочу запускать его с помощью задания cron один раз в час. Он отлично работает в моем браузере, но мне нужно время от времени регистрироваться в моей учетной записи gmail и предоставлять доступ.Google API Oauth 2.0 cron job?

Как сохранить данные для входа в систему gmail в скрипте php, чтобы он автоматически подписывался? Этот скрипт будет использовать только мои данные для входа, поэтому он может быть жестко закодирован.

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


?> 

ответ

2

Вместо этого используйте 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

+0

@DalmTo Эй, это правильный подход. Но на данный момент я получаю только «Результаты на дату: 2014-12-14 ga: userType \t ga: пользователи \t ga: сеансы Строки, возвращенные 0". Я добавил свои учетные данные, загрузил .p12 и добавил электронное письмо в качестве пользователя в Google Analytics. – Vaze

+0

, возможно, вы захотите рассмотреть вопрос об изменении запроса на тот, который действительно для вас, вы не думаете? этот код запрашивает только данные для «2014-12-14», «2014-12-14», – DaImTo

+1

О да, я только это заметил. Теперь он отлично работает, большое вам спасибо:) – Vaze

Смежные вопросы