nodejs開發微信公眾號
阿新 • • 發佈:2020-12-22
1.windows上安裝NodeJS
2.新建專案目錄,如nodejs_wechat_bot
,進入目錄後安裝express
和weixin-api
模組,具體方法是:
npm install express
npm install weixin-api
3.新建檔案index.js
,寫入如下內容
var weixin = require('weixin-api');
var express = require('express');
var app = express();
// 接入驗證
app.get('/', function(req, res) {
// 簽名成功
if (weixin.checkSignature(req)) {
res.status(200).send(req.query.echostr);
} else {
res.status(200).send('fail');
}
});
// config 根據自己的實際配置填寫
weixin.token = 'qbtest';
// 監聽文字訊息
weixin.textMsg(function(msg) {
console.log("textMsg received");
console.log(JSON.stringify(msg));
var resMsg = {};
switch (msg.content) {
case "文字" :
// 返回文字訊息
resMsg = {
fromUserName : msg.toUserName,
toUserName : msg.fromUserName,
msgType : "text",
content : "這是文本回復",
funcFlag : 0
};
break;
case "音樂" :
// 返回音樂訊息
resMsg = {
fromUserName : msg.toUserName,
toUserName : msg.fromUserName,
msgType : "music",
title : "音樂標題",
description : "音樂描述",
musicUrl : "音樂url",
HQMusicUrl : "高質量音樂url",
funcFlag : 0
};
break;
case "圖文" :
var articles = [];
articles[0] = {
title : "PHP依賴管理工具Composer入門",
description : "PHP依賴管理工具Composer入門",
picUrl : "http://weizhifeng.net/images/tech/composer.png",
url : "http://weizhifeng.net/manage-php-dependency-with-composer.html"
};
articles[1] = {
title : "八月西湖",
description : "八月西湖",
picUrl : "http://weizhifeng.net/images/poem/bayuexihu.jpg",
url : "http://weizhifeng.net/bayuexihu.html"
};
articles[2] = {
title : "「翻譯」Redis協議",
description : "「翻譯」Redis協議",
picUrl : "http://weizhifeng.net/images/tech/redis.png",
url : "http://weizhifeng.net/redis-protocol.html"
};
// 返回圖文訊息
resMsg = {
fromUserName : msg.toUserName,
toUserName : msg.fromUserName,
msgType : "news",
articles : articles,
funcFlag : 0
}
}
weixin.sendMsg(resMsg);
});
// 監聽圖片訊息
weixin.imageMsg(function(msg) {
console.log("imageMsg received");
console.log(JSON.stringify(msg));
});
// 監聽位置訊息
weixin.locationMsg(function(msg) {
console.log("locationMsg received");
console.log(JSON.stringify(msg));
});
// 監聽連結訊息
weixin.urlMsg(function(msg) {
console.log("urlMsg received");
console.log(JSON.stringify(msg));
});
// 監聽事件訊息
weixin.eventMsg(function(msg) {
console.log("eventMsg received");
console.log(JSON.stringify(msg));
});
// Start
app.post(