您的位置:首页 > 移动开发 > 微信开发

nodejs express wechat 实现微信消息功能

2016-04-20 16:07 891 查看
参考官方:https://github.com/node-webot/wechat

直接上能用的

1. 微信公众平台准备:
需要:
(1)appid:wxf5eefxxx19a47c0d 。即 AppID(应用ID)。
(2)URL(服务器地址): http://test.nodejs.xxx.com/wechat 。 填你的服务器处理请求地址。
(3)token:CjpMHxxxEEbfq3qTesSc 。 随便写,跟代码保持一致即可,最好是20位。
(4)encodingAESKey: a3uGNIYMEYraMX3xxxxxjqNAOYDnA8rIhseK99。 即图中的 消息加解密密钥。点 随机生成即可。(追加:用的时候发现,这个没用到,估计选 加密方式 时起作用)



2. 写最简单的 基于 express和wechat的处理代码。

// 直接改 app.js
var express = require('express');
var app = express();

var wechat = require('wechat');
var config = {
token : 'CjpMHxxxEEbfq3qTesSc',
appid : 'wxf5xxxxd19a47c0d',
encodingAESKey : 'a3uGNIYMEYraMX3xxxxxxxwjqNAOYDnA8rIhseK99'
};

app.use(express.query());
app.use('/wechat', wechat(config, function(req, res, next) {
// 微信输入信息都在req.weixin上
var message = req.weixin;
console.log('log mao:', message);

if (message.Content === 'diaosi') {
// 回复屌丝(普通回复)
res.reply('hehe');
} else if (message.Content === 'text') {
console.log('log text');
// 你也可以这样回复text类型的信息
res.reply({
content : 'text object',
type : 'text'
});
} else if (message.Content === 'hehe') {
// 回复一段音乐
res.reply({
type : "music",
content : {
title : "来段音乐吧",
description : "一无所有",
musicUrl : "http://mp3.com/xx.mp3",
hqMusicUrl : "http://mp3.com/xx.mp3",
thumbMediaId : "thisThumbMediaId"
}
});
} else {
// 回复高富帅(图文回复)
res.reply([ {
title : '你来我家接我吧',
description : '这是女神与高富帅之间的对话',
picurl : 'https://www.baidu.com/img/bd_logo1.png',
url : 'https://www.baidu.com/'
} ]);
}
}));

// 注意加上 端口监听
var server = app.listen(13001, function() {
var host = server.address().address;
var port = server.address().port;

console.log('Example app listening at http://%s:%s', host, port);
});

消息结构说明 (req.weixin):

{
ToUserName : 'gh_30e178xxbe7',
FromUserName : 'omIHmwCxxxxxxf8Dyn2YGQj4',
CreateTime : '1461140663',
MsgType : 'text',
Content : 'xxv',
MsgId : '62755513xxx5544996'
}

3. 跑起来看看吧

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: