PHP中的YouTube Analytics API:我在验证时不断获得“权限不足”

时间:2014-01-25 18:18:16

标签: php youtube-api youtube-analytics

我正在尝试使用OAUTH2在PHP中访问YouTube Analytics API。在我的场景中,我首先检索通道数据,该数据工作正常(即使使用经过身份验证的段)。然后我在我的Analytics-call中解析channel-id。 YouTube Analytics API已在我的Google Developer Console中激活。我最终得到以下错误:

  

发生客户端错误:调用GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3D##MY_CHANNEL_ID##&start-date=2014-01-01&end-date=2014-01-25&metrics=views&dimensions=7DayTotals&sort=day时出错:(403)权限不足

这是我的代码。请注意,我手动添加了我的频道ID,以确保它绝对正确。正如我所说:该身份验证适用于YouTube Data 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脚本的示例,我会很高兴你能分享它们。我还没有看到整个WWW上的一个工作示例。

1 个答案:

答案 0 :(得分:4)

我自己已经找到了答案。问题在于

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