开发者提交信息后,微信服务器将发送GET请求到填写的URL上,GET请求携带四个参数:
参数 | 描述 |
---|---|
signature | 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。 |
timestamp | 时间戳 |
nonce | 随机数 |
echostr | 随机字符串 |
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
下面是signature的校验工具类
package util; import java.security.MessageDigest; import java.util.Arrays; public final class MessageDigestUtil { private MessageDigest alga; private static MessageDigestUtil _instance ; public static MessageDigestUtil getInstance() { if (_instance == null ){ _instance = new MessageDigestUtil(); } return _instance; } private MessageDigestUtil() { try { alga = MessageDigest.getInstance("SHA-1"); } catch(Exception e) { throw new InternalError("init MessageDigest error:" + e.getMessage()); } } public static String byte2hex(byte[] b) { String des = ""; String tmp = null; for (int i = 0; i < b.length; i++) { tmp = (Integer.toHexString(b[i] & 0xFF)); if (tmp.length() == 1) { des += "0"; } des += tmp; } return des; } public String encipher(String strSrc) { String strDes = null; byte[] bt = strSrc.getBytes(); alga.update(bt); strDes = byte2hex(alga.digest()); //to HexString return strDes; } public static void main(String[] args) { String signature="b7982f21e7f18f640149be5784df8d377877ebf9"; String timestamp="1365760417"; String nonce="1365691777"; String[] ArrTmp = { "token", timestamp, nonce }; Arrays.sort(ArrTmp); StringBuffer sb = new StringBuffer(); for (int i = 0; i < ArrTmp.length; i++) { sb.append(ArrTmp[i]); } String pwd =MessageDigestUtil.getInstance().encipher(sb.toString()); if (signature.equals(pwd)) { System.out.println("token 验证成功~!"); }else { System.out.println("token 验证失败~!"); } } }
本文出自 “流星雨的IT路程” 博客,请务必保留此出处http://lxy2020.blog.51cto.com/2528961/1567329
原文地址:http://lxy2020.blog.51cto.com/2528961/1567329