最近研究微信公众号的二次开发,首先要申请个微信公众号(如何申请不多说),接下来要验证成为开发者,但官网上提供的源代码是php的http://mp.weixin.qq.com/wiki/index.php?title=%E6%8E%A5%E5%85%A5%E6%8C%87%E5%8D%97

自己结合网上的资源再实践写了个java版的微信验证,

简单步骤:创建java web项目-->新建servlet-->编写代码-->打包上传服务器-->微信公众平台验证

代码如下



package com.weixin.pamp;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WeiXinServlet extends HttpServlet {
    / **
     *
     */
    private static final long serialVersionUID = 7534232612712558319L;
    //自定义的TOken
    public static final String Token = "pamp";
    / **
     * Constructor of the object.
     */
    public WeiXinServlet() {
        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 {
        System.out.println("范文芳的阿飞");
         try{ 
             //微信加密签名
              String signature = request.getParameter("signature");
              //时间戳
              String timestamp = request.getParameter("timestamp");
              //随机数
              String nonce = request.getParameter("nonce");
              //随机字符串
              String echostr = request.getParameter("echostr");
            if (echostr!=null) {
                echostr = checkAuthentication(signature,timestamp,nonce,echostr);
                //验证通过返回随即字串
                response.getWriter().write(echostr);
                response.getWriter().flush();
            }
        }catch(Exception e){
        }
    }
    / **
     * 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 {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        出
                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        了out.flush();
        out.close();
    }
    / **
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }
    / **
     *  Function:微信验证方法
     *  @author JLC
     *  @param signature 微信加密签名
     *  @param timestamp 时间戳
     *  @param nonce     随机数
     *  @param echostr   随机字符串
     *  @return
     */
    private String  checkAuthentication(String signature,String timestamp,String nonce,String echostr) {
        String result ="";
        // 将获取到的参数放入数组
        String[] ArrTmp = { Token, timestamp, nonce };
        // 按微信提供的方法,对数据内容进行排序
        Arrays.sort(ArrTmp);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < ArrTmp.length; i++) {
            sb.append(ArrTmp[i]);
        }
        // 对排序后的字符串进行SHA-1加密
        String pwd = Encrypt(sb.toString());
        if (pwd.equals(signature)) {
            try {
                System.out.println("微信平台签名消息验证成功!");
                result = echostr;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("微信平台签名消息验证失败!");
        }
        return result;
    }
    / **
     * 用SHA-1算法加密字符串并返回16进制串
     *
     * @param strSrc
     * @return
     */
    private String Encrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update(bt);
            strDes = bytes2Hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            System.out.println("错误");
            return null;
        }
        return strDes;
    }
    private String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
                                               
}

将以上代码打包上传到服务器,再在微信公众平台进行验证


wKiom1Mqg1zQqws7AADJb33-HpY584.jpg