Java实现微信公众号底部自定义菜单

发布时间:2024年01月22日

自定义菜单 /创建接口: 微信开放文档

示例代码: 

    /**
     * 自定义菜单
     *
     * @return
     */
    @GetMapping("/createMenu")
    public AjaxResult createMenu(){
        return menuService.createMenu();
    }

    /**
     * 自定义菜单
     *
     * @return
     */
    @Override
    public AjaxResult createMenu() {

        MenuVo menuVo = new MenuVo();
        menuVo.setType("view");
        menuVo.setName("生活");
        menuVo3.setUrl("https://xxx");

        MenuVo menuVo2 = new MenuVo();
        menuVo2.setType("view");
        menuVo2.setName("用车");
        menuVo3.setUrl("https://xxx");

        MenuVo menuVo3 = new MenuVo();
        menuVo3.setType("view");
        menuVo3.setName("我的");
        menuVo3.setUrl("https://xxx");

        ArrayList<MenuVo> list = Lists.newArrayList();
        list.add(menuVo);
        list.add(menuVo2);
        list.add(menuVo3);

        HashMap<String, Object> map = Maps.newHashMap();
        map.put("button", list);

        ObjectMapper mapper = new ObjectMapper();
        String menuJson = "";
        try {
            menuJson = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        StringBuilder response = new StringBuilder();
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + SpringUtils.getBean(AccessTokenUtils.class).getAccessToken();
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为POST
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");

            // 启用输入输出流
            con.setDoOutput(true);
            con.setDoInput(true);

            // 写入JSON数据
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = menuJson.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                String inputLine;


                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                log.info(response.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(response.toString());
    }

请求该接口后, 微信公众号即生成自定义的菜单

文章来源:https://blog.csdn.net/weixin_43652507/article/details/135752528
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。