wechat-plus 使用node開發微信公眾號
阿新 • • 發佈:2019-01-31
install
npm install wechat-plus --save
use
//引入 var WeChat=require("wechat-plus"); let weChat= new WeChat({ token: "your token", appid: "your appid", secret: "your secret", }); //文字訊息 weChat.event.on("weChat_msg_text", function (res, msg) { // msg接受到的訊息內容 // res物件 // replay 方法 第一個引數為訊息 第二個引數為訊息型別 預設為text res.reply({ ToUserName: msg.FromUserName, FromUserName: msg.ToUserName, Content: "ee" //回覆內容 },"text"); }); //語音訊息 weChat.event.on("weChat_msg_voice", function (res, msg) { // msg接受到的訊息內容 // res物件 // replay 方法 第一個引數為訊息 第二個引數為訊息型別 res.reply({ ToUserName: msg.FromUserName, FromUserName: msg.ToUserName, Content: "ee" //回覆內容 },"text"); }); /** * 生成授權連結 * @param redirectUrl * @param state 預設為空 * @param scope 預設為"snsapi_userinfo" * @returns {string} */ let authUrl=weChat.authUrl("http://youAddress.com/code","STATE","snsapi_userinfo") /** * 獲取使用者資訊 * @param code * @returns {Promise.<TResult>|Request} */ weChat.getUserInfo("CODE").then(function(res){ //userInfo 為res.body }); /** * 生成jsSDK簽名 * @param url 連結地址 * @returns {Promise.<TResult>} * noncestr:隨機字串, timestamp: 時間戳, signature: 簽名 */ weChat.jssdkSignature("url").then(function(result){ })
express 路由示例
let express = require('express'); let router = express.Router(); let WeChat = require("wechat-plus"); let weChat=new WeChat({ //以下引數自行替換 token: "******", appid: "***************************", secret: "***************************", }); //文字訊息事件 weChat.event.on("weChat_msg_text", function (res, msg) { //回覆內容 res.reply({ ToUserName: msg.FromUserName, FromUserName: msg.ToUserName, Content: "ee" }); }); // 開發者認證 router.get('/wechat', function (req, res, next) { if (weChat.auth(req)) { res.send(req.query.echostr) } else { res.send("false") } }); router.post("/wechat", function (req, res, next) { //使用者訊息處理函式 如果為進行訊息監聽 則向微信伺服器返回空資料 weChat.userMessage(req, res); }); //獲取使用者資訊 跳轉到授權頁面 router.get("/wechat/auth", function (req, res, next) { let t = weChat.authUrl("http://vpn.getlove.cn/api/wechat/code"); res.redirect(t); }); //根據code 獲取使用者的基本資訊 router.get("/wechat/code", function (req, res, next) { weChat.getUserInfo(req.query.code).then(function(data){ //data中包含使用者資訊 }).catch(function(err){ let t = weChat.authUrl("http://vpn.getlove.cn/api/wechat/code"); res.redirect(t); }) }); //jssdk獲取簽名 router.post("/share", function (req, res, next) { weChat.jssdkSignature(req.body.url).then(function (data) { res.send(data); }) }); module.exports = router;