1

我想從谷歌分析API用戶實時谷歌分析如何給訪問令牌

我下面這個:https://developers.google.com/analytics/devguides/reporting/core/v4/basics

我張貼的數據,如:

$url = 'https://analyticsreporting.googleapis.com/v4/reports:batchGet'; 

//Initiate cURL. 
$ch = curl_init($url); 

$jsonDataEncoded = '{ 
    "reportRequests": 
    [ 
    { 
     "viewId": "109200098", 
     "dateRanges": [{"startDate": "2014-11-01", "endDate": "2014-11-30"}], 
     "metrics": [{"expression": "ga:users"}] 
    } 
    ] 
}' 
; 

//Tell cURL that we want to send a POST request. 
curl_setopt($ch, CURLOPT_POST, 1); 

//Attach our encoded JSON string to the POST fields. 
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); 

//Set the content type to application/json 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request 
$result = curl_exec($ch); 

print_r($result); 

{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } } 

我知道我應該得到一些OAuth,但我沒有得到如何做到這一點。 你能幫我解決嗎? 謝謝!

的index.php和oauth2callback.php

一樣在這裏:https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php

做工精細獲得會話數,現在我想用https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get#auth用於獲取RT:activeUsers

我編輯的index.php如:

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
     // Set the access token on the client. 
     $client->setAccessToken($_SESSION['access_token']); 

     // Create an authorized analytics service object. 
     $analytics = new Google_Service_AnalyticsReporting($client); 

     // Call the Analytics Reporting API V4. 
     $response = getReport($analytics); 

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

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

     // Print the response. 
     printResults($response); 

    } else { 
     $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; 
     header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
    } 

獲取錯誤:未定義的屬性:Google_Service_AnalyticsReporting :: $ data_rea ltime

回答

0

首先,如果你想訪問實時數據,那麼你使用的是錯誤的api。你應該使用realtime api

使用curl進行身份驗證有點複雜。您需要先獲取刷新令牌。一旦你有了,你可以在需要時使用以下命令獲取訪問令牌。

curl \ –request POST \ –data ‘client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token’ \ https://accounts.google.com/o/oauth2/token 

所有你需要做的是粘性& =的access_token令牌您對API的任何請求。

我完全教程可以在這裏Google auth curl

更新發現:

記住實時API是不一樣的報告API。如果您仍然參考報告api,那麼它不起作用。你應該發送一個HTTP現在就不是一個HTTP POST和終點是

https://www.googleapis.com/analytics/v3/data/realtime 

查看文檔realtime.get呼叫的格式是不同勢以及

它不應該是很難,雖然沿着這些東西線

https://www.googleapis.com/analytics/v3/data/realtime?id=XXX&metrics=XXX&accesstoken=XXX 

正如我所說的它的一個HTTP GET所以你可以轉儲它在瀏覽器中測試它,你把它添加到您的捲曲腳本之前。

+0

感謝更新!使用此https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php我可以獲取身份驗證令牌,現在我正在使用https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get#auth獲取數據但無法執行此操作。 –

+0

你的錯誤是什麼?編輯問題並添加新的實時api代碼,並且獲取的錯誤不會刪除已在您的問題中擁有的代碼,只需更新即可。 – DaImTo

+0

未定義的屬性:Google_Service_AnalyticsReporting :: $ data_realtime在/Users/admin/lamp/analytics/index.php –

0

我能夠做到這一點使用的index.php

<?php 

// Load the Google API PHP Client Library. 
require_once __DIR__ . '/vendor/autoload.php'; 

session_start(); 

$client = new Google_Client(); 
$client->setAuthConfig(__DIR__ . '/client_secret.json'); 
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); 
$service = new Google_Service_Analytics($client); 

// If the user has already authorized this app then get an access token 
// else redirect to ask the user to authorize access to Google Analytics. 
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
    // Set the access token on the client. 
    $client->setAccessToken($_SESSION['access_token']); 

    // Create an authorized analytics service object. 
    $analytics = new Google_Service_AnalyticsReporting($client); 

    // Call the Analytics Reporting API V4. 
    $response = getReport($analytics); 

    // Print the response. 
    printResults($response); 



    $result = $service->data_realtime->get(
     'ga:<VIEWID CHANGE>', 
     'rt:activeVisitors' 
    ); 
    echo "<pre>"; 
    print_r($result->totalsForAllResults['rt:activeVisitors']); 
    echo "</pre>"; 

} else { 
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; 
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
} 


/** 
* Queries the Analytics Reporting API V4. 
* 
* @param service An authorized Analytics Reporting API V4 service object. 
* @return The Analytics Reporting API V4 response. 
*/ 
function getReport($analytics) { 

    // Replace with your view ID, for example XXXX. 
    $VIEW_ID = "<VIEW ID>"; 

    // Create the DateRange object. 
    $dateRange = new Google_Service_AnalyticsReporting_DateRange(); 
    $dateRange->setStartDate("7daysAgo"); 
    $dateRange->setEndDate("today"); 

    // Create the Metrics object. 
    $sessions = new Google_Service_AnalyticsReporting_Metric(); 
    $sessions->setExpression("ga:sessions"); 
    $sessions->setAlias("sessions"); 

    // Create the ReportRequest object. 
    $request = new Google_Service_AnalyticsReporting_ReportRequest(); 
    $request->setViewId($VIEW_ID); 
    $request->setDateRanges($dateRange); 
    $request->setMetrics(array($sessions)); 

    $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); 
    $body->setReportRequests(array($request)); 
    return $analytics->reports->batchGet($body); 
} 


/** 
* Parses and prints the Analytics Reporting API V4 response. 
* 
* @param An Analytics Reporting API V4 response. 
*/ 
function printResults($reports) { 
    for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) { 
    $report = $reports[ $reportIndex ]; 
    $header = $report->getColumnHeader(); 
    $dimensionHeaders = $header->getDimensions(); 
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries(); 
    $rows = $report->getData()->getRows(); 

    for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { 
     $row = $rows[ $rowIndex ]; 
     $dimensions = $row->getDimensions(); 
     $metrics = $row->getMetrics(); 
     for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) { 
     print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n"); 
     } 

     for ($j = 0; $j < count($metrics); $j++) { 
     $values = $metrics[$j]->getValues(); 
     for ($k = 0; $k < count($values); $k++) { 
      $entry = $metricHeaders[$k]; 
      print($entry->getName() . ": " . $values[$k] . "\n"); 
     } 
     } 
    } 
    } 
} 
相關問題