Comments (11)
It’s sample code. use redis/db instead of.
在 2016年3月31日,下午5:26,dc <[email protected] mailto:[email protected]> 写道:
Your examples don't seem to work to get started...
'use strict';
let debug = require('debug')('wechat-api');
let path = require('path');
let fs = require('fs');let AppConfig = require('../../private/AppConfig');
var WechatAPI = require('wechat-api');
let tokenFilePath = path.join(__dirname, 'access_token.txt');
debug('init', tokenFilePath);
var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET, function (callback) {
// 传入一个获取全局token的方法
fs.readFile(tokenFilePath, 'utf8', function (err, txt) {
debug('read token ', tokenFilePath, txt);
if (err) {return callback(err);}
callback(null, JSON.parse(txt));
});
}, function (token, callback) {
// 请将token存储到全局,跨进程、跨机器级别的全局,比如写到数据库、redis等
// 这样才能在cluster模式及多机情况下使用,以下为写入到文件的示例
debug('write token to ', tokenFilePath, token);
fs.writeFile(tokenFilePath, JSON.stringify(token), callback);
});// var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET);
api.updateRemark('open_id', 'remarked', function (err, data, res) {
debug('updateRemark', data, res);
});
results:wechat-api init +56ms /Users/dc/dev/rikai/boteditor/lib/wechat/access_token.txt
wechat-api read token +11ms /Users/dc/dev/rikai/boteditor/lib/wechat/access_token.txt undefined
wechat-api updateRemark +1ms undefined undefinedso no token is being created or read.
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub #136
from wechat-api.
so this code does not return a token or a usable API?
from wechat-api.
If i obtain a token by my own code, can it be passed to this API for using the api.send ...
methods?
from wechat-api.
this code works fine to obtain a token
but how to then use wechat-api with this token?
'use strict';
let syncRequest = require('sync-request');
let debug = require('debug')('WcTokenManager');
let AppConfig = require('../../private/AppConfig');
let WcTokenManager = {};
// TODO - store this in DB so we can access across multiple servers...
let tokenObj = null;
WcTokenManager.checkToken = function() {
if (!tokenObj) {
tokenObj = WcTokenManager.getNewAccessToken();
}
// else get a new token
var nowTime = Math.floor(new Date().getTime() / 1000);
var diff = tokenObj.expiresAt - nowTime;
if (diff <= 100) {
tokenObj = WcTokenManager.getNewAccessToken();
}
return tokenObj;
};
// // TODO - save to db
// WcTokenManager.saveAccessToken = function(accessToken) {
//
// // expiresIn = 10; // for test expiresIn immediately
// var expiresIn = accessToken.expiresIn || 7200;
//
// var currentTime = Math.floor(new Date().getTime() / 1000);
//
// var tokenObj = {
// appId: ServerConfig.appId,
// token: accessToken.access_token,
// getTokenAt: currentTime,
// expiresIn: expiresIn,
// expiresAt: currentTime + expiresIn,
// createdAt: new Date()
// };
//
// WcTokenManager.remove({ appId: ServerConfig.appId });
// WcTokenManager.insert(tokenObj);
//
// Logger.log('saveAccessToken', tokenObj);
// tokenCache = tokenObj;
// return tokenObj;
// };
//
// https://mp.weixin.qq.com/wiki/11/0e4b294685f817b95cbed85ba5e82b8f.html
WcTokenManager.getNewAccessToken = function() {
var params = {
appid: AppConfig.APP_ID,
secret: AppConfig.APP_SECRET,
grant_type: 'client_credential'
};
var url = AppConfig.API_ENDPOINT + '/cgi-bin/token';
url += `?grant_type=client_credential&appid=${params.appid}&secret=${params.secret}`;
// debug('getNewAccessToken url', url);
var res = syncRequest('GET', url);
// debug('res', res);
var body = res.getBody().toString();
var rawToken = JSON.parse(body);
var expires_in = rawToken.expires_in || 7200;
var currentTime = Math.floor(new Date().getTime() / 1000);
var tokenObj = {
appId: AppConfig.APP_ID,
access_token: rawToken.access_token,
expires_in: expires_in,
expires_at: currentTime + expires_in,
createdAt: new Date(),
createdAtSecs: currentTime
};
debug('gotToken', tokenObj);
return tokenObj;
};
WcTokenManager.tokenString = function() {
var token = WcTokenManager.checkToken().access_token;
return token;
};
// startup
WcTokenManager.checkToken();
module.exports = WcTokenManager;
from wechat-api.
'use strict';
let debug = require('debug')('wechat-api');
let path = require('path');
let redisClient = ...
let AppConfig = require('../../private/AppConfig');
var WechatAPI = require('wechat-api');
debug('init', tokenFilePath);
var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET, function (callback) {
redisClient.get('token_key', function (err,data) {
if (err) {return callback(err);}
callback(null, data && JSON.parse(data));
});
}, function (token, callback) {
redis.set('token_key', JSON.stringify(token),callback);
});
// var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET);
api.updateRemark('open_id', 'remarked', function (err, data, res) {
debug('updateRemark', data, res);
});
from wechat-api.
WechatAPI can auto get new token. You just need provide a save/get interface.
from wechat-api.
so
redisClient.get('token_key', function (err,data) {
callback(null, data && JSON.parse(data));
^ this is the command that calls the API of your library?
callback - passed in API
null - your API expects a null for first argument?
data && JSON.parse(data) - what is this???
I don't understand why the third param needs to &&
with the JSON.parse version??
what is the API expecting?
is there any actual documentation on this?
it seems very obfuscated in order to use this API?
from wechat-api.
here is some simple code to call WeChat APIs.
dataObject is a wechat JSON package.
WcApi.sendMessageToUser = function(dataObject) {
var accessToken = WcTokenManager.tokenString();
var url = AppConfig.API_ENDPOINT + '/cgi-bin/message/custom/send?access_token=' + accessToken;
debug('sendMessageToUser:' + JSON.stringify(dataObject, null, 2));
debug('url:', url);
request.post(
url,
{
body: dataObject,
json: true
}
, function(error, result) {
from wechat-api.
callback(null, data && JSON.parse(data));
//equals
if(data) {
callback(null, JSON.parse(data));
} else {
callback(null)
}
from wechat-api.
thanks @looping84
but I'm interested why the sample code doesn't work.
first callback: readToken - returns undefined.
but the second callback to write the token is never called.
it should be possible to read/write to a file with fs?
so, changing this to use redis/db won't actually fix the problem as far as i can see.
from wechat-api.
https://github.com/node-webot/wechat-api/blob/master/lib/api_common.js#L154
if readToken returns undefined, the saving token method will be called
if save token can't be called , please debug your code.
from wechat-api.
Related Issues (20)
- WeChatAPIJSONResponseFormatError
- 无限重复的post请求 HOT 2
- 什么时候能支持发送【小程序】图文链接? HOT 2
- lib/api_metrial.js HOT 1
- 上传永久素材
- 永久二维码现在支持字符串形式了 希望更新 HOT 1
- getMaterial 接口返回Buffer HOT 1
- WeChatAPIError: 40001
- 40001错误 HOT 1
- Error code: 48001, message: api unauthorized HOT 2
- 如何把 getMaterial 返回的 Buffer 保存为文件? HOT 2
- 上传多媒体的接口貌似不通了, 望你们测试一下 HOT 1
- Error code: 48001: unauthorized api in wechat shop HOT 1
- 希望可以支持下typescript HOT 1
- domain doxmate.cool is expired HOT 4
- 获取二维码地址后,上传到临时素材报错,望指导。 HOT 1
- api文档错误 HOT 1
- 支持MAC和IPAD协议新微信号接入,做机器人,营销系统,客服系统,监管系统的可以看下这个API :http://www.bbaos.com/docs/index HOT 1
- 找不到 doxmate.cool 的服务器 IP 地址。 HOT 1
- 需要最新iPAD协议联系(v:ixiaohe_) HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from wechat-api.