6

나는PHP에서 Google Analytics 실시간 active 사용자를 가져 오는 방법은 무엇입니까?

$client->setApplicationName("Analytics"); 
$client->setDeveloperKey("key"); 
$service = new Google_Service_Analytics($client); 

$optParams = array(
    'dimensions' => 'rt:medium'); 

try { 
    $results = $service->data_realtime->get(
     'ga:profileid', 
     'rt:activeUsers', 
     $optParams); 
    // Success. 
} catch (apiServiceException $e) { 
    // Handle API service exceptions. 
    $error = $e->getMessage(); 
} 
print_r($results); 

그것은 오류 (401)를 보여줍니다 ... https://github.com/google/google-api-php-client 에서 API 파일을 다운로드하고 코드를 아래에 노력 로그인 필요 '내가 https://console.developers.google.com/project/apps~rational-photon-578/apiui/api/analytics/method/analytics.data.realtime.get

I에서 통화를 시도

필요한 실시간 사용자가 profileid에 속해 있습니다.

그럼 어떻게 로그인 절차를 구현할 수 있습니까? (Google 사이트를 방문하지 않고도)이 작업을 수행 할 수 있습니까? 나는 아래의 코드를 시도

...

여기
$client_id    = 'xxxxxxxxxxxxxxx'; 
$service_account_name = '[email protected]'; 
$key_file_location  = 'location of .p12 keyfile'; 

$client = new Google_Client(); 
$client->setApplicationName("Client_Library_Examples"); 

if (isset($_SESSION['service_token'])) { 
$client->setAccessToken($_SESSION['service_token']); 
} 

$key = file_get_contents($key_file_location); 
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, 
array('https://www.googleapis.com/auth/analytics'), 
$key 
); 

$client->setAssertionCredentials($cred); 
if($client->getAuth()->isAccessTokenExpired()) { 
$client->getAuth()->refreshTokenWithAssertion($cred); 
} 

$_SESSION['service_token'] = $client->getAccessToken(); 
echo $_SESSION['service_token']; 
$service = new Google_Service_Analytics($client); 


$optParams = array(
'dimensions' => 'rt:medium'); 


try { 
$results = $service->data_realtime->get(
    'ga:profileid', 
    'rt:activeUsers', 
    $optParams); 
// Success. 
} catch (apiServiceException $e) { 
// Handle API service exceptions. 
$error = $e->getMessage(); 
} 
print_r($results); 

내가 access_token과 및 세부 사항을 얻고있다 ...하지만 분석 데이터를 가져 오는 오류 때문에 "가 부족합니다 권한을"실패

은 내가 가진 결과는 내가 언급 한 프로필 ID와 Google 콘솔에서 테스트를 만들 때.

답변

2

Google Analytics API에 액세스하려면 인증이 필요합니다. 다른 사용자가 소유 한 데이터가 아닌 자신의 데이터에 액세스하려는 것 같습니다. 이렇게하려면 사용중인 Github에서의 service account.

는 PHP 클라이언트 lib 디렉토리를 작성해야합니다, 서비스를 사용하는 예를 가지고 당신이 그것을 service-account.php

예는 Boooks API를 사용하여 찾을 수 있습니다 차지하고있다. 당신이 어떤 문제가 있다면 당신은 내게 알려

$service = new Google_Service_Analytics($client); 

에 다음

$service = new Google_Service_Books($client); 

변화를 수행하여 구글 웹 로그 분석 API로 변경하고 내가 사용하면 전체 예제를 제공하지 못할 경우 내가 볼 서비스 계정이있는 Google 웹 로그 분석. 다른 사람에 대한

참고 : 액세스를 요청해야하는 실시간 API는 아직 베타 버전이 질문의시

. 일반적으로 액세스하려면 24 시간이 걸립니다.

+0

안녕하세요 덕분에 .. 정말 많이 도움이 :) 지금 내가 오류 "가 부족합니다 무엇입니까 실시간 사용자에게 액세스 할 수있는 "권한"이 있어야합니다. 아래 코드를 시도했습니다. 'code' $ optParams = array ( 'dimensions'=> 'rt : medium'); 시도 { $ 결과 = $ 서비스 -> data_realtime-> GET ( 'GA : 123123123가' 이 무엇을 실온 : activeUsers ', $ optParams를); // 성공. } catch (apiServiceException $ e) { // API 서비스 예외를 처리합니다. $ error = $ e-> getMessage(); } 'code' – jpk

+0

실시간 API는 여전히 베타 버전이므로 액세스 권한을 요청해야합니다. Google에 지금 당장 PC에 액세스 할 수 없습니다. 일반적으로 액세스하려면 24 시간이 걸립니다. – DaImTo

+0

서비스 계정에서 가져온 이메일 주소를 analytics 사용자 계정에 추가하고 사용 권한을 부여했습니다. 이메일 주소에 액세스하는 데 24 시간이 걸립니다. – jpk

1

내가 성공적으로 PHP를 아래의 코드 내 웹 사이트에 내 GA 계정에서 현재 데이터를 표시 한 다음 답변

<?php 

//Cloning Google API's 
//git clone https://github.com/google/google-api-php-client.git 

//Setting include_path in PHP.ini 
//include_path = ".:/usr/local's/lib/php:/path/to/google-api-php-client/src" 

//Alternatively, you can set the same ini directive dynamically in your code. 
$lib_path = $_SERVER['DOCUMENT_ROOT'] . '/path/relative/to/DOCUMENT_ROOT/'; 
set_include_path(get_include_path() . PATH_SEPARATOR . $lib_path . 'google-api-php-client/src'); 

require_once 'Google/Client.php'; 
require_once 'Google/Service/Analytics.php'; 

$keyfile = 'path/relative/to/DOCUMENT_ROOT/xxxxxxxxxxxxxxxx.p12'; // keyfile location 
$gaEmail = '[email protected]'; // email you added to GA 
$gaAuth = 'https://www.googleapis.com/auth/analytics.readonly'; 

// Create Client Object 
$client = new Google_Client(); 
$client->setApplicationName('Google_Analytics'); // name of your app 
$client->setClientId('xxxxxxxxxxxxxxxx.apps.googleusercontent.com'); // from API console 
$client->setAssertionCredentials(new Google_Auth_AssertionCredentials($gaEmail, array($gaAuth), file_get_contents($keyfile))); 

/* Sample Grabbing Analytics data 
$service = new Google_Service_Analytics($client); 
var_dump($service->management_accounts->listManagementAccounts()); 
$response = $service->data_ga->get(
    'ga:87364223', // profile id 
    '2014-09-01', // start date 
    '2014-09-10', // end date 
    'ga:uniquePageviews', 
    array(
     'dimensions' => 'ga:pagePath', 
     'sort' => '-ga:uniquePageviews', 
     'filters' => 'ga:pagePath=~/[a-zA-Z0-9-]+/[a-zA-Z0-9-]+', // http://localhost/browse/style/3#showmoreexample url regex filter 
     'max-results' => '25' 
    ) 
); 
var_dump($response); 
*/ 

// Your analytics profile id. (Admin -> Profile Settings -> Profile ID) 
$profile_id = 'ga:xxxxxxxx'; 
$start = 'yesterday'; 
$end = 'today'; 

try { 
    $service = new Google_Service_Analytics($client); 
    $results = $service->data_ga->get($profile_id, $start, $end, 'ga:visits'); 
    echo $results['totalsForAllResults']['ga:visits']; 
} 
catch(Exception $e) { 
    echo 'There was an error : - ' . $e->getMessage(); 
} 

?> 
관련 문제