1.自定義菜單簡介
https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html
自定義菜單能夠幫助公眾號豐富界面,讓用戶更好更快地理解公眾號的功能。開啟自定義菜單後,公眾號界面如圖所示:
自定義菜單最多包括3個一級菜單,每個一級菜單最多包含5個二級菜單。一級菜單最多4個漢字,二級菜單最多7個漢字,多出來的部分將會以「...」代替。創建自定義菜單後,菜單的刷新策略是,在用戶進入公眾號會話頁或公眾號profile頁時,如果發現上一次拉取菜單的請求在5分鐘以前,就會拉取一下菜單,如果菜單有更新,就會刷新客戶端的菜單。測試時可以嘗試取消關注公眾帳號後再次關注,則可以看到創建後的效果。
自定義菜單接口可實現多種類型按鈕,這裡只使用我們經常處理的兩個事件類型,如下:
click:點擊推事件用戶點擊click類型按鈕後,微信伺服器會通過消息接口推送消息類型為event的結構給開發者(參考消息接口指南),並且帶上按鈕中開發者填寫的key值,開發者可以通過自定義的key值與用戶進行交互;
view:跳轉URL用戶點擊view類型按鈕後,微信客戶端將會打開開發者在按鈕中填寫的網頁URL,可與網頁授權獲取用戶基本信息接口結合,獲得用戶基本信息。
注意:沒有更新菜單的接口,那麼就需要每次創建之前先刪除菜單。
2.刪除自定義菜單
app/router.js定義removeMenu路由
router.get("/api/v1/web/weChat/removeMenu", controller.auth.removeMenu);controller/auth.js新增removeMenu方法
async removeMenu() { const { ctx, service } = this; const res = await service.auth.removeMenu(); console.log(res) ctx.body = res; }service/auth.js新增removeMenu方法
async removeMenu() { const { ctx, app, service } = this; const data = await service.utils.getTicket(); const url = `https: const result = await ctx.curl(url, { dataType: "json", }); return { data: result.data, msg: "刪除菜單成功", }; }
3.創建自定義菜單
app/router.js定義createMenu路由
router.post("/api/v1/web/weChat/createMenu", controller.auth.createMenu);controller/auth.js新增createMenu方法
async createMenu() { const { ctx, service } = this; const res = await service.auth.createMenu(); console.log(res) ctx.body = res; }service/auth.js新增createMenu方法
async createMenu() { const { ctx, app, service } = this; const menu = { button: [ { type: "click", name: "今日歌曲", key: "V1001_TODAY_MUSIC", }, { name: "菜單", sub_button: [ { type: "view", name: "搜索", url: "http://www.soso.com/", }, { type: "click", name: "贊一下我們", key: "V1001_GOOD", }, ], }, ], };
const data = await service.utils.getTicket(); const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${data.access_token}`; const result = await ctx.curl(url, { method: "POST", contentType: "json", dataType: "json", data: menu, }); return { data: result.data, msg: "創建菜單成功", }; }
4.使用第三方庫co-wechat-api來實現
github: https://github.com/node-webot/co-wechat-api
文檔:https://doxmate.cool/node-webot/co-wechat-api/api.html#api_menu_exports_createMenu
安裝:
service/auth.js使用:
const Service = require("egg").Service;const WeChatAPI = require("co-wechat-api");
class AuthService extends Service { constructor(ctx) { this.api = new WeChatAPI('appId', 'AppSecret'); super(ctx); } async createMenu() { const menu = { button: [ { type: "click", name: "今日歌曲", key: "V1001_TODAY_MUSIC", }, { name: "菜單", sub_button: [ { type: "view", name: "搜索", url: "http://www.soso.com/", }, { type: "click", name: "贊一下我們", key: "V1001_GOOD", }, ], }, ], }; const result = await this.api.createMenu(menu); return { data: result, msg: "創建菜單成功", }; }
async removeMenu() { const result = await this.api.removeMenu(); return { data: result, msg: "刪除菜單成功", }; }}
module.exports = AuthService;co-wechat-api這個庫封裝了很多函數可供我們用於微信公眾號開發使用: