微信公众号java开发沉淀(二)菜单设置

xiaoxiao2025-08-24  104


菜单相关的介绍都在 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013

package com.tsing.wechat.service; import com.tsing.wechat.utils.HttpUtils; import com.tsing.wechat.utils.ResourceUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; @Slf4j @Service public class MenuService { private static final String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s"; private static final String MENU_GET_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s"; private static final String MENU_DELETE_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s"; @Resource private WxUserInfoService wxUserInfoService; public void getMenu() { String access_token = wxUserInfoService.getToken(); String url = String.format(MENU_GET_URL, access_token); String res = HttpUtils.doGet(url); log.info("获取菜单返回:{}", res); } public void createMenu() throws IOException { String access_token = wxUserInfoService.getToken(); String url = String.format(MENU_CREATE_URL, access_token); String json = ResourceUtils.getResourceString("/menu.txt"); log.info("创建菜单的参数:{}", json); String res = HttpUtils.doPost(url, json); log.info("创建菜单返回:{}", res); } public void delMenu() { String access_token = wxUserInfoService.getToken(); String url = String.format(MENU_DELETE_URL, access_token); String res = HttpUtils.doGet(url); log.info("删除菜单返回:{}", res); } }

wxUserInfoService 是为了获取到access_token,这里我就不赘述了。 菜单创建删除获取的三个url列在了上面。

这次我创建菜单的样式menu.txt是:

{ "button":[ { "type":"click", "name":"用户信息", "key":"USER_INFO_CLICK" }, { "name":"菜单", "sub_button":[ { "type":"view", "name":"搜索", "url":"http://www.baidu.com" }, { "type":"click", "name":"赞一下我们", "key":"V1001_GOOD" }] }, { "name": "扫码", "sub_button": [ { "type": "scancode_waitmsg", "name": "扫码带提示", "key": "rselfmenu_0_0", "sub_button": [ ] }, { "type": "scancode_push", "name": "扫码推事件", "key": "rselfmenu_0_1", "sub_button": [ ] } ] }] }

创建出来以后的样子是

点用户信息,发送一个 click 事件消息到我们配置的接口。时间的event_key 是 USER_INFO_CLICK。 可以自行更具需要返回消息。 第二个菜单的**“搜索”**, 我们设置的是view , 点击不会向服务器发消息,直接打开配置的url, 这里点了以后是通过微信自带的浏览器打开了百度。

转载请注明原文地址: https://www.6miu.com/read-5035209.html

最新回复(0)