微信公衆號創建底部菜單(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 "";
    }

 

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