4

저는 매번 인증을받지 않아도 백그라운드 크론 작업을 통해 Google 애널리틱스에서 자체 데이터베이스로 데이터를 가져오고 싶습니다.서버 측 백그라운드 서비스에서 Google Analytics API에 액세스하는 방법은 무엇입니까?

내가 이전에 물어 본대로 how to get an Google Analytics OAuth Access Token with user interaction을 알고 있습니다. 사용자 상호 작용이 필요하기 때문에 OAuth를 사용하면 작동하지 않습니다. Google Analytics API Reference에 따르면 OAuth는 물론 액세스 토큰을 사용하여 세션 기반 당 한 번 페이지의 통계에 액세스 할 수 있습니다. 그러나 백그라운드 서비스에서이를 구현하는 지속적인 방법을 찾고 있습니다.

사용자 인증없이 Google 애널리틱스에 액세스하거나 만료되지 않는 액세스 토큰을 얻으려면 어떻게해야합니까?

답변

4

해당 계정이 귀하의 것으로 가정하면 service account을 사용할 수 있습니다. Google Analytics 계정에 계정 수준의 서비스 계정 이메일 주소 읽기 액세스 권한을 부여하면 데이터를 읽을 수 있습니다. 이 후, 당신은 당신이 데이터에 액세스 할 수 있습니다 정상으로 OAuth2 방법은 새로 고침 토큰을 사용하여 다음 번을 인증하기 위해 사용을 요구 사용할 수있는 계정이 아닌 경우

<?php 
session_start(); 
require_once 'Google/Client.php'; 
require_once 'Google/Service/Analytics.php'; 

/************************************************ 
    The following 3 values an befound in the setting 
    for the application you created on Google 
    Developers console. 
    The Key file should be placed in a location 
    that is not accessable from the web. outside of 
    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 = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com'; 
$Email_address = '[email protected]eaccount.com'; 
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12'; 

$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); 
$accounts = $service->management_accountSummaries->listManagementAccountSummaries(); 

//calulating start date 
$date = new DateTime(date("Y-m-d")); 
$date->sub(new DateInterval('P10D')); 

//Adding Dimensions 
$params = array('dimensions' => 'ga:userType'); 
// requesting the data 
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params); 


?><html> 
<?php echo $date->format('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) {  
    print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>"; 
} 

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

?> 

코드는 튜토리얼 Google Service Account with PHP

찢어진 . 이전 질문의 코드를 사용하십시오.

+0

치명적인 오류 : D : \ xampp \ htdocs \ ga_api \ google-api-php에서 'OAuth2 토큰을 새로 고침하는 중 오류가 발생했습니다.'오류 메시지 : '{ "오류": invalid_grant "}' '오류로'Google_Auth_Exception '오류가 발생했습니다. -client-master \ src \ Google \ Auth \ OAuth2.php : 358'무엇이 잘못되었는지 말해 줄 수 있습니까? – Sayed

+0

기계의 Google 유효 기간 확인. 인증을 사용하기 전에 인증이 만료되는 것은 오류입니다. – DaImTo

+0

대답 할 수 있다면 내 컴퓨터의 시간을 Google과 동기화하는 방법은 무엇입니까? – Sayed

관련 문제