微信公众号-自定义菜单

https://www.bilibili.com/video/BV1nb411P76t?p=12

微信开发文档:https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html

以ViewButton为例,设置组团菜单,并有三个二级菜单(拼车、拼船、拼游)

 1 public class Button {
 2     private List<BaseButton> button = new ArrayList<>();  // 这里的名字 在生成的Button对象时,将其转成json对象时  显示的名称就是这个
 3     public List<BaseButton> getButton() {
 4         return button;
 5     }
 6     public void setButton(List<BaseButton> button) {
 7         this.button = button;
 8     }
 9 }
10 
11 public class SubButton extends BaseButton {
12     public List<BaseButton> sub_button = new ArrayList<BaseButton>();
13     public List<BaseButton> getSub_button() {
14         return sub_button;
15     }
16     public void setSub_button(List<BaseButton> sub_button) {
17         this.sub_button = sub_button;
18     }
19     public SubButton() {
20     }
21     public SubButton(String name) {
22         super(name);
23     }
24     public SubButton(List<BaseButton> sub_button) {
25         this.sub_button = sub_button;
26     }
27     public SubButton(String name, List<BaseButton> sub_button) {
28         super(name);
29         this.sub_button = sub_button;
30     }
31 }

 

 1 public abstract class BaseButton {
 2     private String name;
 3     public BaseButton(String name) {
 4         this.name = name;
 5     }
 6 }
 7 
 8 public class ViewButton extends BaseButton {
 9     private String type = "view";
10     private String url; // 点击菜单后要跳转的地址
11     public ViewButton(String name, String url) {
12         super(name);
13         this.url = url;
14     }
15     //  省略了get() set()  
16 }

 

 1 public void createMenu() {
 2     String pinChe = "拼车URL";
 3     String pinChuan = "拼船URL";
 4     String pinYou = "拼游URL";
 5     Button button = new Button();
 6     SubButton subButton = new SubButton("组团");
 7     subButton.getSub_button().add(new ViewButton("拼车", pinChe));
 8     subButton.getSub_button().add(new ViewButton("拼船", pinChuan));
 9     subButton.getSub_button().add(new ViewButton("拼游", pinYou));
10     button.getButton().add(subButton);
11     JSONObject jsonObject = JSONObject.fromObject(button);
12     String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
13     url = url.replace("ACCESS_TOKEN", WXService.getAccessToken()); // 自定义方法 获取accessToken
14     String result = Util.post(url, jsonObject.toString()); // 自定义方法 发送post请求 并携带数据
15     System.out.println(jsonObject.toString());  // 在创建失败的情况下 查看json字符串与开发文档里面创建菜单时的json字符串格式是否一致
16     System.out.println(result);  // 查看输出结果 如果是{"errcode":0,"errmsg":"ok"}则创建成功
17     /*
18     一直报错 {"errcode":40017,"errmsg":"invalid button type hint: [I8nq_a0783sha1]"}
19     原因是 在对应的Button类里面没有加getType()方法 导致对应的json字符串中没有type.
20     */
21}

就是单独执行一下上面creteMenu()方法即可创建菜单。

要实现进入菜单之前获取用户信息(openid,nickName...):https://www.cnblogs.com/DDiamondd/p/13041742.html

 

posted @ 2020-06-04 09:21  DDiamondd  阅读(388)  评论(0编辑  收藏  举报
TOP