Getting invalid_request for Youtube Analytics with nodejs library - node.js

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.

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

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) => {})

Related

how to create a postgresql instance using OAuth2Client in google using nodejs client library

i have a requirement for creating PostgreSQL instance using google SQL admin API, for the authentication, i want to use OAuth2Client in node js client library
function first() {
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
var tkn = await oAuth2Client.getToken(code_from_another_user);
oAuth2Client.setCredentials(tkn);
return oAuth2Client;
});
function second(oAuth2Client)
{
var req = {
project: prjName,
resource: {
databaseVersion: "POSTGRES_13",
name: name,
region: cregion ,
gceZone: czone,
settings: {*****}
rootPassword: "xxxxx",
},
auth: oAuth2Client,
};
var crpsql = await sqlAdmin.instances.insert(req);
return crpsql;
});
function mainexec()
{
var a = first();
var b = second(a);
});
and i get this error
Error: No access, refresh token, API key or refresh handler callback
is set
here actually, i am trying to create a PostgreSQL instance on other google account cloud platform with there consent using OAuth2Client access token method. anyone please help? any supporting documentation?.
The function first returns oAuth2Client as it is . But in the function second it is converted to JSON object automatically.
so changed the function named second like this
function second(oAuth2Client)
{
var newoAuth2Client = new google.auth.OAuth2(
oAuth2Client._clientId,
oAuth2Client._clientSecret,
oAuth2Client.redirectUri
);
var tokenObj = {
access_token: oAuth2Client.credentials.tokens.access_token,
refresh_token: oAuth2Client.credentials.tokens.refresh_token,
};
newoAuth2Client.credentials = tokenObj;
var req = {
project: prjName,
resource: {
databaseVersion: "POSTGRES_13",
name: name,
region: cregion ,
gceZone: czone,
settings: {*****}
rootPassword: "xxxxx",
},
auth: newoAuth2Client,
};
var crpsql = await sqlAdmin.instances.insert(req);
return crpsql;
});
it worked like a magic.

Retrieve birthdays and genders from people API in server side with token generated client side

I would like to retrieve birthday and gender from google people API in my backend nodejs server.
The access token is generated client side with those 2 scopes:
https://www.googleapis.com/auth/user.birthday.read
https://www.googleapis.com/auth/userinfo.profile
The client sends the accessToken and the server queries the people API in the following way :
const {google} = require('googleapis');
async function getDataFromPeopleAPI(googleId, accessToken) {
try {
let params = {
resourceName: `people/${googleId}`,
personFields: 'birthdays,genders',
access_token: accessToken //generated by client
};
let res = await google.people({
auth: GOOGLE_API_KEY //API key
}).people.get(params);
let {birthdays, genders} = res.data;
} catch (e) {
}
};
The issue is that even though my birthday is set as public and my gender the people api always returns the same result . I don't receive any error code but I never receive the data I want. Here is the response I get:
"resourceName": "people/102865456870877320332",
"etag": "%EgUBBwg3LhoEAQIFBw=="
}
What am I doing wrong when querying the people API ?
Thanks !
This might be too old to answer, but here is the correct format of the request:
const {google} = require('googleapis');
let userData = await google
.people({
version: "v1", // mention the API version
auth: process.env.GOOGLE_SERVER_API_KEY,
})
.people.get({
resourceName: "people/me", // not people/${googleId}
personFields: "genders,birthdays", // mention your scopes
access_token: accessToken, // generated by client
});
Refer to this URL for scope documentation:
https://developers.google.com/people/api/rest/v1/people/get

nodejs googleapis, authClient.request is not a function

I am creating an oauth2client in one function like so and returning it. I actually do pass in the clien id, secret, redirect url, and credentials. Those are all correct from what I have checked.
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
...
credentials = {
access_token: accessToken,
refresh_token: refreshToken
};
oauth2Client.setCredentials(credentials);
I then do this in the function where the oauth2client object is returned:
var plus = google.plus('v1');
console.log(JSON.stringify(oauth_client));
plus.people.get({ userId: 'me' , auth: oauth_client}, function(err, response) {
if(err) {
console.log(err);
} else {
console.log(JSON.stringify(response));
return response;
}
});
However I then get an error message saying that authClient.request is not a function.
TypeError: authClient.request is not a function
at createAPIRequest (/node_modules/googleapis/lib/apirequest.js:180:22)
I'm not sure why I get this error. I also did console.log(JSON.stringify(oauth_client)) to check for a request function and I didn't see any. Someone mentioned that this can't display the full prototype chain and that the request function might actually be there.
The problem is with "oauth_client".I used "google-auth-library" to authenticate.
var googleAuth = require('google-auth-library');
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
oauth2Client.credentials = credentials;
and then use this oauth2Client as oauth_client.
Not sure if you ever resolved this but try checking the scopes you have permissions for.
I was getting this error and turns out I had my scope set to 'https://www.googleapis.com/auth/youtube.readonly' and then when I changed my scope to 'https://www.googleapis.com/auth/youtube.upload' & 'https://www.googleapis.com/auth/youtube' I was able to upload videos instead of getting the error authClient.request is not a function

