Java 微信公眾號選單關聯小程式
阿新 • • 發佈:2019-02-01
最近微信公眾號開發了選單關聯小程式功能,實現程式碼如下
/** * 自定義選單工具類 * @author why * */ public class MenuUtil { private static Logger logger = Logger.getLogger(MenuUtil.class);// 日誌 //建立選單介面地址 public final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; /** *建立選單 * @param menu 選單例項 * @param accessToken 憑證 * @return true 成功 false 失敗 */ public static boolean createMenu(Menu menu, String accessToken){ boolean result = false; String url = menu_create_url.replace("ACCESS_TOKEN", accessToken); //將選單物件轉換成JSON字串 String jsonMenu = JSONObject.fromObject(menu).toString(); //發起post請求建立選單 JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonMenu); if(null != jsonObject){ int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); System.out.println("====================="+errorCode+" "+errorMsg); if(0 == errorCode){ result = true; }else{ result = false; logger.error("建立選單失敗errorCode:{"+errorCode+"} errorMsg:{"+errorMsg+"}"); System.out.println(errorCode+" "+errorMsg); } } return result; } }
/** * 類名稱:ToXcx.java * 類描述:小程式選單實體類 * 作 者:why * 時 間:2017年4月21日 */ public class ToXcx extends Button { private String type; //型別 private String name; //選單名稱 private String url; //不支援小程式跳轉地址 private String appid; //小程式appid private String pagepath; //小程式頁面路徑 public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getPagepath() { return pagepath; } public void setPagepath(String pagepath) { this.pagepath = pagepath; } }
建立選單
ToXcx xcxBtn1 = new ToXcx();
xcxBtn1.setName("我要寄件");
xcxBtn1.setType("miniprogram");
xcxBtn1.setUrl("");
xcxBtn1.setAppid("");
xcxBtn1.setPagepath("pages/send/send");
呼叫
MenuUtil.createMenu(選單json, token);