一、本節要點
1、菜單相關實體類的封裝
參考官方文檔中的請求包的內容,對菜單相關實體類進行封裝。
2、數據傳輸格式—JSON
自定義菜單中請求包的數據是Json字符串格式的,請參見: Java_數據交換_fastJSON_01_用法入門
二、代碼實現
1、菜單實體的封裝
1.1 按鈕基類—Button

package com.ray.weixin.gz.model.menu; /** * @desc : 按鈕的基類 * * @author: shirayner * @date : 2017年11月13日 上午11:36:16 */ public class Button { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
1.2 普通按鈕—CommonButton

package com.ray.weixin.gz.model.menu; /** * @desc : 普通按鈕(子按鈕) * * @author: shirayner * @date : 2017年11月13日 上午11:37:18 */ public class CommonButton extends Button { private String type; private String key; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
1.3 復雜按鈕—ComplexButton

package com.ray.weixin.gz.model.menu; /** * @desc : 復雜按鈕(父按鈕) * * @author: shirayner * @date : 2017年11月13日 上午11:36:42 */ public class ComplexButton extends Button { private Button[] sub_button; public Button[] getSub_button() { return sub_button; } public void setSub_button(Button[] sub_button) { this.sub_button = sub_button; } }
1.4 跳轉按鈕—ViewButton

package com.ray.weixin.gz.model.menu; /** * @desc : view類型的按鈕 * * @author: shirayner * @date : 2017年11月13日 上午11:37:42 */ public class ViewButton extends Button { private String type; private String url; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
1.5 菜單實體—Menu

package com.ray.weixin.gz.model.menu; /** * @desc : 菜單 * * @author: shirayner * @date : 2017年11月13日 上午11:37:31 */ public class Menu { private Button[] button; public Button[] getButton() { return button; } public void setButton(Button[] button) { this.button = button; } }
2.自定義菜單業務類—MenuService

package com.ray.weixin.gz.service.menu; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ray.weixin.gz.model.menu.Menu; import com.ray.weixin.gz.util.HttpHelper; /**@desc : 自定義菜單業務類 * * @author: shirayner * @date : 2017年10月31日 上午9:40:05 */ public class MenuService { private static final Logger logger = LogManager.getLogger(MenuService.class); //1.菜單創建(POST) 限100(次/天) public static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; //2.查詢菜單數據 public static final String GET_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN"; //3.刪除菜單 public static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN"; /** * @desc :1.創建菜單 * * @param menu 菜單實例 * @param accessToken 有效憑證 * @throws Exception void */ public static void createMenu(Menu menu, String accessToken) throws Exception { //1.准備POST請求參數 Object data=JSON.toJSON(menu); logger.info(data); //2.拼裝創建菜單的url String url=CREATE_MENU_URL.replace("ACCESS_TOKEN", accessToken); //3.發起POST請求,獲取返回結果 JSONObject jsonObject=HttpHelper.doPost(url, data); logger.info("jsonObject:"+jsonObject.toString()); if (null != jsonObject) { //5.錯誤消息處理 if (0 != jsonObject.getInteger("errcode")) { int errCode = jsonObject.getInteger("errcode"); String errMsg = jsonObject.getString("errmsg"); throw new Exception("error code:"+errCode+", error message:"+errMsg); } else { logger.info("菜單創建成功!"); } } } /** * @desc :2.查詢菜單數據 * * @param accessToken 有效憑證 * @return * @throws Exception JSONObject */ public static JSONObject getMenu(String accessToken) throws Exception { //1.獲取請求url String url=GET_MENU_URL.replace("ACCESS_TOKEN", accessToken); //2.發起GET請求,獲取返回結果 JSONObject jsonObject=HttpHelper.doGet(url); logger.info("jsonObject:"+jsonObject.toString()); //3.解析結果,獲取菜單數據 JSONObject returnJsonObject=null; if (null != jsonObject) { //4.錯誤消息處理 if (jsonObject.getInteger("errcode")!=null && 0 != jsonObject.getInteger("errcode")) { int errCode = jsonObject.getInteger("errcode"); String errMsg = jsonObject.getString("errmsg"); throw new Exception("error code:"+errCode+", error message:"+errMsg); //5.成功獲取菜單數據 } else { returnJsonObject= jsonObject; } } return returnJsonObject; } /** * @desc : 3.刪除菜單 * * @param accessToken 有效憑證 * @throws Exception void */ public static void deleteMenu(String accessToken) throws Exception { //1.獲取請求url String url=DELETE_MENU_URL.replace("ACCESS_TOKEN", accessToken); //2.發起GET請求,獲取返回結果 JSONObject jsonObject=HttpHelper.doGet(url); logger.info("jsonObject:"+jsonObject.toString()); //3.解析結果 if (null != jsonObject) { //4.錯誤消息處理 if (jsonObject.getInteger("errcode")!=null && 0 != jsonObject.getInteger("errcode")) { int errCode = jsonObject.getInteger("errcode"); String errMsg = jsonObject.getString("errmsg"); throw new Exception("error code:"+errCode+", error message:"+errMsg); //5.成功刪除菜單 } else { logger.info("菜單刪除成功!"); } } } }
3.菜單測試類—MenuServiceTest

package com.ray.weixin.gz.service.menu; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import com.alibaba.fastjson.JSONObject; import com.ray.weixin.gz.config.Env; import com.ray.weixin.gz.model.menu.Button; import com.ray.weixin.gz.model.menu.CommonButton; import com.ray.weixin.gz.model.menu.ComplexButton; import com.ray.weixin.gz.model.menu.Menu; import com.ray.weixin.gz.model.menu.ViewButton; import com.ray.weixin.gz.service.menu.MenuService; import com.ray.weixin.gz.util.AuthHelper; /**@desc : 菜單測試類 * * @author: shirayner * @date : 2017年10月31日 上午9:53:00 */ public class MenuServiceTest { private static final Logger logger = LogManager.getLogger(MenuServiceTest.class); /** * @desc :1. 創建菜單 * * @throws Exception void */ @Test public void testCreateMenu() throws Exception { //1.准備好請求參數 String accessToken=AuthHelper.getAccessToken(Env.APP_ID, Env.APP_SECRET); Menu menu=getMenu(); //2.調用接口,執行請求 MenuService.createMenu(menu, accessToken); } /** * @desc :2.查詢菜單數據 * * @throws Exception void */ @Test public void testGetMenu() throws Exception { //1.准備好請求參數 String accessToken=AuthHelper.getAccessToken(Env.APP_ID, Env.APP_SECRET); //2.調用接口,執行請求 JSONObject jsonObject=MenuService.getMenu(accessToken); logger.info("菜單數據:"+jsonObject.toJSONString()); } /** * @desc :3.刪除菜單 * * @throws Exception void */ @Test public void testDeleteMenu() throws Exception { //1.准備好請求參數 String accessToken=AuthHelper.getAccessToken(Env.APP_ID, Env.APP_SECRET); //2.調用接口,執行請求 MenuService.deleteMenu(accessToken); } /** * @desc :輔助1.組裝菜單數據 * * @return Menu */ private static Menu getMenu() { ViewButton btn11 = new ViewButton(); btn11.setName("移動審批"); btn11.setType("view"); btn11.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa0064ea657f80062&redirect_uri=http%3A%2F%2Frayner.nat300.top%2Fweixin_gz%2FIDAuthentication.jsp&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"); //btn11.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa0064ea657f80062&redirect_uri=http%3A%2F%2Frayner.nat300.top%2Fweixingz_hec%2Fweixingz.screen&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"); ViewButton btn12 = new ViewButton(); btn12.setName("上傳圖片"); btn12.setType("view"); btn12.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa0064ea657f80062&redirect_uri=http%3A%2F%2Frayner.nat300.top%2Fweixin_gz%2FuploadImg.jsp&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"); ViewButton btn13 = new ViewButton(); btn13.setName("申請開票"); btn13.setType("view"); btn13.setUrl("https://mp.weixin.qq.com/bizmall/authinvoice?action=list&s_pappid=d3hhMDA2NGVhNjU3ZjgwMDYyX0s22HY1myAuWWro7q-FsX8KWzrWiEgI8Ngqa3-W6dQ4&appid=wxa0064ea657f80062&num=1&o1=1234&m1=11&t1=1510036149&source=web&type=1&redirect_url=https%3A%2F%2Fmp.weixin.qq.com&signature=9aa88c3a4587f51397703a7838cd2fcaa60abb38#wechat_redirect"); ViewButton btn14 = new ViewButton(); btn14.setName("獲取發票信息"); btn14.setType("view"); btn14.setUrl("http://rayner.nat300.top/weixin_gz/showInvoice.jsp"); ViewButton btn15 = new ViewButton(); btn15.setName("上傳圖片2"); btn15.setType("view"); btn15.setUrl("http://5hcn2d.natappfree.cc/WeiXin_SanFenBaiXue/index2.jsp"); ViewButton btn21 = new ViewButton(); btn21.setName("index"); btn21.setType("view"); btn21.setUrl("http://rayner.nat300.top/weixin_gz/index.jsp"); CommonButton btn22 = new CommonButton(); btn22.setName("經典游戲"); btn22.setType("click"); btn22.setKey("22"); CommonButton btn23 = new CommonButton(); btn23.setName("美女電台"); btn23.setType("click"); btn23.setKey("23"); CommonButton btn24 = new CommonButton(); btn24.setName("人臉識別"); btn24.setType("click"); btn24.setKey("24"); CommonButton btn25 = new CommonButton(); btn25.setName("聊天嘮嗑"); btn25.setType("click"); btn25.setKey("25"); CommonButton btn31 = new CommonButton(); btn31.setName("Q友圈"); btn31.setType("click"); btn31.setKey("31"); CommonButton btn33 = new CommonButton(); btn33.setName("幽默笑話"); btn33.setType("click"); btn33.setKey("33"); CommonButton btn34 = new CommonButton(); btn34.setName("用戶反饋"); btn34.setType("click"); btn34.setKey("34"); CommonButton btn35 = new CommonButton(); btn35.setName("關於我們"); btn35.setType("click"); btn35.setKey("35"); ViewButton btn32 = new ViewButton(); btn32.setName("周邊搜索"); btn32.setType("view"); btn32.setUrl("http://liufeng.gotoip2.com/xiaoqrobot/help.jsp"); ComplexButton mainBtn1 = new ComplexButton(); mainBtn1.setName("漢得測試"); mainBtn1.setSub_button(new Button[] { btn11, btn12, btn13, btn14, btn15 }); ComplexButton mainBtn2 = new ComplexButton(); mainBtn2.setName("休閑驛站"); mainBtn2.setSub_button(new Button[] { btn21, btn22, btn23, btn24, btn25 }); ComplexButton mainBtn3 = new ComplexButton(); mainBtn3.setName("更多"); mainBtn3.setSub_button(new Button[] { btn31, btn33, btn34, btn35, btn32 }); /** * 這是公眾號xiaoqrobot目前的菜單結構,每個一級菜單都有二級菜單項<br> * * 在某個一級菜單下沒有二級菜單的情況,menu該如何定義呢?<br> * 比如,第三個一級菜單項不是“更多體驗”,而直接是“幽默笑話”,那么menu應該這樣定義:<br> * menu.setButton(new Button[] { mainBtn1, mainBtn2, btn33 }); */ Menu menu = new Menu(); menu.setButton(new Button[] { mainBtn1, mainBtn2, mainBtn3 }); return menu; } }
三、參考文檔
2.柳峰: [專欄]微信公眾帳號開發教程