自定義菜單接口
/**
* 查詢菜單
*/
MenuApi.getMenu();
/**
* 創建菜單
*/
MenuApi.createMenu(String jsonStr);
/**
* 自定義菜單刪除接口
*/
MenuApi.deleteMenu();
WeinxinApiController.java
createMenu(String jsonStr)
接受 json 格式的字符串,我們根據微信技術文檔拼接自定義菜單字符串:
/**
* 創建菜單
*/
public void createMenu() {
String path = Constants.HOST;
String jsonstr = "{" +
" \"button\": [" +
" {" +
" \"name\": \"一級菜單1\"," +
" \"sub_button\": [" +
" {\"name\": \"二級菜單11\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單12\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單13\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單14\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單15\",\"type\": \"view\",\"url\": \"" + path + "/api\"}]" +
" }," +
" {" +
" \"name\": \"一級菜單2\"," +
" \"sub_button\": [" +
" {\"name\": \"測 試\",\"type\": \"view\",\"url\": \"" + path + "/api/index\"}," +
" {\"name\": \"click\",\"type\": \"click\",\"key\": \"22\"}," +
" {\"name\": \"二級菜單23\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"百度\",\"type\": \"view\",\"url\": \"http://www.baidu.com\"}," +
" {\"name\": \"二級菜單25\",\"type\": \"view\",\"url\": \"" + path + "/api\"}]" +
" }," +
" {" +
" \"name\": \"一級菜單3\"," +
" \"sub_button\": ["+
" {\"name\": \"二級菜單31\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單32\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單33\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單34\",\"type\": \"view\",\"url\": \"" + path + "/api\"}," +
" {\"name\": \"二級菜單35\",\"type\": \"view\",\"url\": \"" + path + "/api\"}]" +
" }" +
" ]" +
"}";
ApiResult apiResult = MenuApi.createMenu(jsonstr);
renderText(apiResult.getJson());
}
自定義菜單接口可實現多種類型按鈕,詳見:微信公眾平臺技術文檔。
這里使用了兩種:
1、click
:點擊推事件用戶點擊 click 類型按鈕后,微信服務器會通過消息接口推送消息類型為 event 的結構給開發者(參考消息接口指南),并且帶上按鈕中開發者填寫的 key 值,開發者可以通過自定義的 key 值與用戶進行交互;
2、view
:跳轉 URL 用戶點擊 view 類型按鈕后,微信客戶端將會打開開發者在按鈕中填寫的網頁 URL,可與網頁授權獲取用戶基本信息接口結合,獲得用戶基本信息。
getMenu()
方法,查詢自定義菜單:
/**
* 查詢菜單
*/
public void getMenu() {
ApiResult apiResult = MenuApi.getMenu();
renderText(apiResult.getJson());
}
WeixinMsgController.java
processInMenuEvent(InMenuEvent inMenuEvent)
方法接受菜單中 click
類型按鈕的點擊事件
// 自定義菜單事件
@Override
protected void processInMenuEvent(InMenuEvent inMenuEvent) {
OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
outMsg.setContent("processInMenuEvent() 方法測試成功");
render(outMsg);
}
index.html
<h3>自定義菜單</h3>
點擊<a href='/api/createMenu'>【創建自定義菜單】</a><br>
點擊<a href='/api/getMenu'>【獲取自定義菜單】</a><br>
運行
點擊創建菜單,微信客戶端不會立馬刷新。想立馬看到效果,可以取消關注再關注。
微信菜單:
一級菜單
二級菜單
三級菜單
點擊 click22
Paste_Image.png
新增了“測試”按鈕,可以直接跳轉主頁面:
測試頁面
點擊“獲取自定義菜單”
得到 json 格式的菜單數據:
菜單數據
源碼地址
JFinal Weixin 學習筆記(9)-- 微信賬號二維碼
JFinal Weixin 學習筆記(1)-- 目錄