微信公众平台开发模式自定义菜单

时间:2024-10-15 01:35:40

1、在设置自定义菜单之前,我们需要获取一个access_token.这个可以通过微信公众号appid和secret向公众号服务器获取api.weixin.qq.com/cgi-bin/token?appid=公众号ID&secret=公众号secret&grant_type=client_credential

微信公众平台开发模式自定义菜单

2、这样会收到返回数据中,会有一个access_token的值。

微信公众平台开发模式自定义菜单

3、创建自定义菜单是通过POST协议发送一个json格式的结构体。WxAccessToken accessToken = WxAppManager.getCacheAccessToken(redis.client, app); // 获取存取的access_tokenString path = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken.access_token;URL url = new URL(path);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setDoOutput(true);httpURLConnection.setDoInput(true);httpURLConnection.setRequestMethod("POST");httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");httpURLConnection.connect();OutputStream outputStream = httpURLConnection.getOutputStream();outputStream.write(jsonMenu.getBytes("UTF-8"));outputStream.close();InputStream inputStream = httpURLConnection.getInputStream();JsonNode jsonIn = JsonUtil.readTree(inputStream);String errcode = jsonIn.path("errcode").asText();String errmsg = jsonIn.path("errmsg").asText();

微信公众平台开发模式自定义菜单

4、json格式的结构体这里的类型有view,超连接; click,点击事件。这里会回调到event事件中,key就是event事件中的CLICK中的EventKey值{ "button": [{ "name": "菜单1", "type": null, "key": null, "url": null, "sub_button": [{ "name": "菜单1-1", "type": "view", "key": null, "url": "点击连接地址" }, { "name": "菜单1-2", "type": "click", "key": "menu1-2", "url": null }] }, { "name": "菜单2", "type": null, "key": null, "url": null, "sub_button": [{ "name": "菜单2-1", "type": "click", "key": "menu2-1", "url": null }, { "name": "菜单2-2", "type": "view", "key": null, "url": "点击连接地址" }] }, { "name": "关于我", "type": null, "key": null, "url": null, "sub_button": [{ "name": "联系我", "type": "click", "key": "contactus", "url": null }] }]}

微信公众平台开发模式自定义菜单

5、查询现有的菜单。这里使用GET请求api.weixin.qq.com/cgi-bin/menu/get?access_token=access_token

微信公众平台开发模式自定义菜单

6、删除菜单使用GET消息api.weixin.qq.com/cgi-bin/menu/delete?access_token=access_token返回{"errcode":0,"errmsg":"ok"}然后,再查看,就没有菜单了

微信公众平台开发模式自定义菜单
© 手抄报圈