微信公众号创建底部菜单(Ps:这里只介绍如何用main方法创建)

1、创建Button类

public class Button {
    private String name;//所有一级菜单、二级菜单都共有一个相同的属性,那就是name

    private String type;
    private String url;
    private KidButton[] sub_button;

    public KidButton[] getSub_button() {
        return sub_button;
    }

    public void setSub_button(KidButton[] sub_button) {
        this.sub_button = sub_button;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2、继承Butten类

public class KidButton extends Button {

}

3、创建菜单类

import cn.hutool.setting.dialect.Props;

public class Menu {
    private Button[] button;

    public Button[] getButton() {
        return button;
    }

    public void setButton(Button[] button) {
        this.button = button;
    }


    /**
     * 创建微信自定义菜单
     */
    public static Menu createMenu() {
        Props props = new Props("wx.properties", "utf-8");
        String WEI_XIN_AUTO = props.getStr("WEI_XIN_AUTO");


        Button kidButton = new Button();
        kidButton.setType("view");//链接形式
        kidButton.setUrl(WEI_XIN_AUTO);//菜单链接
        kidButton.setName("你的菜单名称");

        Menu menu = new Menu();
        menu.setButton(new Button[]{kidButton});
        return menu;


//        Button b1 = new Button();
//        b1.setName("使用方法");
//
//        KidButton kidButton = new KidButton();
//        kidButton.setName("免费体验");
//        kidButton.setType("view");
//        kidButton.setUrl(mianfei);
//
//        KidButton kidButton2 = new KidButton();
//        kidButton2.setName("使用方法");
//        kidButton2.setType("view");
//        kidButton2.setUrl("http://mp.weixin.qq.com/s/tkWVtXhhODso07o0Npr55A");
//
//        b1.setSub_button(new KidButton[]{kidButton,kidButton2});
//
//        Button b2 = new Button();
//        b2.setName("科一科四");
//        b2.setType("view");
//        b2.setUrl(keyikesi);
//
//        Button b3 = new Button();
//        b3.setName("分享好友");
//        b3.setType("view");
//        b3.setUrl(fenxiang);
//
//        Menu menu = new Menu();
//        menu.setButton(new Button[]{b1,b2,b3});
//        return menu;

    }

4、创建生成菜单方法

import com.dckj.bcq.common.utils.weixin.wxmenu.Menu;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class WXCreateMenu {

    private static final Logger LOGGER = Logger.getLogger(WXCreateMenu.class);


    /**
     * 创建菜单
     *
     * @param accessToken 有效的access_token
     * @return 0表示成功,其他值表示失败
     */
    public static int createMenu(Menu menu, String accessToken) {

        // 菜单创建(POST) 限100(次/天)
        String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
        int result = 0;
        // 拼装创建菜单的url
        String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
        // 将菜单对象转换成json字符串
        String jsonMenu = JSONUtil.toJsonStr(menu);
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            LOGGER.info("Post请求的参数:" + jsonMenu);

            HttpEntity httpEntity = new StringEntity(jsonMenu, "utf-8");
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity responseEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(responseEntity, "utf-8");
            LOGGER.info("微信返回的json:" + response);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            if (null != jsonObject) {
                if (0 != jsonObject.getInt("errcode")) {
                    result = jsonObject.getInt("errcode");
                    LOGGER.error("创建菜单失败 errcode:" + jsonObject.getInt("errcode") + ",errmsg:" + jsonObject.get("errmsg"));
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result;
    }

 

5、调用生成菜单

        Menu menu = Menu.createMenu();//菜单对象
        //获取accessToken
        String accessToken = WXEHCacheParam.getAccessToken("appId","appSecret");
        //创建 create>0?成功:失败
        int create = WXCreateMenu.createMenu(menu,accessToken);

附带如何获得AccessToken

/**
     * 获access_token
     *
     * @return
     */
    public static String getAccessToken(String appId,String appSecret) {

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appId + "&secret=" + appSecret;

        LOGGER.info("request user info from url: {" + url + "}");
        JsonObject accessTokenInfo = null;
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            System.out.println("获取Token-------------------"+response);
            Gson token_gson = new Gson();

            accessTokenInfo = token_gson.fromJson(response, JsonObject.class);
            LOGGER.info("get accessTokenInfo success. [result={" + accessTokenInfo + "}]");

            return accessTokenInfo.get("access_token").toString().replaceAll("\"", "");

        } catch (Exception ex) {
            LOGGER.error("fail to request wechat user info. [error={" + ex + "}]");
        }
        return "";
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章