0

I am trying to setup nodejs with youtube analytics api. I am currently using a refresh token to try and get access tokens. It works great when using postman but I can't seem to replicate the functionality in nodejs and get a 400: invalid_request with no additional information provided.

Here is my code

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oAuthClient = new OAuth2();

// Retrieve tokens via token exchange explained above or set them:
oAuthClient.setCredentials({
   access_token: "",
   refresh_token: process.env["YOUTUBE_ANALYTICS_REFRESHTOKEN"]
});

var youtubeAnalytics = google.youtubeAnalytics({
   version: 'v1', auth: oAuthClient
});


var moduleExports = {
    retrieveDailyBreakdownViews : function(){   
       var query = {
          ids: 'channel==' + {channelID here},
          'start-date': '2017-05-01',
          'end-date': '2017-05-02',
           metrics: 'views,estimatedMinutesWatched',
           dimensions: 'insightPlaybackLocationType',
           sort: 'views'
       }
  youtubeAnalytics.reports.query(query, (error, response) => {
    console.log(error);
    console.log(response);
  });
}
}

module.exports = moduleExports;

Any ideas? If this doesn't work I can just try and build the query through HTTP/REST but I'd prefer to use the SDK.

mortey
  • 179
  • 1
  • 4
  • 15

2 Answers2

1

In order to be able to refresh the access token, you will also need the client_id and client_secret. What's happening under the hood is the following request to refresh the token (referenced here):

POST https://accounts.google.com/o/oauth2/token
{
    refresh_token: refresh_token,
    client_id: this._clientId,
    client_secret: this._clientSecret,
    grant_type: 'refresh_token'
}

You'll need to initialize your Oauth2 client with :

var oAuthClient = new OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

You'll also need to provide a refresh token that was generated using the same client_id / client_secret if you hardcode the refresh token value

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
1

This is what I ended up doing to fix the issue

var google = require('googleapis');
var googleAuth = require('google-auth-library');
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(process.env["YOUTUBE_CLIENT_ID"], 
process.env["YOUTUBE_CLIENT_SECRET"]);
oauth2Client.credentials.refresh_token = 
process.env["YOUTUBE_ANALYTICS_REFRESHTOKEN"];

var youtubeAnalytics = google.youtubeAnalytics({
    version: 'v1'
});

I then make my calls like this:

youtubeAnalytics.reports.query(query, (error, response) => {})
mortey
  • 179
  • 1
  • 4
  • 15