您的位置:首页 > 其它

自定义菜单与调用接口创建菜单

2016-04-06 10:43 429 查看
如果我们不需要调用事件推送,则可使用自定义菜单,如果需要调用事件推送,比如扫描二维码,长按识别二维码,则需要使用服务器配置。

一、自定义菜单

略......

二、调用接口创建菜单

2.1.登录微信公众平台,在基本配置,配置URL,如下图。

这个URL是微信所有事件的统一入口,可以理解为回调函数。



2.2.调用微信接口创建菜单

微信接口调试地址



token是去微信服务器获取的,body是json字符串,也就是你需要创建的菜单。

怎么获取token?

appid,secret在基础配置上就能看到。



2.3 后台实现创建,写好菜单字符串,token.

public static void createMenu(){
//		String appId = "wxd30cf078223d3aca";
String jsonStr =  "{\"button\":[{\"type\":\"view\",\"name\":\"首页\",\"url\":\"http://xxxxx.com/project<span style="font-family: Arial, Helvetica, sans-serif;">/</span><span style="font-family: Arial, Helvetica, sans-serif;">action</span><span style="font-family: Arial, Helvetica, sans-serif;">/method.do?appIdxxx\"}]}";</span><span style="font-family: Arial, Helvetica, sans-serif;">
</span>		jsonStr = jsonStr.replace("@", "=").replace("#","&");
String accessToken = "jB4r8ldK_4loz3UFrC5GcycTabNw1RPKQddbeDsgzklAU2zkodBTgT3OF_4BAQwsK9keoMQVhwJcMhmEqBsuRSWCHI-pCJm9LLL9xOFTDAcYQMeAAADVR";
String url =MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
CommonUtil.httpsRequest(url, "POST", jsonStr);
}

public static void main(String[] args) {
createMenu();
}


public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();

URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);

conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);

// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}

// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}

// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSON.parseObject(buffer.toString());
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
}
return jsonObject;
}


2.4验证创建菜单是否成功

在浏览器输入:https://api.weixin.qq.com/cgi-bin/menu/get?access_token=Token或者调试输入token,然后就可以了。

toekn的还是通过appid和secret在调试接口处获取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: