一:微信接入原理
1.1 微信接入的时候,其实是一个doget请求它携带的参数有signature微信加密签名、 timestamp 时间戳、nonce 随机数。我们只要验证定义的token、timestamp、nonce三者通过sha1加密后与signature是否相同,如果相同便可接入成功。服务器课使用花生壳映射http://www.oray.com/。下面介绍下具体代码的编写
1.2 工具类的编写:主要进行sha1加密
package com.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; /** * * @author 黄路飞 * * @data 2016年6月16日19:23:00 */ public class SignUtil { //微信接口配置时填写的Token private static String token = "weixin"; /** * * 校验签名 * @param signature 微信加密签名 * @param timestamp 时间戳 * @param nonce 随机数 * @return true/false */ public static boolean checkSignature(String signature, String timestamp, String nonce) { //字典排序 String[] paramArr = new String[] { token, timestamp, nonce }; Arrays.sort(paramArr); String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]); String ciphertext = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); // 对接后的字符串进行sha1加密 byte[] digest = md.digest(content.toString().getBytes()); ciphertext = byteToStr(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false; } /** * 将字节转换为十六进制字符串 * @param byteArray * @return */ private static String byteToStr(byte[] byteArray) { String strDigest = ""; for (int i = 0; i < byteArray.length; i++) { strDigest += byteToHexStr(byteArray[i]); } return strDigest; } /** * 将字节转换为十六进制字符串 * * @param mByte * @return */ private static String byteToHexStr(byte mByte) { char[] Digit = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ }; char[] tempArr = new char[2]; tempArr[0] = Digit[(mByte >>> 4) & 0X0F]; tempArr[1] = Digit[mByte & 0X0F]; String s = new String(tempArr); return s; } }
1.3 doget请求处理
package com.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; import com.util.SignUtil; /** * * @author 黄路飞 * * @data 2016年6月16日19:34:37 */ public class CoreServlet extends HttpServlet { private static final long serialVersionUID = 2168408682288701938L; /** * 请求校验(确认请求来自微信服务器) */ public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); if (SignUtil.checkSignature(signature, timestamp, nonce)) { out.print(echostr); } out.close(); out = null; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
备注:学习要点 1) 字典排序
2) sha1加密
二:微信测试号具体接入步骤
备注:URL 为花生壳地址+部署项目名+servlet名
Token 为项目中填写的token
时间: 2024-10-13 22:27:17