前文说到接入了开发者模式后用户通过微信后台创建的菜单就会丢失。这时候就要程序员通过微信的接口手动去创建菜单。微信创建菜单比较简单。
可以参照微信的官方文档点击打开链接
需要注意的是微信创建菜单有一定的缓存。这时候可以手动去查询创建的菜单。微信提供了调试的接口点击打开链接
在下面的接口调试中可以立即看到创建的菜单。特别需要注意的是菜单的url里面一定不能包含空格不然菜单会一直创建不成功,本人就是因为这个问题花了半天的时间。
下面附上创建菜单的代码
public static void createMenu(String type) throws UnsupportedEncodingException{
String url="";
if("0".equals(type)){
url =SMEURL;
}else{
url =SMEMPURL;
}
SmsClientAccessTool tool = SmsClientAccessTool.getInstance();
Snippet.getAccessToken();//获取token
String token = (String)SystemInit.weixinMap.get("weixintoken");
System.out.println(token);
List<Map<String, Object>> button1 = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> button2_1 = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> button2_2 = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> button2_3 = new ArrayList<Map<String, Object>>();
Map<String,Object> map1 = new HashMap<String,Object>();
map1.put("type","click");
map1.put("name", "菜单一");
map1.put("key", "1_PROMANAGE");
Map<String,Object> map11 = new HashMap<String,Object>();
map11.put("type","view");
map11.put("name", "菜单11");
map11.put("url", "http://url");
Map<String,Object> map12 = new HashMap<String,Object>();
map12.put("type","view");
map12.put("name", "菜单12");
map12.put("url", "http://url");
button2_1.add(map11);
button2_1.add(map12);
map1.put("sub_button",button2_1);
Map<String,Object> map2 = new HashMap<String,Object>();
map2.put("type","click");
map2.put("name", "菜单二");
map2.put("key", "2_PROMANAGE");
Map<String,Object> map21 = new HashMap<String,Object>();
map21.put("type","view");
map21.put("name", "菜单22");
map21.put("url",url+"/service/activity_july.html?trackid=10023");
map2.put("sub_button",button2_2);
Map<String,Object> map3 = new HashMap<String,Object>();
map3.put("type","click");
map3.put("name", "菜单三");
map3.put("key", "3_PROMANAGE");
Map<String,Object> map31 = new HashMap<String,Object>();
map31.put("type","view");
map31.put("name", "菜单31");
map31.put("url","http://111");
map3.put("sub_button",button2_3);
button1.add(map1);
button1.add(map2);
button1.add(map3);
JSONObject json = new JSONObject();
json.put("button", button1);
System.out.println(json.toString());
String url1 ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
String result=tool.doAccessHTTPPostJson(url1,json.toString() ,null);
System.out.println(result);
}
创建后的截图