nodejs express wechat 實現微信消息功能

參考官方:https://github.com/node-webot/wechatnode

直接上能用的git

1. 微信公衆平臺準備:
須要:
(1)appid:wxf5eefxxx19a47c0d 。即 AppID(應用ID)。
(2)URL(服務器地址): http://test.nodejs.xxx.com/wechat 。   填你的服務器處理請求地址。
(3)token:CjpMHxxxEEbfq3qTesSc 。   隨便寫,跟代碼保持一致便可,最好是20位。
(4)encodingAESKey: a3uGNIYMEYraMX3xxxxxjqNAOYDnA8rIhseK99。 即圖中的 消息加解密密鑰。點 隨機生成便可。(追加:用的時候發現,這個沒用到,估計選 加密方式 時起做用)
github

2. 寫最簡單的 基於 express和wechat的處理代碼。web

// 直接改 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):express

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

3. 跑起來看看吧服務器

相關文章
相關標籤/搜索