Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

node.js - 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' } ] }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...