|
作者:王慧永,來自原文地址
最近微信公眾號(hào)開發(fā)了菜單關(guān)聯(lián)小程序功能,實(shí)現(xiàn)代碼如下
-
/**
-
* 自定義菜單工具類
-
* @author why
-
*
-
*/
-
public class MenuUtil {
-
private static Logger logger = Logger.getLogger(MenuUtil.class);// 日志
-
//創(chuàng)建菜單接口地址
-
public final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
-
/**
-
*創(chuàng)建菜單
-
* @param menu 菜單實(shí)例
-
* @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);
-
//將菜單對(duì)象轉(zhuǎn)換成JSON字符串
-
String jsonMenu = JSONObject.fromObject(menu).toString();
-
//發(fā)起post請(qǐng)求創(chuàng)建菜單
-
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("創(chuàng)建菜單失敗errorCode:{"+errorCode+"} errorMsg:{"+errorMsg+"}");
-
System.out.println(errorCode+" "+errorMsg);
-
}
-
}
-
return result;
-
}
-
}
-
/**
-
* 類名稱:ToXcx.java
-
* 類描述:小程序菜單實(shí)體類
-
* 作 者:why
-
* 時(shí) 間:2017年4月21日
-
*/
-
public class ToXcx extends Button {
-
private String type; //類型
-
private String name; //菜單名稱
-
private String url; //不支持小程序跳轉(zhuǎn)地址
-
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;
-
}
-
-
}
創(chuàng)建菜單
-
ToXcx xcxBtn1 = new ToXcx();
-
xcxBtn1.setName("我要寄件");
-
xcxBtn1.setType("miniprogram");
-
xcxBtn1.setUrl("");
-
xcxBtn1.setAppid("");
-
xcxBtn1.setPagepath("pages/send/send");
調(diào)用
-
MenuUtil.createMenu(菜單json, token);
|