チャンネルの各分析レポートから分単位ですべてのデータをダウンロードしたいのですが、403 エラーが発生します。どのような権限が必要ですか? Analytics Reporting API にアクセスするにはどうすればよいですか? API が利用できないと表示されます。
さらに、サーバー 2 サーバー認証は、定期的に (少なくとも 1 日に 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>");
}