采纳答案成功!
向帮助你的同学说点啥吧!感谢那些助人为乐的人
var content=yield util.parseXMLAsync(data);
console.log("I want to recived the"+content.toString());
var message=util.formatMessage(content.xml);
console.log("this is message"+message);
this.weixin = message; //message is object
yield handler.call(this, next);
wechat.reply.call(this);
{"errcode":40125,"errmsg":"invalid appsecret, view more at http://t.cn/RAEkdVq hint: [jEvVTa0197e277]","expires_in":null}
首先我看到你代码里这个生成的凭据是没有成功的,因为你代码里变量拼错了:
1 2 3 4 | function Wechat(opts){ var that = this ; this .appID=opts.appID; this .appsecret=opts.appsecret; |
appsecret 在你的配置文件里是 appSecret,其他的由于我本地貌似防火墙有问题,没法往下排查了,你先修复后,看看
看看是不是 util 里面 formateMessage 暴漏的有错误,如果没有的话,可以把更多代码贴出来。
建议你自己先往上查一下:
at Object.exports.tpl (/Users/mac/wechat/wechat/util.js:124:19)
at Object.Wechat.reply (/Users/mac/wechat/wechat/wechat.js:172:20)
at Object.<anonymous> (/Users/mac/wechat/wechat/g.js:102:30)
这里的错误已经很明显了,util.js:124 行 调用的是wechat.js:172行,调用的是g.js:102 行,那么肯定是这 3 行代码前后的逻辑出了问题,设下 console 把相关变量都打印一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | //util.js 'use strict' var xml2js = require( 'xml2js' ); var Promise = require( 'bluebird' ); var tpl = require( './tpl' ); exports.parseXMLAsync = function (xml){ return new Promise( function (resolve, reject){ xml2js.parseString(xml, {trim: true }, function (err, content){ if (err) {reject(err)} else {resolve(content)} }) }) }; function formatMessage(result){ var message = {} if ( typeof result === 'object' ){ var keys = Object.keys(result) for ( var i = 0; i <keys.length; i++) { var item = result[keys[i]] var key = keys[i] if (!(item instanceof Array) || item.length === 0) { continue } if (item.length === 1) { var val = item[0] if ( typeof val === 'object' ) { message[key] = formatMessage(val) } else { message[key] = (val || '' ).trim() } } else { message[key] = [] for ( var j = 0, k = item.length; j < k; j++){ message[key].push(formatMessage(item[j])) } } } } return message } exports.formatMessage = formatMessage exports.tpl = function (content, message){ var info = {} var type = 'text' var fromUserName = message.FromUserName var toUserName = message.ToUserName if (Array.isArray(content)) { type = 'news' } type = content.type||type info.content = content info.createTime = new Date().getTime() info.msgType = type info.toUserName = fromUserName info.fromUserName = toUserName console.log( '=============' +info + '==========' ) return tpl.compiled(info) } |
//wechat.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | 'use strict' var Promise=require( 'bluebird' ); var request=Promise.promisify(require( 'request' )); var prefix= 'https://api.weixin.qq.com/cgi-bin/' ; var util = require( './util' ); var api={ accessToken:prefix+ 'token?grant_type=client_credential' }; function Wechat(opts){ var that = this ; this .appID=opts.appID; this .appsecret=opts.appsecret; this .getAccessToken=opts.getAccessToken; this .saveAccessToken=opts.saveAccessToken; this .getAccessToken() .then( function (data){ try { data=JSON.parse(data); } catch (e){ return that.updataAccessToken() } if (that.isValidAccessToken(data)) { return Promise.resolve(data) } else { return that.updataAccessToken() } }) .then( function (data){ that.data=data.access_token; that.expires_in=data.expires_in; that.saveAccessToken(data) }) } Wechat.prototype.isValidAccessToken = function (data) { if (!data || !data.access_token || !data.expires_in) { return false ; } var access_token=data.access_token; var expires_in=data.expires_in; var now = ( new Date().getTime()) if (now < expires_in) { return true } else { return false } }; Wechat.prototype.updataAccessToken = function () { var appID = this .appID; var appsecret = this .appsecret; var url=api.accessToken+ '&appid=' +appID+ '&secret=' +appsecret; return new Promise( function (resolve,reject){ request({url: url , json : true }).then( function (response){ var data = response.body; var now = ( new Date().getTime()) var expires_in = now+(data.expires_in-20)*1000 data.expires_in = expires_in; resolve(data) }) }) }; Wechat.prototype.reply = function () { var content = this .body; var message = this .weixin; console.log( "type is " + content.type); console.log( "你好" +message); //message is object console.log( "my name is " +content); //value has been received var xml = util.tpl(content,message); this .status = 200; this .type = 'application/xml' ; this .body = xml }; module.exports=Wechat; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 'use strict' //g.js var sha1=require( "sha1" ); var getRawBody=require( "raw-body" ); var Wechat=require( "./wechat" ); var util=require( "./util" ); module.exports= function (option,handler){ var wechat= new Wechat(option); //管理与微信交互的接口,管理票据的更新,存储,有效期; return function *(next){ //推送的数据,返回的信息 console.log( this .query); //var that=this; var token=option.token; var signature= this .query.signature; var nonce= this .query.nonce; var timestamp= this .query.timestamp; var echostr= this .query.echostr; var str=[token,timestamp,nonce].sort().join( "" ); var sha=sha1(str); if ( this .method=== "GET" ){ if (sha === signature){ this .body=echostr+ "" ; console.log(token); } else { this .body= "wrong" ; } } else if ( this .method=== "POST" ){ if (sha !== signature){ this .body= "wrong" ; return false ; } var data=yield getRawBody( this .req,{ length: this .length, limit: "1Mb" , encoding: this .charset }); //message is a object //content is a object var content=yield util.parseXMLAsync(data); console.log( "I want to recived the" +content); var message=util.formatMessage(content.xml); console.log( "this is message" +message); this .weixin = message; //message is object yield handler.call( this , next); wechat.reply.call( this ); } }; }; |
//wechat.js
'use strict'
var Promise=require('bluebird');
var request=Promise.promisify(require('request'));
var prefix='https://api.weixin.qq.com/cgi-bin/';
var util = require('./util');
var api={
accessToken:prefix+'token?grant_type=client_credential'
};
function Wechat(opts){
var that = this;
this.appID=opts.appID;
this.appsecret=opts.appsecret;
this.getAccessToken=opts.getAccessToken;
this.saveAccessToken=opts.saveAccessToken;
this.getAccessToken()
.then(function(data){
try{
data=JSON.parse(data);
}
catch(e){
return that.updataAccessToken()
}
if (that.isValidAccessToken(data)) {
return Promise.resolve(data)
}else{
return that.updataAccessToken()
}
})
.then(function(data){
that.data=data.access_token;
that.expires_in=data.expires_in;
that.saveAccessToken(data)
})
}
Wechat.prototype.isValidAccessToken = function(data) {
if (!data || !data.access_token || !data.expires_in) {
return false;
}
var access_token=data.access_token;
var expires_in=data.expires_in;
var now = (new Date().getTime())
if (now < expires_in) {
return true
}else{
return false
}
};
Wechat.prototype.updataAccessToken = function() {
var appID = this.appID;
var appsecret = this.appsecret;
var url=api.accessToken+'&appid='+appID+'&secret='+appsecret;
return new Promise(function(resolve,reject){
request({url: url , json : true}).then(function(response){
var data = response.body;
var now = (new Date().getTime())
var expires_in = now+(data.expires_in-20)*1000
data.expires_in = expires_in;
resolve(data)
})
})
};
Wechat.prototype.reply = function() {
var content = this.body;
var message = this.weixin;
console.log("type is "+ content.type);
console.log("你好"+message); //message is object
console.log("my name is "+content);//value has been received
var xml = util.tpl(content,message);
this.status = 200;
this.type = 'application/xml';
this.body = xml
};
module.exports=Wechat;
//util.js
'use strict'
var xml2js = require('xml2js');
var Promise = require('bluebird');
var tpl = require('./tpl');
exports.parseXMLAsync = function(xml){
return new Promise(function(resolve, reject){
xml2js.parseString(xml, {trim: true}, function(err, content){
if (err) {reject(err)}
else{resolve(content)}
})
})
};
function formatMessage(result){
var message = {}
if(typeof result === 'object'){
var keys = Object.keys(result)
for (var i = 0; i <keys.length; i++) {
var item = result[keys[i]]
var key = keys[i]
if (!(item instanceof Array) || item.length === 0) {
continue
}
if (item.length === 1) {
var val = item[0]
if (typeof val === 'object') {
message[key] = formatMessage(val)
}else{
message[key] = (val || '').trim()
}
}
else{
message[key] = []
for(var j = 0, k = item.length; j < k; j++){
message[key].push(formatMessage(item[j]))
}
}
}
}
return message
}
exports.formatMessage = formatMessage
exports.tpl = function(content, message){
var info = {}
var type = 'text'
var fromUserName = message.FromUserName
var toUserName = message.ToUserName
if (Array.isArray(content)) {
type = 'news'
}
type = content.type||type
info.content = content
info.createTime = new Date().getTime()
info.msgType = type
info.toUserName = fromUserName
info.fromUserName = toUserName
console.log('============='+info + '==========')
return tpl.compiled(info)
}
老师,我也报这个错
TypeError: Cannot read property 'type' of undefined
at Object.exports.tpl (/Users/mac/wechat/wechat/util.js:124:19)
at Object.Wechat.reply (/Users/mac/wechat/wechat/wechat.js:172:20)
at Object.<anonymous> (/Users/mac/wechat/wechat/g.js:102:30)
at GeneratorFunctionPrototype.next (native)
at Object.<anonymous> (/Users/mac/wechat/node_modules/koa/node_modules/koa-compose/index.js:28:19)
at GeneratorFunctionPrototype.next (native)
at onFulfilled (/Users/mac/wechat/node_modules/koa/node_modules/co/index.js:65:19)
at runMicrotasksCallback (node.js:337:7)
at process._tickCallback (node.js:355:11)
登录后可查看更多问答,登录/注册