转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/45042549
http://www.llwjy.com/blogdetail/43b9fff3f2b827f4444826aeee756ec7.html
个人博客站已经上线了,网址 www.llwjy.com ~欢迎各位吐槽~
-------------------------------------------------------------------------------------------------
从这篇博客起,个人开启另一个板块的开发介绍:微信公众平台。官方给的参考文档多数都是基于PHP的,所以关于如何使用PHP开发参考官方文档即可,这里只介绍如何基于java做开发。
微信公共平台官网地址:https://mp.weixin.qq.com/ 没有公共帐号的可以直接在上面注册,注册部分自己实践,这里不做介绍,下面的部分都是在您已有微信公共号的前提下,微信公共平台开发者文档:http://mp.weixin.qq.com/wiki/home/index.html。
开发环境准备
java IDE:MyEclipse;web服务:apache+tomcate;计算机:需要有外网独立IP(如果没有的话,可以搜索下花生壳)。
接入指南
在开发者文档的新手指南--接入指南中我们可以看到,在实现具体业务之前,需要验证服务器的有效性,因此我们需要先开发一个接口来完成这个验证。注:微信公众号接口只支持80接口,所以apache的监听端口是80。
项目开发
在MyEclipse中新建一个web项目,自己这边的包分布如下图所示:
在开发者文档中我们可以得知,服务器验证是对一些信息做sha1加密处理,我们需要写加密算法,具体代码如下:
/** *@Description: JAVA实现常见加密算法 */ package com.lulei.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Encrypt { /** * @param str 需要加密的字符串 * @param encName 加密种类 MD5 SHA-1 SHA-256 * @return * @Author:lulei * @Description: 实现对字符串的加密 */ public static String encrypt(String str, String encName){ String reStr = null; try { MessageDigest md5 = MessageDigest.getInstance(encName); byte[] bytes = md5.digest(str.getBytes()); StringBuffer stringBuffer = new StringBuffer(); for (byte b : bytes){ int bt = b&0xff; if (bt < 16){ stringBuffer.append(0); } stringBuffer.append(Integer.toHexString(bt)); } reStr = stringBuffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return reStr; } public static void main(String[] args) { System.out.println(Encrypt.encrypt("nihao", null)); } }加密/校验流程如下:
对于微信公共平台的加密,我们创建SignUtil类,让他来完成具体的验证工作,源代码如下:
/** *@Description: 微信验证 */ package com.lulei.weixin.util; import java.util.Arrays; import com.lulei.util.Encrypt; import com.lulei.weixin.config.Config; public class SignUtil { /** * @param signature * @param timestamp * @param nonce * @return * @Author:lulei * @Description: 微信权限验证 */ public static boolean checkSignature(String signature, String timestamp, String nonce) { String[] arr = new String[] { Config.TOKEN, timestamp, nonce }; //按字典排序 Arrays.sort(arr); StringBuilder content = new StringBuilder(); for (int i = 0; i < arr.length; i++) { content.append(arr[i]); } //加密并返回验证结果 return signature == null ? false : signature.equals(Encrypt.encrypt(content.toString(), "SHA-1")); } }在上面有一个常量Config.TOKEN,这个是来自配置文件,也就是即将要在微信公共平台填写的Token值,可以根据自己的需要填写(英文或数字,3~32位)。在阅读相关开发者文档后发现,微信公共平台的接口几乎都是输出json字符串或者xml字符串,因此我们创建一个接口父类StringServletBase,具体代码如下:
/** *@Description: */ package com.lulei.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public abstract class StringServletBase extends HttpServlet { private static final long serialVersionUID = 1L; /** * Constructor of the object. */ public StringServletBase() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); response.setContentType("text/plain"); String str = parseString(request); if (str != null) { out.print(str); } out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { } /** * @param request * @return * @Author:lulei * @Description: 接口需要输出的字符串 */ protected abstract String parseString(HttpServletRequest request); }在接入指南中,还有一个URL项目需要填写,这个URL地址就是微信服务器和自己服务器互相通信的接口,因此我们创建WeiXinServlet接口类,源代码如下:
/** *@Description: */ package com.lulei.weixin.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import com.lulei.util.ParseRequest; import com.lulei.weixin.util.SignUtil; public class WeiXinServlet extends StringServletBase { private static final long serialVersionUID = 1L; /** * @param request * @return * @throws ServletException * @throws IOException * @Author:lulei * @Description: 这里是微信服务器验证 */ protected String check(HttpServletRequest request) { String signature = ParseRequest.getString(request, "signature", ""); String timestamp = ParseRequest.getString(request, "timestamp", ""); String nonce = ParseRequest.getString(request, "nonce", ""); String echostr = ParseRequest.getString(request, "echostr", ""); if (SignUtil.checkSignature(signature, timestamp, nonce)) { return echostr; } return null; } @Override protected String parseString(HttpServletRequest request) { //微信首次验证 return check(request); } }
在web.xml文件中,添加如下代码:
<!-- 微信服务器 --> <servlet> <servlet-name>WeiXinServlet</servlet-name> <servlet-class>com.lulei.weixin.servlet.WeiXinServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WeiXinServlet</servlet-name> <url-pattern>/weixin.do</url-pattern> </servlet-mapping>到现在为止,所有的准备工作都已经做好,下面就开始配置项的填写(注:自己的这个weixin.do接口必须可以通过外网ip的80端口访问到)
填写配置项
登录微信公共平台,在左侧最下方选择开发者中心菜单,如下图:
在右侧选择配置项(启用左侧按钮),在页面上填写与自己开发想匹配的信息,如下图:
EncodingAESKey直接选择随机生成即可,如果你填写的信息都正确的话,提价就完成了服务器有效性验证,这时候点击启用就可以开始自己的微信公共平台开发之旅。下一篇博客将介绍如何采集百小度的聊天信息,实现微信小机器人功能~
原文地址:http://blog.csdn.net/xiaojimanman/article/details/45042549