how to get people info using google api in node js?

I want to verify user google id on server side.So i want user google info by using google api.I have gone through all documentation but i stuck.I have seen this code,its working fine:
var google = require('googleapis');
var plus = google.plus('v1');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
// Retrieve tokens via token exchange explained above or set them:
oauth2Client.setCredentials({
access_token: 'ACCESS TOKEN HERE',
refresh_token: 'REFRESH TOKEN HERE'
});
plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
// handle err and response
});
but this is for google plus.I want to fetch user google profile with id not google plus info. Please help.
For googleapis version 19.0.0, you're gonna have to do something like this:
const googleapis = require('googleapis');
googleapis.people('v1').people.get({
resourceName: 'people/me',
personFields: 'emailAddresses,names',
auth: oauth2Client,
(err, response) => {
// do your thing
}
});
The fields resourceName and personFields are the ones that you might get error for saying that these are mandatory. You can find details on these here https://developers.google.com/people/api/rest/v1/people/get.
As for the scopes, following should be enough for this code snippet:
https://www.googleapis.com/auth/userinfo.email and
https://www.googleapis.com/auth/userinfo.profile

Refresh token of google api do not work properly in nodejs

I am using google api nodejs , I try to get data from google Anaytics
var google = require('googleapis');
var OAuth2Client = google.auth.OAuth2;
var CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxx';
//var REDIRECT_URL = 'http://yieldops.co/oauth2Callback';
var REDIRECT_URL = 'http://localhost:8000/oauth2Callback';
var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET,REDIRECT_URL);
var credentials={}
credentials.expiry_date= "1463514280558",
credentials['refresh_token']="aaaaaaaaa"
credentials['access_token']="aaaaaaaaaaaaaaa"
oauth2Client.setCredentials(credentials)
var gauth = {
'auth': outh2Client,
'ids': 'ga:101' ,
'start-date': '2016-01-01',
'end-date': 'today',
'metrics': 'ga:impressions,ga:sessions,ga:pageviews',
'dimensions': 'ga:date'
}
analytics.data.ga.get(gauth, function (err, gaData) {
console.log("err 1234",err)
console.log("gaData ",gaData)
//console.log("ga",Object.keys(gaData))
})
Note
Now the problem is if access token is not expire then it give me data , and if access token is expire then it gave me 400 error Invalid grant . And if I remove expiry_date from credentials then it gave me error
{ [Error: Invalid Credentials]
code: 401,
errors:
[ { domain: 'global',
reason: 'authError',
message: 'Invalid Credentials',
locationType: 'header',
location: 'Authorization' } ] }
access_token have expire time is 1 hour. You must refresh access_token when it's expired.
oauth2Client.refreshAccessToken(function(err, tokens) {
// your access_token is now refreshed and stored in oauth2Client
// store these new tokens in a safe place (e.g. database)
});
Can you find it here
No need to explicitly refresh token, when access_token expired. Oauth2 Client will refresh token automatically and the request is replayed, provided when you get refresh_token in first authorization, set this refresh_token in OAuth2 client credentials as shown in the following code
const {tokens} = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens);
Still, you want to manually refresh the access_token, then use the following code.
oauth2Client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log(tokens.refresh_token);
}
});
OR
oauth2Client.refreshAccessToken((err, tokens) => {
// your access_token is now refreshed and stored in oauth2Client
// store these new tokens in a safe place (e.g. database)
});
References:
https://github.com/googleapis/google-api-nodejs-client/blob/c00d1892fe70d7ebf934bcebe3e8a5036c62440c/README.md#making-authenticated-requests
https://github.com/googleapis/google-api-nodejs-client/blob/c00d1892fe70d7ebf934bcebe3e8a5036c62440c/README.md#manually-refreshing-access-token
https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens

Resources