官网接口地址:https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html

//创建一个微信菜单实体类

WeixinMenu.java

package com.weixin.menu;

import java.io.Serializable;
import java.util.Set; public abstract class WeixinMenu implements Serializable { // primary key
private Integer id; // fields
private String name;
private String type;
private String url;
private String key; // many to one
private WeixinMenu parent; // collections
private java.util.Set<WeixinMenu> child; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} 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 getKey() {
return key;
} public void setKey(String key) {
this.key = key;
} public WeixinMenu getParent() {
return parent;
} public void setParent(WeixinMenu parent) {
this.parent = parent;
} public Set<WeixinMenu> getChild() {
return child;
} public void setChild(Set<WeixinMenu> child) {
this.child = child;
} public String toString() {
return super.toString();
} }

  

//控制器方法

WeixinMenuAct.java

package com.weixin.menu;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Set; public class Menu { /**
* 生成微信菜单请求方法
* @param request
* @param model
* @return
*/
@RequestMapping("/weixinMenu/o_menu.do")
public String menu(HttpServletRequest request, ModelMap model) {
List<WeixinMenu> menus =null; //获取菜单集合
String msg =createMenu(getMenuJsonString(menus));
try {
JSONObject object = new JSONObject(msg);
if (!object.get("errcode").equals("0")){
model.addAttribute("msg",msg);
//操作失败处理代码
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
} /**
* 创建自定义菜单
*/
public String createMenu(String menus){
String token=getToken();//获取access_token
String createMenuUrl="https://api.weixin.qq.com/cgi-bin/menu/create"; //微信提供的菜单接口地址
String url = createMenuUrl+"?access_token=" + token;
String msg = post(url, menus,"application/json");
return msg;
} /**
* 获取access_token
* @return
*/
public String getToken() {
String tokenGetUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";//微信提供获取access_token接口地址
String appid="";
String secret=""; System.out.println("~~~~~appid:"+appid);
System.out.println("~~~~~secret:"+secret);
JSONObject tokenJson=new JSONObject();
if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(secret)){
tokenGetUrl+="&appid="+appid+"&secret="+secret;
tokenJson=getUrlResponse(tokenGetUrl);
System.out.println("~~~~~tokenJson:"+tokenJson.toString());
try {
return (String) tokenJson.get("access_token");
} catch (JSONException e) {
System.out.println("报错了");
return null;
}
}else{
System.out.println("appid和secret为空");
return null;
}
} private JSONObject getUrlResponse(String url){
CharsetHandler handler = new CharsetHandler("UTF-8");
try {
HttpGet httpget = new HttpGet(new URI(url));
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
return new JSONObject(client.execute(httpget, handler));
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 将菜单集合转换为json数据
* @param menus
* @return
*/
public String getMenuJsonString(List<WeixinMenu> menus) { String strJson = "{" +
"\"button\":["; for (int i = 0; i < menus.size(); i++) {
strJson = strJson + "{ ";
WeixinMenu menu = menus.get(i);
if(menu.getChild().size()>0){
strJson = strJson +
"\"name\":\""+menu.getName()+"\","+
"\"sub_button\":[";
Set<WeixinMenu> sets = menu.getChild();
Iterator<WeixinMenu> iter = sets.iterator();
int no = 1;
while(iter.hasNext()){
if(no>5){
break;
}else{
if(no==1){
strJson = strJson + "{";
}else{
strJson = strJson + ",{";
}
WeixinMenu child = iter.next();
if(child.getType().equals("click")){
strJson = strJson +
"\"type\":\"click\","+
"\"name\":\""+child.getName()+"\","+
"\"key\":\""+child.getKey()+"\"}";
}else{
strJson = strJson +
"\"type\":\"view\","+
"\"name\":\""+child.getName()+"\","+
"\"url\":\""+child.getUrl()+"\"}";
}
no++;
}
}
strJson = strJson+"]";
}else if(menu.getType().equals("click")){
strJson = strJson +
"\"type\":\"click\","+
"\"name\":\""+menu.getName()+"\","+
"\"key\":\""+menu.getKey()+"\"";
}else{
strJson = strJson +
"\"type\":\"view\","+
"\"name\":\""+menu.getName()+"\","+
"\"url\":\""+menu.getUrl()+"\"";
}
if(i==menus.size()-1){
strJson = strJson + "}";
}else{
strJson = strJson + "},";
}
}
strJson = strJson + "]}";
return strJson; } /**
* 发送请求
* @param url 请求地址
* @param json 数据
* @param contentType 编码
* @return
*/
private String post(String url, String json,String contentType)
{
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
HttpPost post = new HttpPost(url);
try
{
StringEntity s = new StringEntity(json,"utf-8");
if(StringUtils.isBlank(contentType)){
s.setContentType("application/json");
}
s.setContentType(contentType);
post.setEntity(s);
HttpResponse res = client.execute(post);
HttpEntity entity = res.getEntity();
String str= EntityUtils.toString(entity, "utf-8");
return str;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
} private static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
} public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient; } catch (Exception ex) {
return null;
}
} private class CharsetHandler implements ResponseHandler<String> {
private String charset; public CharsetHandler(String charset) {
this.charset = charset;
} public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
return EntityUtils.toString(entity, charset);
} else {
return EntityUtils.toString(entity);
}
} else {
return null;
}
}
} }

  

