1

我試圖做一些分析查詢從服務器到服務器。 我正在使用laravel和https://github.com/google/google-api-php-client庫。Youtube Analytics API PHP無效查詢。查詢不符合預期

這是我使用的代碼:

$client = new Google_Client(); 
$key = file_get_contents(storage_path('key.p12')); 
$cred = new Google_Auth_AssertionCredentials(
     '***@developer.gserviceaccount.com', array('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly'), $key); 
$client->setAssertionCredentials($cred); 
if ($client->getAuth()->isAccessTokenExpired()) { 
    $client->getAuth()->refreshTokenWithAssertion($cred); 
} 

Session::put('service_token', $client->getAccessToken()); 


    $service = new Google_Service_YouTubeAnalytics($client); 
    $id = 'channel==MINE'; 
    $start_date = '2014-05-01'; 
    $end_date = '2014-06-30'; 

    $optparams = array(
    'dimensions' => 'day', 
    'sort' => 'day,-views' 
); 

    $metric = 'views,estimatedMinutesWatched'; 

    $api = $service->reports->query($id, $start_date, $end_date, $metric, $optparams); 

    $service = new Google_Service_YouTubeAnalytics($client); 
    $id = 'channel==MINE'; 
    $start_date = '2014-05-01'; 
    $end_date = '2014-06-30'; 

    $optparams = array(
    'dimensions' => 'day', 
    'sort' => 'day,-views' 
); 

    $metric = 'views,comments,favoritesAdded,likes,dislikes,estimatedMinutesWatched,averageViewDuration';//'views,estimatedMinutesWatched'; 

    $api = $service->reports->query($id, $start_date, $end_date, $metric, $optparams); 

我的問題是,認證工作得很好,但我不能讓分析查詢得到的要努力,我發現了以下錯誤:

Error calling GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2014-05-01&end-date=2014-06-30&metrics=views%2CestimatedMinutesWatched&dimensions=day&sort=day%2C-views: (400) Invalid query. Query did not conform to the expectations. 

即使完全相同的查詢在API Explorer中工作: https://developers.google.com/apis-explorer/#p/youtubeAnalytics/v1/youtubeAnalytics.reports.query?ids=channel%253D%253DMINE&start-date=2014-05-01&end-date=2014-06-30&metrics=views%252CestimatedMinutesWatched&dimensions=day&sort=day%252C-views&_h=1&

任何想法?

+0

嗨,我有同樣的問題,我猜!你是如何修改oAuth2的? – zeidanbm 2016-01-23 20:05:57

回答

3

我測試了您的查詢並且工作正常,但顯然YouTube不支持服務帳戶。 documentation表示在這種情況下應該返回403,但由於某種原因,它將返回400

+0

那麼這可能是問題所在,但在分析文檔中找不到任何內容。無論如何,這是一個可憐的事,我可以用它來做其他類型的api,但不是youtube ......無論如何,我會將它改爲oAuth2,然後用它來嘗試。 – 2014-11-04 07:00:30

+2

這就是問題所在,我將它修改爲oAuth2,它的功能就像是一種魅力,可惜在互聯網上沒有這個教程。當我有更多時間時,我會寫下我的經驗,以及如何設置它。 – 2014-11-04 07:20:15

+0

在我鏈接的頁面中,如果您搜索'服務帳戶',您會發現:'YouTube不支持服務帳戶,並且如果您嘗試使用服務帳戶進行驗證,則會出現此錯誤。 – 2014-11-04 14:08:48

0

您需要添加一個谷歌API密鑰

https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2014-05-01&end-date=2014-06-30&metrics=views%2CestimatedMinutesWatched&dimensions=day&sort=day%2Cviews&key={YOUR_API_KEY} 

此外,如果你看看你的字符串你在哪裏「-views」應該只是「意見」沒有破折號 您可以使用末尾類型的錯誤Google自動化工具生成有效的鏈接。

https://developers.google.com/youtube/analytics/v1/