Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions lib/wechat.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,11 +416,29 @@ Handler.prototype.middlewarify = function () {
var _respond = respond(this);
return function (req, res, next) {
if (req.query.encrypt_type && req.query.msg_signature) {
// 增加前置cryptor
// req.wechat_token.cryptorStop @param {boolean} 通过中间件进行传递,是否通过wechat生成前置cryptor
if (req.wechat_token &&
req.wechat_token.token &&
req.wechat_token.encodingAESKey &&
req.wechat_token.appid &&
!req.wechat_token.cryptorStop) {
var cryptor = new WXBizMsgCrypt(req.wechat_token.token, req.wechat_token.encodingAESKey, req.wechat_token.appid);
req.cryptor = cryptor;
}
serveEncrypt(that, req, res, next, _respond);
} else {
var method = req.method;
// 动态token,在前置中间件中设置该值req.wechat_token,优先选用
if (!checkSignature(req.query, req.wechat_token || token)) {
var _token;
if (req.wechat_token) {
if (typeof req.wechat_token === 'string') {
_token = req.wechat_token;
} else {
_token = req.wechat_token.token;
}
}
if (!checkSignature(req.query, _token || token)) {
res.writeHead(401);
res.end('Invalid signature');
return;
Expand Down Expand Up @@ -467,7 +485,7 @@ Handler.prototype.middlewarify = function () {
* }).middlewarify();
* ```
* 加密模式下token为config
*
* 官方推荐的安全模式,请配置好encodingAESKey
* ```
* var config = {
* token: 'token',
Expand All @@ -486,20 +504,30 @@ Handler.prototype.middlewarify = function () {
* - `location`,处理位置推送的回调函数,接受参数为(location, req, res, next)。
* - `link`,处理链接推送的回调函数,接受参数为(link, req, res, next)。
* - `event`,处理事件推送的回调函数,接受参数为(event, req, res, next)。
*
*
* middleware
*
* - resetToken,提供动态切换微信号。可用于单一path下,对应多个微信号的情况。需要前置中间件的配合。
*
*
* @param {String} token 在微信平台填写的口令
* @param {Function} handle 生成的回调函数,参见示例
*/
var middleware = function (token, handle) {
if (arguments.length === 1) {
return new Handler(token);
this.handle = new Handler(token);
return this.handle;
}

if (arguments.length === 2) {
if (handle instanceof Handler) {
this.handle = handle;
handle.setToken(token);
return handle.middlewarify();
} else {
return new Handler(token, handle).middlewarify();
this.handle = new Handler(token, handle);
return this.handle.middlewarify();
}
}
};
Expand All @@ -514,5 +542,12 @@ middleware.toXML = compiled;
middleware.reply = reply;
middleware.reply2CustomerService = reply2CustomerService;
middleware.checkSignature = checkSignature;
middleware.resetToken = function (token) {
if (this.handle) {
this.handle.setToken(token);
} else {
console.wain('not have handle object.');
}
};

module.exports = middleware;