Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

每次调用任何接口,access token就会被刷新一次 #232

Open
zyujiawei opened this issue Jun 15, 2017 · 8 comments
Open

每次调用任何接口,access token就会被刷新一次 #232

zyujiawei opened this issue Jun 15, 2017 · 8 comments

Comments

@zyujiawei
Copy link

我用的构建函数是带了存入和取出token的,为什么每次调用任何接口,token就会被刷新一次

@JacksonTian
Copy link
Member

没有正确使用。

@zyujiawei
Copy link
Author

zyujiawei commented Jun 16, 2017

比如

var wechat_api = new API(keystone.get('appid'), keystone.get('appsecret'),function(callback){
	//获取token的函数
		token.model.findOne().exec(function(err, result) {
			if (result != null){
				keystone.set('access_token',result.content);
				console.log("[wechat]reading token :"+result.content);
				callback(null,result.content);
			} else {
				callback(err);
			}
		});
	},function(newtoken,callback){
		token.model.remove(function(){
			var newToken = new token.model({
				content: newtoken.accessToken,
			});
			newToken.save(function(){
				keystone.set('access_token',newtoken.accessToken);
				console.log("[wechat]token has been saved :"+newtoken.accessToken);
				callback();
			});
		});
	});

wechat_api.xxxx();
这样在xxxx都会打印一次token被读了token被存了,请问问题在哪里

@JacksonTian
Copy link
Member

看起来木有错啊。

@zyujiawei
Copy link
Author

然后我在代码下面调用wechat_api时就发现每次都会重新拿一个token

@weconquered
Copy link

应该是 callback(null,result.content); content的格式不对。 要求的格式如下:

{
accessToken:"XXXXX",
expireTime: 毫秒数
}

@nick-ma
Copy link
Member

nick-ma commented Jul 2, 2018

检查一下第三个参数(回调函数)里面写的result.content的格式,要符合

{
accessToken:"XXXXX",
expireTime: 毫秒数
}

@zhu5439peng
Copy link

zhu5439peng commented Jul 30, 2018

var WechatAPI = require('wechat-api');
var api = new WechatAPI('appid', 'secret', function (callback) {
// 传入一个获取全局token的方法
fs.readFile('access_token.txt', 'utf8', function (err, txt) {
if (err) {return callback(err);}
callback(null, JSON.parse(txt));
});
}, function (token, callback) {
// 请将token存储到全局,跨进程、跨机器级别的全局,比如写到数据库、redis等
// 这样才能在cluster模式及多机情况下使用,以下为写入到文件的示例
fs.writeFile('access_token.txt', JSON.stringify(token), callback);
});

官方的这个例子,跑了很多次,一直报错
后来错误追踪到了这里:
callback(null, JSON.parse(txt));
修改成
var strToken=JSON.parse(txt); callback(null, strToken);

@JacksonTian
Copy link
Member

@zhu5439peng 有区别?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants