我希望每分钟从我的每个频道的分析报告中下载所有数据,但是我收到403错误。我需要什么样的权限?如何访问Analytics Reporting 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>");
}
答案 0 :(得分:0)
您需要在Cloud Platform Console中启用API。有关详细信息,请参阅https://support.google.com/cloud/answer/6158841?hl=en