2014-05-13 37 views
6

BenGoogle Analytics gerçek zamanlı activeUsers php olarak nasıl alınır?

$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); 

Bir hata (401) gösterir ... https://github.com/google/google-api-php-client API dosyalarını indirip kodunun altına denedik Girişi Gerekli' i https://console.developers.google.com/project/apps~rational-photon-578/apiui/api/analytics/method/analytics.data.realtime.get

ben çağrıyı çalıştı

Gerekli gerçek zamanlı kullanıcılar profileid ait var.

Peki bunun için bir giriş işlemini (google sitesine gitmeden) nasıl uygulayabilirim? Ben aşağıdaki kodu çalıştı

...

İşte
$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); 

i access_token ve ayrıntıları alıyorum ... ama analiz verisi getirilirken bir hata nedeniyle "yetersiz sayıda izni" başarısız

aldım google konsolundan söz konusu profil kimliğiyle test yaptığımda sonuçlar.

cevap

2

Google Analytics API’sına erişim kimlik doğrulaması gerektirir. Kendi verilerinize erişmek istediğiniz gibi değil, başka bir kullanıcıya ait verilere benziyor. Bunu yapmak için kullandığınız Github bir service account.

php istemci lib oluşturmanız gerekir, bir hizmeti kullanmak için bir örnek vardır bunu service-account.php

örnek Boooks API kullanır bulabilirsiniz hesabı. Eğer herhangi bir sorun varsa Sen bana bildirin

$service = new Google_Service_Analytics($client); 

için aşağıdaki

$service = new Google_Service_Books($client); 

değişiklik yaparak Google analytics API olarak değiştirebilirsiniz ve ben kullanarak size tam bir örnek vermek olamaz diye göreceksiniz Bir hizmet hesabıyla Google Analytics. diğerleri için

Not: erişim istemek zorunda Gerçek zamanlı API hala beta Bu sorunun anda

. Normalde erişim için 24 saat sürer.

+0

Hey sayesinde .. gerçekten çok yardımcı oldu :) Şimdi ben bir hata "yetersiz sayıda alıyorum gerçek zamanlı kullanıcılara erişim için "izin". Aşağıdaki kodu denedim 'code' $ optParams = dizi ( 'boyutlar' => 'rt: orta'); try { $ sonuçları = $ hizmette-> data_realtime-> get ( 'ga: 123123123', 'rt: activeusers', $ optParams); // Başarı. } catch (apiServiceException $ e) { // API hizmeti istisnalarını işlemek. $ error = $ e-> getMessage(); } 'code' – jpk

+0

Gerçek zamanlı API hala beta sürümde erişim istemeniz gerekiyor. Google, şu anda bir PC'ye erişimim yok. Normalde erişim için 24 saat sürer. – DaImTo

+0

Analitik kullanıcı hesabına e-posta adresini (servis hesabından aldım) ekledim ve izinleri verdim. Bu yüzden bu e-posta adresine erişmek için 24 saat sürecek mi? – jpk

1

başarıyla php aşağıda kodu ile web siteme benim GA hesabından cari verilerini görüntülemek adres: cevap için

<?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(); 
} 

?> 
İlgili konular