如果出现 {"errcode":40001,"errmsg":"invalid credential, hint:。。。

可能是需要把当前的ip地址加入到公众号的后台 IP白名单中

JAVA微信公众号网页开发——生成自定义微信菜单(携带参数)的更多相关文章

  1. 你所误解的微信公众号开发、以及微信公众号网页授权、接收url跳转参数等问题

    前言:有一星期没跟新博客了,最近太忙.项目赶进度就没把时间花在博客上:今天来说说所谓的微信公众号开发和填坑记录: 微信公众号:运行在微信终端的应用 (对于开发者来说比较爽的你只需考虑兼容微信浏览器,因 ...

  2. JAVA微信公众号网页开发 —— 用户授权获取openid

    官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 HttpClientUtil.java packa ...

  3. JAVA微信公众号网页开发——获取公众号关注的所有用户(微信公众号粉丝)

    package com.weixin.sendmessage; import org.apache.commons.lang.StringUtils; import org.apache.http.H ...

  4. JAVA微信公众号网页开发——将接收的消息转发到微信自带的客服系统

    如果公众号处于开发模式,普通微信用户向公众号发消息时,微信服务器会先将消息POST到开发者填写的url上,无法直接推送给微信自带的客服功能.如果需要把用户推送的普通消息推送到客服功能中,就需要进行代码 ...

  5. 微信公众号第三方平台生成自定义菜单提示 获取"access_token失败"

    在微信公众号第三方平台要生成自定义菜单时,程序反应很慢,最终提示"获取access_token失败"(之前程序无改动,使用时间已久),查了大半天,找不出原因. 排除.在微信公众号平 ...

  6. 微信公众号网页开发-jssdk config配置参数生成(Java版)

    一.配置参数 参考官方文档:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&la ...

  7. JAVA微信公众号网页开发 —— 接收微信服务器发送的消息

    WeixinMessage.java package com.test; import java.io.Serializable; /** * This is an object that conta ...

  8. JAVA微信公众号网页开发——通过接收人的openid发送模板消息

    TemplateData.java 1 package com.weixin.weixin.template; 2 3 public class TemplateData { 4 private St ...

  9. C#开发微信公众号——网页开发之微信网页授权

    首先咱们先看下公众号的文档里面的介绍 上述图片的文字描述就是讲述了网页授权有什么用,就是为了获取微信用户的基本信息:授权回调域名的规范,说到域名回调的事情就不得不提一下设置网页授权域名 最好将这三个域 ...

随机推荐

  1. DirectX12 3D 游戏开发与实战第九章内容(上)

    仅供个人学习使用,请勿转载. 9.纹理贴图 学习目标: 学习如何将局部纹理映射到网格三角形上 探究如何创建和启用纹理 学会如何通过纹理过滤来创建更加平滑的图像 探索如何使用寻址模式来进行多次纹理贴图 ...

  2. SUNTANS 及 FVCOM 对流扩散方程求解简介[TBC]

    最近接到一个任务,就是解决FVCOM中对流扩散计算不守衡问题.导师认为是其求解时候水平和垂向计算分开求解所导致的,目前我也没搞清到底有什么问题,反正就是让把SUNTANS的对流扩散计算挪到FVCOM中 ...

  3. PHP识别二维码(php-zbarcode)

    PHP识别二维码(php-zbarcode) 标签: php二维码扩展 2015-11-06 17:12 609人阅读 评论(0) 收藏 举报  分类: PHP(1)  Linux 版权声明:本文为博 ...

  4. day06 python代码操作MySQL

    day06 python代码操作MySQL 今日内容 python代码操作MySQL 基于python与MySQL实现用户注册登录 python操作MySQL python 胶水语言.调包侠(贬义词& ...

  5. SpringMVC详细实例

    一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于SpringMVC的配置 1 2 3 4 5 6 ...

  6. ReactiveCocoa操作方法-重复

    retry重试      只要失败,就会重新执行创建信号中的block,直到成功. __block int i = 0; [[[RACSignal createSignal:^RACDisposabl ...

  7. 【Spring Framework】Spring入门教程(八)Spring的事务管理

    事务是什么? 事务:指单个逻辑操作单元的集合. 在操作数据库时(增删改),如果同时操作多次数据,我们从业务希望,要么全部成功,要么全部失败.这种情况称为事务处理. 例如:A转账给B. 第一步,扣除A君 ...

  8. 【Linux】【Services】【Web】Haproxy

    1. 概念 1.1. 官方网站 http://www.haproxy.org/ 2. 安装 yum安装 yum -y install haproxy keepalived 配置haproxy日志,修改 ...

  9. html如何让input number类型的标签不产生上下加减的按钮(转)

    添加css代码: <style> input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit- ...

  10. 索引以及Mysql中的索引

    一.什么是索引 索引是表的目录,会保存在额外的文件中,针对表中的指定列建立,专门用于帮助用户快速查询数据的一种数据结构.类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获取 ...