第四课:公众号自定义菜单
自定义菜单创建
官方参考文档:
https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html
代码语言:javascript复制// /routes/chatrobot.js
// 添加一个新路由
// 生成自定义菜单
router.get('/menu', menuController)
代码语言:javascript复制// /controller/customer.js
//修改暴露的接口
module.exports = {
customerController,
getAccessToken
}
代码语言:javascript复制// /controller/menu.js
// 菜单创建的核心代码
const { getAccessToken } = require('../controller/customer')
const axios = require('axios')
async function menuController(req, res, next) {
const ACCESS_TOKEN = await getAccessToken()
// 菜单创建请求 url
const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${ACCESS_TOKEN}`
// 定义菜单
const menu = {
button: [
{
name: '模式切换',
sub_button: [
{
type: 'click',
name: 'chatgpt',
key: 'model_chatgpt'
},
{
type: 'click',
name: '人工服务',
key: 'model_human'
}
]
},
{
name: '账户',
sub_button: [
{
type: 'view',
name: '账户充值',
url: 'https://pay.weixin.qq.com/'
},
{
type: 'view',
name: '余额查询',
url: 'https://pay.weixin.qq.com/'
}
]
}
]
}
// 创建菜单
const result = await axios.post(url, menu)
res.send(result.data.errmsg)
}
module.exports = menuController
需要在浏览器或 insomnia
里访问 http://qnext.nat300.top/chatrobot/menu
来执行菜单的创建。
菜单事件消息回复
由于要根据菜单的不同目标完成相应的功能,因此需要对代码做全面的整合:
1、/routes/chatrobot.js
const express = require('express');
const signatureController = require('../controller/signature')
const menuController = require('../controller/menu')
const messageController = require('../controller/message')
const router = express.Router();
// 第三方服务器验证
router.get('/', signatureController)
// 消息接收与回复
router.post('/', messageController)
// 生成自定义菜单
router.get('/menu', menuController)
module.exports = router
2、/controller/signature.js
const crypto = require('crypto')
function checkSignature(req, res, next) {
// 定义 token,此 token 一定要与微信公众号 token 一致
const token = 'weixin'
// 获取来自微信服务器的信息
const { signature, echostr, timestamp, nonce } = req.query
// 将token、timestamp、nonce三个参数进行字典序排序,再拼接成一个字符串
const tmpStr = [token, timestamp, nonce].sort().join('')
// 将三个参数字符串拼接成一个字符串进行sha1加密
const mySignature = crypto.createHash('sha1').update(tmpStr).digest('hex')
// 获得加密后的字符串可与signature对比,标识该请求来源于微信
// 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容
res.send(mySignature === signature ? echostr : 'error')
}
module.exports = checkSignature
3、/controller/message.js
const { customerController } = require('./customer')
function formatMsg(msg) {
const msgXml = msg.xml
const msgArray = Object.keys(msgXml)
return msgArray.reduce((obj, key) => {
obj[key] = msgXml[key][0]
return obj
}, {})
}
function messageController(req, res, next) {
// 接收到微信方发来的消息并处理
const msg = formatMsg(req.body)
// 回复信息
const {
fromusername
} = msg
msg['createtime'] = Math.floor((new Date().getTime()) / 1000)
// msg['content'] = '你好呀 ☕️'
msg['content'] = '答案正在准备中...'
// 发送客服消息
customerController(fromusername, '答案内容')
res.set('Content-Type', 'text/xml')
res.render('reply', msg)
}
module.exports = messageController
4、/controller/menu.js
const { getAccessToken } = require('../controller/customer')
const axios = require('axios')
async function menuController(req, res, next) {
const ACCESS_TOKEN = await getAccessToken()
// 菜单创建请求 url
const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${ACCESS_TOKEN}`
// 定义菜单
const menu = {
button: [
{
name: '模式切换',
sub_button: [
{
type: 'click',
name: 'chatgpt',
key: 'model_chatgpt'
},
{
type: 'click',
name: '人工服务',
key: 'model_human'
}
]
},
{
name: '账户',
sub_button: [
{
type: 'view',
name: '账户充值',
url: 'https://pay.weixin.qq.com/'
},
{
type: 'view',
name: '余额查询',
url: 'https://pay.weixin.qq.com/'
}
]
}
]
}
// 创建菜单
const result = await axios.post(url, menu)
res.send(result.data.errmsg)
}
module.exports = menuController
5、/utils/format.js
function formatMsg(msg) {
const msgXml = msg.xml
const msgArray = Object.keys(msgXml)
return msgArray.reduce((obj, key) => {
obj[key] = msgXml[key][0]
return obj
}, {})
}
module.exports = {
formatMsg
}
6、根据 msgtype
完成不同的任务
修改 chatrobot.js
, 创建一个新的 controller
——switcherController
const express = require('express');
const signatureController = require('../controller/signature')
const menuController = require('../controller/menu')
const switcherController = require('../controller/switcher')
const router = express.Router();
// 第三方服务器验证
router.get('/', signatureController)
// 消息接收与回复
router.post('/', switcherController)
// 生成自定义菜单
router.get('/menu', menuController)
module.exports = router
7、/controller/switcher.js
const { formatMsg } = require('../utils/format')
const messageController = require('./message')
function switcherController(req, res) {
const requestBody = formatMsg(req.body)
switch (requestBody.msgtype) {
case 'text':
messageController(req, res)
break
case 'event':
const { tousername, fromusername } = requestBody
switch (requestBody.eventkey) {
case 'model_chatgpt':
res.render('reply', {
...requestBody,
content: '你的身份已经切换为 ChatGPT 模式,机器人为您提供答疑服务 ☕️'
})
break
case 'model_human':
res.render('reply', {
...requestBody,
content: '你的身份已经切换为人工服务模式,陆老师为你答疑解惑 ☕️'
})
break
default:
break
}
default:
break;
}
}
module.exports = switcherController
现在无论菜单单击还是输入对话,均可正常回复内容。
关注、取消关注事件回复
代码语言:javascript复制// /controller/switcher.js
// ...
function switcherController(req, res) {
// ..
switch (requestBody.msgtype) {
// ...
case 'event':
// ...
switch (requestBody.event) {
case 'subscribe':
res.render('reply', {
...requestBody,
content: '谢谢关注 ☕️'
})
break
case 'unsubscribe':
res.render('reply', {
...requestBody,
content: '欢迎您再来 ☕️'
})
break
default:
break
}
// ...
}
}
// ...
后记