Youtube SDK -如何在PHP中获得分析报告访问和数据转储



我希望从我的每个频道的分析报告每分钟下载所有数据,但我得到一个403错误。我需要什么样的权限?如何访问分析报告API?它说这个API对我来说不可用。

另外,服务器2服务器验证是否可以定期获取数据(每天至少10次)?

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
/*
 * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
 * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
 * use this scope.
 */
$client->setScopes(array('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly'));
$redirect = filter_var('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$redirect = str_replace('.php', '', $redirect);
$client->setRedirectUri($redirect);
if (isset($_GET['code'])) {
    if (strval($_SESSION['state']) !== strval($_GET['state'])) {
        die('The session state did not match.');
    }
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    header('Location: ' . $redirect);
}
try {
    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }
    if ($client->getAccessToken()) {
        $youtube = new Google_Service_YouTube($client);
        //die("<pre>" . var_export($youtube->channels->listChannels('id', array('forUsername' => 'kingbach')),1));
        $analytics = new Google_Service_YouTubeAnalytics($client);
        $id = 'channel==<CHANNEL_ID>';
        $start_date = '2016-09-17';
        $end_date = '2016-09-24';
        $optparams = array(
            'onBehalfOfContentOwner' => '<USERNAME>'
        );
        $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];
            }
        }
    } else {
        // If the user hasn't authorized the app, initiate the OAuth flow
        $state = mt_rand();
        $client->setState($state);
        $_SESSION['state'] = $state;
        $authUrl = $client->createAuthUrl();
        $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
    }
} catch (Exception $e) {
    die("<pre>" . $e->getMessage() . "</pre>");
}

您需要在云平台控制台中启用API。详见https://support.google.com/cloud/answer/6158841?hl=en

相关内容

  • 没有找到相关文章

最新更新