`
zzc1684
  • 浏览: 1229127 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

微信公众开放平台开发08---纯java 实现微信开发:编写自定义菜单

阅读更多
微信公众开放平台开发08---纯java 实现微信开发:编写自定义菜单

 微信公众开放平台开发08---纯java 实现微信开发:编写自定义菜单
 技术交流群:JavaDream:251572072
------------------------------------------------------------------------
1.这里只做一个很简单的例子:
2.像我一样木有钱升级服务号的,去申请测试号吧:
3.下面看代码,太sample了
-----------------------------------------------------------
5.创建项目ROOT:
a.用到的jar包
//  dom4j-1.6.jar
//commons-beanutils-1.8.3.jar
//commons-collections-3.1.jar
//commons-lang-2.3.jar
//commons-logging-1.0.4.jar
//ezmorph-1.0.6.jar
//json-lib-2.1.jar
//slf4j-api-1.5.8.jar
//slf4j-nop-1.5.8.jar
以上的jar包是上次用的.
fastjson-1.1.1.jar
httpclient-4.2.5.jar
httpcore-4.2.4.jar
------------------------------------
b.项目结构:
credream
credream.entity
--/ROOT/src/credream/entity/AccessToken.java
credream.https
/ROOT/src/credream/https/HttpClientConnectionManager.java
/ROOT/src/credream/https/MySSLSocketFactory.java
/ROOT/src/credream/https/TrustAnyTrustManager.java
credream.utils
--/ROOT/src/credream/utils/MyX509TrustManager.java
--/ROOT/src/credream/utils/SHA1.java
--/ROOT/src/credream/utils/WechatCallbackApi.java
--/ROOT/src/credream/utils/WeixinUtil.java 
--//这个类是用来进行微信服务器验证的,需要用到token,微信服务器验证的时候,会向
--//对应的url,传送get参数,这个类,接收了参数后,利用参数进行计算,加密,对比...
--//
/ROOT/src/credream/utils/WxMenuUtils.java//这个类是用来进行菜单的操作
credream.weixin
--/ROOT/src/credream/weixin/weixinUtil.java
含有--是这次,用不到的类
----------------------------------------------------------------------
c.下面是操作菜单用到的代码:这个部分其实不用公网的ip,只需要把appid,和appsecret传给微信服务器,微信服务器会
  返回accesstoken,这个东西很有用的,需要把这个作为参数传给微信服务器,看代码吧先:
d./ROOT/src/credream/utils/WeixinUtil.java 
package credream.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import credream.https.HttpClientConnectionManager;

/**
 * 微信自定义菜单创建
 */
public class WxMenuUtils {
 // http客户端
 public static DefaultHttpClient httpclient;
 
 static {
  httpclient = new DefaultHttpClient();
  httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient);
  // 接受任何证书的浏览器客户端
 }

 public static void main(String[] args) {
  try {
   // 获取accessToken -参数appid,secret
   String accessToken = getAccessToken("appid(这里填写你自己的啊)", "appsecret(这里填写你自己的啊)");
   System.out.println(accessToken);
   // 创建菜单
   //String s = "{\"button\":[{\"name\":\"休闲娱乐\",\"sub_button\":[{\"type\":\"click\", \"name\":\"笑话大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"内涵段 子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑图片\",\"key\": \"m_laughImg\"}]},{\"name\":\"实用工具\",\"sub_button\":[{\"type\":\"click \",\"name\":\"天气查询\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name \":\"公交查询\",\"key\":\"m_bus\"}]},{\"type\":\"click\",\"name\":\"关于企特\", \"key\":\"m_about\"}]}";
   String s = "{\"button\":[{\"name\":\"休闲娱乐\",\"sub_button\":[{\"type\":\"click\", \"name\":\"笑话大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"内涵段 子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑图片\",\"key\": \"m_laughImg\"}]},{\"name\":\"实用工具\",\"sub_button\":[{\"type\":\"click \",\"name\":\"天气查询\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name \":\"公交查询\",\"key\":\"m_bus\"},{\"type\":\"click\",\"name\":\"功能菜单\", \"key\":\"m_sysmenu\"}]},{\"name\":\"消息示例\",\"sub_button\":[{\"type\": \"click\",\"name\":\"关于企特\",\"key\":\"m_about\"},{\"type\":\"click\", \"name\":\"图文消息\",\"key\":\"m_imgmsg\"},{\"type\":\"click\",\"name\":\"音 乐消息\",\"key\":\"m_musicmsg\"}]}]}";
   String res = createMenu(s, accessToken);
   System.out.println(res);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 
 /**
  * 创建菜单
  */
 public static String createMenu(String params, String accessToken) throws Exception {
  HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken);
  httpost.setEntity(new StringEntity(params, "UTF-8"));
  HttpResponse response = httpclient.execute(httpost);
  String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
  System.out.println(jsonStr);
  JSONObject object = JSON.parseObject(jsonStr);
  return object.getString("errmsg");
 }

 /**
  * 获取accessToken
  */
 public static String getAccessToken(String appid, String secret) throws Exception {
  HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
  HttpResponse response = httpclient.execute(get);
  String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
  JSONObject object = JSON.parseObject(jsonStr);
  return object.getString("access_token");
 }
 
 /**
  * 查询菜单
  */
 public static String getMenuInfo(String accessToken) throws Exception {
  HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken);
  HttpResponse response = httpclient.execute(get);
  String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
  return jsonStr;
 }
 
 /**
  * 删除自定义菜单
  */
 public static String getAccessToken(String accessToken) throws Exception {
  HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken);
  HttpResponse response = httpclient.execute(get);
  String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
  JSONObject object = JSON.parseObject(jsonStr);
  return object.getString("errmsg");
 }
}
-------------------------------------------------------------------------------------------------------------
1.下面是一个辅助类,用来管理证书的:
2.第一个:管理http链接和参数提交
/ROOT/src/credream/https/HttpClientConnectionManager.java
package credream.https;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientConnectionManager {
 
 
 /**
  * 获取SSL验证的HttpClient
  * @param httpClient
  * @return
  */
 public static HttpClient getSSLInstance(HttpClient httpClient){
  ClientConnectionManager ccm = httpClient.getConnectionManager();
  SchemeRegistry sr = ccm.getSchemeRegistry();
  sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));
  httpClient =  new DefaultHttpClient(ccm, httpClient.getParams());
  return httpClient;
 }
 
 /**
  * 模拟浏览器post提交
  * @param url
  * @return
  */
 public static HttpPost getPostMethod(String url) {
  HttpPost pmethod = new HttpPost(url); // 设置响应头信息
  pmethod.addHeader("Connection", "keep-alive");
  pmethod.addHeader("Accept", "*/*");
  pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  pmethod.addHeader("Host", "mp.weixin.qq.com");
  pmethod.addHeader("X-Requested-With", "XMLHttpRequest");
  pmethod.addHeader("Cache-Control", "max-age=0");
  pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
  return pmethod;
 }

 /**
  * 模拟浏览器GET提交
  * @param url
  * @return
  */
 public static HttpGet getGetMethod(String url) {
  HttpGet pmethod = new HttpGet(url);
  // 设置响应头信息
  pmethod.addHeader("Connection", "keep-alive");
  pmethod.addHeader("Cache-Control", "max-age=0");
  pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
  pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");
  return pmethod;
 }
}
-----------------------------------------------------------------------------------------------------------------
3.证书管理器:
/ROOT/src/credream/https/TrustAnyTrustManager.java
package credream.https;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
 * 这个是一个证书管理器和下面的MyX509TrustManager类是一样的
 * @author credream
 *
 */
public class TrustAnyTrustManager implements X509TrustManager{

 public void checkClientTrusted(X509Certificate[] chain, String authType)
   throws CertificateException {
  
 }

 public void checkServerTrusted(X509Certificate[] chain, String authType)
   throws CertificateException {
  
 }

 public X509Certificate[] getAcceptedIssuers() {
  return null;
 }

}
-------------------------------------------------------------------------------------------
4./ROOT/src/credream/https/MySSLSocketFactory.java
package credream.https;
/**
 * 这里是证书的一个工厂类,用来实现证书的创建
 * @author credream
 */
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;

public class MySSLSocketFactory extends SSLSocketFactory{
 static{
  mySSLSocketFactory = new MySSLSocketFactory(createSContext());
 }
 private static MySSLSocketFactory mySSLSocketFactory = null;
 private static SSLContext createSContext(){
  SSLContext sslcontext = null;
  try {
   sslcontext = SSLContext.getInstance("SSL");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  try {
   sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null);
  } catch (KeyManagementException e) {
   e.printStackTrace();
   return null;
  }
  return sslcontext;
 }
 
 @SuppressWarnings("deprecation")
 private MySSLSocketFactory(SSLContext sslContext) {
  super(sslContext);
  this.setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER);
 }
 
 public static MySSLSocketFactory getInstance(){
  if(mySSLSocketFactory != null){
   return mySSLSocketFactory;
  }else{
   return mySSLSocketFactory = new MySSLSocketFactory(createSContext());
  }
 }
 
}
---------------------------------------------------------------------------------------------------
其实没有必要创建web应用,普通的java类,含有main方法就可以简单的实现菜单的创建,也没必要一定要用公网ip,
上面是所有的创建菜单的代码.
---------------------------------------------------------------------------------------------------------

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics