springboot 微信菜单创建

一:建立以下实体类

//点击菜单
public class ClickButton extends Button{
	private String key;
 
	public String getKey() {
		return key;
	}
 
	public void setKey(String key) {
		this.key = key;
	}
}

public class Button {
	private String type;
	private String name;
	private Button[] sub_button;
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Button[] getSub_button() {
		return sub_button;
	}
	public void setSub_button(Button[] sub_button) {
		this.sub_button = sub_button;
	}
}
``

package com.wx.wx_test.wx.button;

public class Menu {
private Button[] button;

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

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

}

package com.wx.wx_test.wx.button;

//发送位置
public class SendLocalButton extends Button{
	private String key;
 
	public String getKey() {
		return key;
	}
 
	public void setKey(String key) {
		this.key = key;
	}
}

二:初始化菜单的工具类


import org.springframework.stereotype.Component;


@Component
public class WxButtonUtil {

    /**
     * 组装菜单
     * @return
     */
    public static Menu initMenu(){
        Menu menu = new Menu();
        ViewButton button11 = new ViewButton();
        //注意按钮名字不要太长,不然会报40018错误
        button11.setName("搜索");
        button11.setType("view");
        button11.setUrl("https://www.baidu.com");
        //注意链接不要少了https://  否则会报错40055

//        SendPicButton button21 = new SendPicButton();
//        button21.setName("发图");
//        button21.setType("pic_photo_or_album");
//        button21.setKey("pic");

        SendLocalButton button32 = new SendLocalButton();
        button32.setName("发位置");
        button32.setType("location_select");
        button32.setKey("local");

        ClickButton button31 = new ClickButton();
        button31.setName("点赞");
        button31.setType("click");
        button31.setKey("strtest");//事件key

        Button button = new Button();
        button.setName("click2");
        button.setSub_button(new Button[]{button31,button32});

        menu.setButton(new Button[]{button11,button});
        return menu;
    }



}

ApiUtil类

package com.ipfsemc.ipfsemc.wx;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ApiUtil {

    @Autowired(required = false)
    private RequestConfig requestConfig;            /* 默认请求配置,由Apache提供 */

    /**
     * 执行 GET 请求
     *
     * @param url
     * @return 响应200返回内容,404返回null
     * @throws Exception
     */
    public String getRequest(String url, String encoding) {
        HttpGet request = new HttpGet(url);     /* 创建http GET请求 */
        request.setConfig(requestConfig);
        try {
            return doHttpRequest(request, encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行带有参数的GET请求
     *
     * @param url
     * @param params
     * @return 响应200返回内容,404返回null
     * @throws ClientProtocolException
     * @throws IOException
     * @throws URISyntaxException
     */
    public String getRequest(String url, Map<String, String> params, String encoding) throws Exception {
        URIBuilder builder = new URIBuilder(url);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.setParameter(entry.getKey(), entry.getValue());
        }
        return getRequest(builder.build().toString(), encoding);
    }

    /**
     * 执行HTTP Request
     *
     * @param request 请求
     * @return 状态200 返回数据,否则返回null
     * @throws Exception
     */
    public String doHttpRequest(HttpUriRequest request, String encoding) {
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient().execute(request);            /* 执行请求 */
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), encoding);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 创建HTTP本地连接
     *
     * @return
     */
    private CloseableHttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

    /**
     * 执行post请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public String postMapRequest(String url, Map<String, String> params, Map<String, String> headers, String encoding) throws Exception {
        HttpPost request = new HttpPost(url);           /* 创建http POST请求 */
        request.setConfig(requestConfig);               /* 设置默认配置信息 */
        if (null != headers && !headers.isEmpty()) {    /* 有头信息参数 */
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        if (null != params) {
            List<NameValuePair> parameters = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }           /* 构造一个form表单式的实体 */
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, encoding);
            request.setEntity(formEntity);              /* 将请求实体设置到httpPost对象中 */
        }
        return doHttpRequest(request, encoding);
    }

    /**
     * 执行post请求
     *
     * @return
     * @throws IOException
     */
    public String postRequest(String url, Map<String, String> headers, String encoding) {
        HttpPost request = new HttpPost(url);           /* 创建http POST请求 */
        request.setConfig(requestConfig);               /* 设置默认配置信息 */
        if (null != headers && !headers.isEmpty()) {    /* 有头信息参数 */
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return doHttpRequest(request, encoding);
    }

    /**
     * 执行post请求
     *
     * @param url       请求地址
     * @param paramType 数据类型JSON/XML
     * @param params    请求JSON/XML字符串数据(没有设置为空即可)
     * @param headers   需要添加请求头的map(没有设置为空即可)
     * @return 响应状态200 返回数据,否则返回null
     * @throws Exception
     */
    public String postRequest(String url, String paramType, String params, Map<String, String> headers, String encoding) {
        HttpPost request = new HttpPost(url);           /* 创建http POST请求 */
        request.setConfig(requestConfig);               /* 设置默认配置 */
        if (null != headers && !headers.isEmpty()) {    /* 有头信息参数 */
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        if ("xml".equalsIgnoreCase(paramType)) {/* 构造一个字符串的实体,并将请求实体设置到httpPost对象中 */
            request.setEntity(new StringEntity(params, ContentType.APPLICATION_XML));
        } else if ("json".equalsIgnoreCase(paramType)) {
            request.setEntity(new StringEntity(params, ContentType.APPLICATION_JSON));
        }
        return doHttpRequest(request, encoding);
    }

}

创建菜单代码

 @Component
public class Wx {
	 @Autowired
	    private ApiUtil apiUtil;
	// 测试环境
	    public static final String APP_ID1 = "";
	    public static final String APP_SECRET1 = "";
	```
	/**
	     * 添加自定义菜单
	     */
	    public boolean menuAdd() {
	        // 获取普通token
	        com.alibaba.fastjson.JSONObject normalToken = getNormalToken();
	        String access_token = normalToken.getString(ACCESS_TOKEN);
	        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+access_token;
	
	        String menu = JSON.toJSONString(WxButtonUtil.initMenu()).toString();
	        JSONObject result = doPostStr(url,menu);
	        if("ok".equals(result.getString("errmsg"))){
	            return true;
	        }
	        System.out.println("菜单结果no"+ result);
	        return false;
	    }
	
	
	 /**
	     * 获取普通token:用来执行公众号功能调用
	     *
	     * @return
	     */
	    public JSONObject getNormalToken() {
	        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
	                "&appid=" + APP_ID +
	                "&secret=" + APP_SECRET;
	        String result = apiUtil.getRequest(url, ENCODING);
	        return JSON.parseObject(result);
	    }
	
	 /**
	     * 发起Http请求, 通过POST方式访问网络用到的方法
	     * @param url,请求的URL地址
	     * @return 响应后的字符串
	     */
	    public static JSONObject doPostStr(String url, String outstr){
	        DefaultHttpClient httpClient = new DefaultHttpClient();
	        HttpPost httpPost = new HttpPost(url);
	        JSONObject jsonObject = null;
	        try {
	            httpPost.setEntity(new StringEntity(outstr, "UTF-8"));
	            HttpResponse response = httpClient.execute(httpPost);
	            HttpEntity entity = response.getEntity();
	            String result= EntityUtils.toString(entity,"UTF-8");
	            jsonObject = JSON.parseObject(result);
	
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        return jsonObject;
	
	    }

}



controller层

@Autowired
    private Wx wx;
/**
     * 添加微信公众号菜单
     * @return
     */
    @RequestMapping(value="/menuAdd",method= RequestMethod.POST)
    public String menuAdd(){
        boolean b = wx.menuAdd();
        if (b) {
            return "success";
        }
        return "unsuccess";
    }

最后,发送以下请求就可以看见公众号上的菜单发生变化了,注意,必须是重新关注之后才可以看见(测试号是这样的!)

哈哈哈!!朋友们 点个赞支持一下 !!😁😊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值