尝试执行YouTube解析API时出现“禁止错误" [英] Getting 'Forbidden error' when trying to execute youtube analytic API
问题描述
尝试执行youtube Analytics API时,我收到一条错误消息.
I am receiving an error message when trying to execute youtube analytics API.
A service error occurred: Error calling GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DUCaayLD9i5x4MmIoVZxXSv_g&start-date=2016-08-01&end-date=2016-08-07&metrics=views&dimensions=7DayTotals: (403) Forbidden
这是我的代码:
require_once __DIR__.'\google-api-php-client-1-master\src\Google\autoload.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Client.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Service\YouTube.php';
session_start();
$key = file_get_contents('mykey.json');
$OAUTH2_CLIENT_ID = 'xx-xx-xx';
$OAUTH2_CLIENT_SECRET = 'xxx';
$scope = array("https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner-channel-audit", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly","https://www.googleapis.com/auth/youtubepartner");
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
if ($client->getAccessToken()) {
//Check to see if our access token has expired. If so, get a new one and save it to file for future use.
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $client->getAccessToken());
}
$analytics = new Google_Service_YouTubeAnalytics($client);
$channel_url = 'UCaayLD9i5x4MmIoVZxXSv_g';
$ids = 'channel==' . $channel_url . '';
$end_date = '2016-08-07';
$start_date = '2016-08-01';
$optparams = array(
'dimensions' => '7DayTotals',
);
$metric = 'views';
$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
echo '<pre>';print_r($api);die;
}
我已经启用了'youtube analytic API'
,并且从此处
I have already enable 'youtube analytic API'
and I get the access_token from here
我的代码有什么问题,还是我们需要做更多的事情来摆脱这种情况?
What is wrong with my code ,Or do we need to do some more stuff to get rid from this?
推荐答案
看一下代码,看来您是在将新的访问令牌保存到文件的时候生成了一个新的访问令牌(使第一个无效).
Looking at your code, it seems that you are generating a new access token at the point you save it to file (invalidating the first one).
尝试:
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $newToken);
}
这篇关于尝试执行YouTube解析API时出现“禁止错误"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!