Youtube API v3:使用服务帐户访问YouTube视频

时间:2018-08-04 01:20:03

标签: .net youtube-api service-accounts youtube-data-api

我正在尝试使用Google服务帐户列出.NET中YouTube Data API v3中的视频。我已经激活了YouTube API,创建了帐户服务,但是每当我尝试从自己的频道中列出视频时,即使我上传了视频,它也会显示0个视频。能否请你帮忙 ?谢谢。

这是代码-

string[] scopes = new string[] 
{    
    YouTubeAnalyticsService.Scope.YtAnalyticsReadonly, 
    YouTubeAnalyticsService.Scope.YtAnalyticsMonetaryReadonly, 
    "https://www.googleapis.com/auth/youtube.force-ssl" 
};

// service account credential
GoogleCredential credential = GoogleCredential.FromFile(SecretPath).CreateScoped(scopes);

var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = channelinfo.AnalyticsAPIFileDataStore
});

Dictionary<string, DateTime?> videoIds = new Dictionary<string, DateTime?>();

var channelResourcesList = youtubeService.Channels.List("contentDetails");
channelResourcesList.Id = channelinfo.ChannelId;
var listResult = channelResourcesList.Execute();
string playListId = listResult.Items[0]?.ContentDetails.RelatedPlaylists.Uploads;

var listOfVideos = youtubeService.PlaylistItems.List("snippet");

listOfVideos.PlaylistId = playListId;
var nextPageToken = "";

while (nextPageToken != null)
{
    listOfVideos.MaxResults = 50;
    listOfVideos.PageToken = nextPageToken;

    // searchresult is empty (listOfVideos.Execute() returns empty result) although channelResourcesList.Execute() worked
    var searchListResult = listOfVideos.Execute();
    nextPageToken = searchListResult.NextPageToken;
}

1 个答案:

答案 0 :(得分:0)

YouTube API不支持服务帐户身份验证。

如果您发现链接的页面没有说出如何设置服务帐户的原因,这是您所链接页面中的错误,这是因为这很可能是生成的文档。我很幸运地联系了团队,他们将对其进行修复,以免其他开发人员感到困惑。

您将需要使用Oauth2并至少对用户进行一次身份验证,然后保存刷新令牌,以便在需要访问API时可以请求新的访问令牌。