我正在尝试使用OAuth2访问PHP中的YouTube Analytics API。在我的方案中,我首先检索频道数据,该数据可以正常运行(即使使用经过身份验证的段)。然后,我在分析通话中解析了频道ID。YouTube Analytics API在我的Google Developer Console中激活。我最终遇到以下错误:
端口错误发生:错误打电话获取https://www.googleapis.com/youtube/analytics/v1/reports?ids=Channel=##MMY_CHANNEL_CHANNEL_CHANNEL_ID##&start-date = 2014-01-01& end-date = 2014-01-25& metrics = view& dimensions = 7dayTotals& stort = day = day:(403)许可不足
这是我的代码。请注意,我手动添加了频道ID,以确保它是绝对正确的。正如我所说:身份验证适用于YouTube数据API,但无法连接到Analytics-API。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$OAUTH2_CLIENT_ID = '##MY_CLIENT_ID##';
$OAUTH2_CLIENT_SECRET = '##MY_SECRET##';
set_include_path('##PATH_TO_CLIENT_LIBRARY##');
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubeAnalytics.php';
session_start();
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$youtube = new Google_Service_YouTube($client);
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$analytics = new Google_Service_YouTubeAnalytics($client);
$id = 'channel==##MY_CHANNEL_ID##';
$start_date = '2014-01-01';
$end_date = '2014-01-20';
$optparams = array(
'dimensions' => '7DayTotals',
'sort' => 'day',
);
$metrics = array(
'views',
'estimatedMinutesWatched',
'averageViewDuration',
'comments',
'favoritesAdded',
'favoritesRemoved',
'likes',
'dislikes',
'shares',
'subscribersGained',
'subscribersLost'
);
$api_response = $metrics;
foreach ($metrics as $metric)
{
$api = $analytics->reports->query($id, $start_date, $end_date, $metric, $optparams);
if (isset($api['rows'])) $api_response[$metric] = $api['rows'][0][0];
}
}
?>
顺便说一句,如果有人使用YouTube Analytics API进行了php-scripts的示例,那么如果您可以分享它们,我会很高兴。我还没有在整个www上看到一个工作示例。
我自己已经找到了答案。问题在线
$client->setScopes('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly');
将其更改为下面的行使脚本工作:
$client->setScopes(array('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly'));