Error accessing analytics API with ruby gem

2019-08-21 19:47发布

问题:

I am having problems to obtain the the number of views per video. What i got is so far:

First of all I logged in as the youtube user and went to the developer console. There I granted access to the Youtube APIs. I also generated a server key with a p12 file, which I downloaded.

key_file = "***/***.p12"
issuer = "****@developer.gserviceaccount.com"

Then I initiate the youtube client using the ruby library. I know I need two scopes:

data_scope = "https://www.googleapis.com/auth/youtube"
analytics_scope = "https://www.googleapis.com/auth/yt-analytics.readonly"

Finally its time to create the actual clients

# Youtube Data and Analytics Client
$youtube_client = Google::APIClient.new(
     :application_name => "Youtube Monitoring",
     :application_version => "0.1")
$youtube_data_config = $youtube_client.discovered_api('youtube', 'v3')
$youtube_analytics_config = $youtube_client.discovered_api('youtubeAnalytics', 'v1')
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, 'notasecret')
$youtube_client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience => 'https://accounts.google.com/o/oauth2/token',
  :scope => [data_scope, analytics_scope],
  :issuer => issuer,
  :signing_key => key)
$youtube_client.authorization.fetch_access_token!

Once this client is created I want to retrieve all of the videos that I uploaded:

video_ids = $youtube_client.execute(:api_method => $youtube_data_config.search.list, :parameters => {:for_mine => true, :maxResults => 50, :part => "snippet"})

And for each video I'd like to retrieve the number of views it got in a certain time frame. Lets take the last video of the retrieved ones:

video_id = video_ids.data.items.last.id.videoId
channel_id = video_ids.data.items.last.snippet.channelId

Now for this video I'd like to get the number of views:

analytics = $youtube_client.execute(:api_method => $youtube_analytics_config.reports.query, :parameters => {"ids" => "channel==#{channel_id}", "filters" => "video==#{video_id}", "start-date" => "2013-01-01", "end-date" => "2014-01-10", "metrics" => "views"})

An this is where I am getting problems. I am getting a forbidden call:

body=>"{\n \"error\": {\n  \"errors\": [\n   {\n    \"domain\": \"global\",\n    \"reason\": \"forbidden\",\n    \"message\": \"Forbidden\"\n   }\n  ],\n  \"code\": 403,\n  \"message\": \"Forbidden\"\n }\n}\

I am puzzled why this doesn't work. I've tried a number of times but always with the same result. What am I doing wrong?