Youtube分析API 403错误
你好,我想知道一些想法 我遵循网站上的步骤 但当我启动应用程序时,我始终会收到以下信息: “超出未经验证使用的每日限制。继续使用需要注册。” 我有两个链接。1在youtube上连接(0auth)如何工作,并给我令牌和第二个链接,该链接提供度量、维度。。。在json中。但是除了上面的留言我什么都没有。 js页面:Youtube分析API 403错误,youtube,youtube-api,Youtube,Youtube Api,你好,我想知道一些想法 我遵循网站上的步骤 但当我启动应用程序时,我始终会收到以下信息: “超出未经验证使用的每日限制。继续使用需要注册。” 我有两个链接。1在youtube上连接(0auth)如何工作,并给我令牌和第二个链接,该链接提供度量、维度。。。在json中。但是除了上面的留言我什么都没有。 js页面: (function() { // Retrieve your client ID from the Google Developers Console at // https://con
(function() {
// Retrieve your client ID from the Google Developers Console at
// https://console.developers.google.com/.
var OAUTH2_CLIENT_ID = '261487559881-d9al0muik318iaa07uiasvqb2gliinpm.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/youtube.readonly'
];
var ONE_MONTH_IN_MILLISECONDS = 1000 * 60 * 60 * 24 * 30;
// Keep track of the currently authenticated user's YouTube channel ID.
var channelId;
// For information about the Google Chart Tools API, see:
// https://developers.google.com/chart/interactive/docs/quick_start
google.load('visualization', '1.0', {'packages': ['corechart']});
// Upon loading, the Google APIs JS client automatically invokes this callback.
// See http://code.google.com/p/google-api-javascript-client/wiki/Authentication
window.onJSClientLoad = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
};
// Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
// If the currently logged-in Google Account has previously authorized
// the client specified as the OAUTH2_CLIENT_ID, then the authorization
// succeeds with no user intervention. Otherwise, it fails and the
// user interface that prompts for authorization needs to display.
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
if (authResult) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Authorization was unsuccessful. Show content related to prompting for
// authorization and hide content that should be visible if authorization
// succeeds.
$('.post-auth').hide();
$('.pre-auth').show();
// Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
// client flow. The current function is called when that flow completes.
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
// Load the client interfaces for the YouTube Analytics and Data APIs, which
// are required to use the Google APIs JS client. More info is available at
// http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
gapi.client.load('youtubeAnalytics', 'v1', function() {
// After both client interfaces load, use the Data API to request
// information about the authenticated user's channel.
console.log(getUserChannel());
getUserChannel();
});
});
}
// Call the Data API to retrieve information about the currently
// authenticated user's YouTube channel.
function getUserChannel() {
// Also see: https://developers.google.com/youtube/v3/docs/channels/list
var request = gapi.client.youtube.channels.list({
// Setting the "mine" request parameter's value to "true" indicates that
// you want to retrieve the currently authenticated user's channel.
mine: true,
part: 'id,contentDetails'
});
request.execute(function(response) {
console.log(response);
if ('error' in response) {
displayMessage(response.error.message);
} else {
// We need the channel's channel ID to make calls to the Analytics API.
// The channel ID value has the form "UCdLFeWKpkLhkguiMZUp8lWA".
channelId = response.items[0].id;
// Retrieve the playlist ID that uniquely identifies the playlist of
// videos uploaded to the authenticated user's channel. This value has
// the form "UUdLFeWKpkLhkguiMZUp8lWA".
var uploadsListId = response.items[0].contentDetails.relatedPlaylists.uploads;
// Use the playlist ID to retrieve the list of uploaded videos.
getPlaylistItems(uploadsListId);
}
});
}
// Call the Data API to retrieve the items in a particular playlist. In this
// example, we are retrieving a playlist of the currently authenticated user's
// uploaded videos. By default, the list returns the most recent videos first.
function getPlaylistItems(listId) {
// See https://developers.google.com/youtube/v3/docs/playlistitems/list
var request = gapi.client.youtube.playlistItems.list({
playlistId: listId,
part: 'snippet'
});
request.execute(function(response) {
if ('error' in response) {
displayMessage(response.error.message);
} else {
if ('items' in response) {
// The jQuery.map() function iterates through all of the items in
// the response and creates a new array that only contains the
// specific property we're looking for: videoId.
var videoIds = $.map(response.items, function(item) {
return item.snippet.resourceId.videoId;
});
// Now that we know the IDs of all the videos in the uploads list,
// we can retrieve information about each video.
getVideoMetadata(videoIds);
} else {
displayMessage('There are no videos in your channel.');
}
}
});
}
// Given an array of video IDs, this function obtains metadata about each
// video and then uses that metadata to display a list of videos.
function getVideoMetadata(videoIds) {
// https://developers.google.com/youtube/v3/docs/videos/list
var request = gapi.client.youtube.videos.list({
// The 'id' property's value is a comma-separated string of video IDs.
id: videoIds.join(','),
part: 'id,snippet,statistics'
});
request.execute(function(response) {
if ('error' in response) {
displayMessage(response.error.message);
} else {
// Get the jQuery wrapper for the #video-list element before starting
// the loop.
var videoList = $('#video-list');
$.each(response.items, function() {
// Exclude videos that do not have any views, since those videos
// will not have any interesting viewcount Analytics data.
if (this.statistics.viewCount == 0) {
return;
}
var title = this.snippet.title;
var videoId = this.id;
// Create a new <li> element that contains an <a> element.
// Set the <a> element's text content to the video's title, and
// add a click handler that will display Analytics data when invoked.
var liElement = $('<li>');
var aElement = $('<a>');
// Setting the href value to '#' ensures that the browser renders the
// <a> element as a clickable link.
aElement.attr('href', '#');
aElement.text(title);
aElement.click(function() {
displayVideoAnalytics(videoId);
});
// Call the jQuery.append() method to add the new <a> element to
// the <li> element, and the <li> element to the parent
// list, which is identified by the 'videoList' variable.
liElement.append(aElement);
videoList.append(liElement);
});
if (videoList.children().length == 0) {
// Display a message if the channel does not have any viewed videos.
displayMessage('Your channel does not have any videos that have been viewed.');
}
}
});
}
// This function requests YouTube Analytics data for a video and displays
// the results in a chart.
function displayVideoAnalytics(videoId) {
if (channelId) {
// To use a different date range, modify the ONE_MONTH_IN_MILLISECONDS
// variable to a different millisecond delta as desired.
var today = new Date();
var lastMonth = new Date(today.getTime() - ONE_MONTH_IN_MILLISECONDS);
var request = gapi.client.youtubeAnalytics.reports.query({
// The start-date and end-date parameters must be YYYY-MM-DD strings.
'start-date': formatDateString(lastMonth),
'end-date': formatDateString(today),
// At this time, you need to explicitly specify channel==channelId.
// See https://developers.google.com/youtube/analytics/v1/#ids
ids: 'channel==' + channelId,
dimensions: 'day',
sort: 'day',
// See https://developers.google.com/youtube/analytics/v1/available_reports
// for details about the different filters and metrics you can request
// if the "dimensions" parameter value is "day".
metrics: 'views',
filters: 'video==' + videoId
});
request.execute(function(response) {
// This function is called regardless of whether the request succeeds.
// The response contains YouTube Analytics data or an error message.
if ('error' in response) {
displayMessage(response.error.message);
} else {
displayChart(videoId, response);
}
});
} else {
// The currently authenticated user's channel ID is not available.
displayMessage('The YouTube channel ID for the current user is not available.');
}
}
// This boilerplate code takes a Date object and returns a YYYY-MM-DD string.
function formatDateString(date) {
var yyyy = date.getFullYear().toString();
var mm = padToTwoCharacters(date.getMonth() + 1);
var dd = padToTwoCharacters(date.getDate());
return yyyy + '-' + mm + '-' + dd;
}
// If number is a single digit, prepend a '0'. Otherwise, return the number
// as a string.
function padToTwoCharacters(number) {
if (number < 10) {
return '0' + number;
} else {
return number.toString();
}
}
// Call the Google Chart Tools API to generate a chart of Analytics data.
function displayChart(videoId, response) {
if ('rows' in response) {
hideMessage();
// The columnHeaders property contains an array of objects representing
// each column's title -- e.g.: [{name:"day"},{name:"views"}]
// We need these column titles as a simple array, so we call jQuery.map()
// to get each element's "name" property and create a new array that only
// contains those values.
var columns = $.map(response.columnHeaders, function(item) {
return item.name;
});
// The google.visualization.arrayToDataTable() function wants an array
// of arrays. The first element is an array of column titles, calculated
// above as "columns". The remaining elements are arrays that each
// represent a row of data. Fortunately, response.rows is already in
// this format, so it can just be concatenated.
// See https://developers.google.com/chart/interactive/docs/datatables_dataviews#arraytodatatable
var chartDataArray = [columns].concat(response.rows);
var chartDataTable = google.visualization.arrayToDataTable(chartDataArray);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(chartDataTable, {
// Additional options can be set if desired as described at:
// https://developers.google.com/chart/interactive/docs/reference#visdraw
title: 'Views per Day of Video ' + videoId
});
} else {
displayMessage('No data available for video ' + videoId);
}
}
// This helper method displays a message on the page.
function displayMessage(message) {
$('#message').text(message).show();
}
// This helper method hides a previously displayed message on the page.
function hideMessage() {
$('#message').hide();
}
(函数(){
//从位于的Google Developers控制台检索您的客户端ID
// https://console.developers.google.com/.
var OAUTH2_CLIENT_ID='261487559881-D9AL0MUIK318IAA07UIASVQB2GLINPM.apps.googleusercontent.com';
变量OAUTH2_作用域=[
'https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/youtube.readonly'
];
var一个月(单位:毫秒)=1000*60*60*24*30;
//跟踪当前已验证用户的YouTube频道ID。
var channelId;
//有关Google图表工具API的信息,请参阅:
// https://developers.google.com/chart/interactive/docs/quick_start
load('visualization','1.0',{'packages':['corechart']});
//加载时,GoogleAPIsJS客户端自动调用此回调。
//看http://code.google.com/p/google-api-javascript-client/wiki/Authentication
window.onJSClientLoad=函数(){
gapi.auth.init(函数(){
setTimeout(checkAuth,1);
});
};
//页面加载后立即尝试OAuth 2.0客户端流。
//如果当前登录的Google帐户之前已授权
//指定为OAUTH2_client_ID的客户机,然后是授权
//在没有用户干预的情况下成功。否则,它将失败,并且
//需要显示提示授权的用户界面。
函数checkAuth(){
gapi.auth.authorize({
客户端id:OAUTH2\u客户端id,
作用域:OAUTH2_作用域,
立即:对
},handleAuthResult);
}
//处理gapi.auth.authorize()调用的结果。
函数handleAuthResult(authResult){
如果(authResult){
//授权成功。隐藏授权提示并显示
//授权成功后应可见的内容。
$('.pre-auth').hide();
$('.post auth').show();
loadAPIClientInterfaces();
}否则{
//授权失败。显示与提示进行授权相关的内容
//授权和隐藏授权后应可见的内容
//成功。
$('.post auth').hide();
$('.pre-auth').show();
//使#登录链接可点击。尝试非即时OAuth 2.0
//客户端流。当前函数在该流完成时调用。
$(“#登录链接”)。单击(函数(){
gapi.auth.authorize({
客户端id:OAUTH2\u客户端id,
作用域:OAUTH2_作用域,
即时:假
},handleAuthResult);
});
}
}
//加载YouTube分析和数据API的客户端界面
//需要使用Google API JS客户端。有关更多信息,请访问
// http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
函数loadAPIClientInterfaces(){
load('youtube','v3',function(){
load('youtubeAnalytics','v1',function(){
//两个客户端接口加载后,使用数据API请求
//有关已验证用户通道的信息。
log(getUserChannel());
getUserChannel();
});
});
}
//调用数据API以检索有关当前
//已验证用户的YouTube频道。
函数getUserChannel(){
//另见:https://developers.google.com/youtube/v3/docs/channels/list
var request=gapi.client.youtube.channels.list({
//将“mine”请求参数的值设置为“true”表示
//您希望检索当前已验证用户的频道。
我的:是的,
部分:'id,contentDetails'
});
请求.执行(函数(响应){
控制台日志(响应);
if(响应中的“错误”){
显示消息(响应.错误.消息);
}否则{
//我们需要频道的频道ID来调用Analytics API。
//通道ID值的形式为“UCdLFeWKpkLhkguiMZUp8lWA”。
channelId=response.items[0].id;
//检索唯一标识的播放列表的播放列表ID
//已上载到已验证用户频道的视频。此值已更改
//表格“UUdLFeWKpkLhkguiMZUp8lWA”。
var uploadsListId=response.items[0]。contentDetails.relatedPlaylists.uploads;
//使用播放列表ID检索已上载视频的列表。
GetPlayItems(uploadsListId);
}
});
}
//调用数据API来检索特定播放列表中的项目
//例如,我们正在检索当前经过身份验证的用户的播放列表
//上传的视频。默认情况下,列表首先返回最近的视频。
函数GetPlayItems(listId){
//看https://developers.google.com/youtube/v3/docs/playlistitems/list
var request=gapi.client.youtube.playlitems.list({
playlid:listId,
部分:“代码片段”
});
请求.执行(函数(响应){
if(响应中的“错误”){
显示消息(响应.错误.消息);
}否则{
if(响应中的“项目”){
//函数的作用是:遍历
//响应并创建一个仅包含
//我们正在寻找的特定属性:videoId。
var videoIds=$.map(response.items,函数(item){
返回item.snippet.resourceId.videoId;
})
<!doctype html>
<html>
<head>
<title>Sample YouTube Analytics API Implementation</title>
<link type="text/css" rel="stylesheet" href="/index.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript" src="/index.js"></script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=onJSClientLoad"></script>
</head>
<body>
<div id="login-container" class="pre-auth">This application requires access to your YouTube account.
Please <a href="#" id="login-link">authorize</a> to continue.
</div>
<div class="post-auth">
<div id="message"></div>
<div id="chart"></div>
<div>Choose a Video:</div>
<ul id="video-list"></ul>
</div>
<a class="plain" href="https://accounts.google.com/o/oauth2/auth?client_id=261487559881-d9al0muik318iaa07uiasvqb2gliinpm.apps.googleusercontent.com&redirect_uri=http://php.com/2/&scope=https://www.googleapis.com/auth/yt-analytics.readonly&response_type=token" target="_blank">
get token </a>
<br><br>
<a class="result" href="">
to see resultat
</a>
</body>
<script>
//(function() {
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
$(document).ready(function(){
var token = getUrlVars()['access_token'];
$('.result').attr('href', 'https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel==mine&start-date=2014-01-01&end-date=2014-02-01&metrics=comments,views,likes&dimensions=month&access_token=' + token);
});
//});
</script>
</html>
})();
YouTube Analytics API
YouTube Data API v3
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}
// Calls the Data API to retrieve the items in a particular playlist. In this
// example, we are retrieving a playlist of the currently authenticated user's
// uploaded videos. By default, the list returns the most recent videos first.
function getPlaylistItems(listId) {
// https://developers.google.com/youtube/v3/docs/playlistItems/list
var request = gapi.client.youtube.playlistItems.list({
playlistId: listId,
part: 'snippet',
maxResults: 30
});
request.execute(function(response) {
if ('error' in response) {
displayMessage(response.error.message);
} else {
if ('items' in response) {
// jQuery.map() iterates through all of the items in the response and
// creates a new array that only contains the specific property we're
// looking for: videoId.
var videoIds = $.map(response.items, function(item) {
return item.snippet.resourceId.videoId;
});
// Now that we know the IDs of all the videos in the uploads list,
// we can retrieve info about each video.
getVideoMetadata(videoIds);
} else {
displayMessage('There are no videos in your channel.');
}
}
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}