看到微信的公共平台接入文档接口验证的例子是PHP写的,对于很多不是做php的人来说有点麻烦,虽然编程思想是相同的,逻辑也很简单,但是一种语言有一种语言的语法规范,其实代码的编写还是差距挺大的。这里写一下JAVA版接口验证的实现。
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
String reSignature = null;
try {
String[] str = { TOKEN, timestamp, nonce };
Arrays.sort(str);
String bigStr = str[0] + str[1] + str[2];
reSignature = new SHA1().getDigestOfString(bigStr.getBytes())
.toLowerCase();
} catch (Exception e) {
e.printStackTrace();
}
if (null != reSignature && reSignature.equals(signature)) {
//请求来自微信
out.print(echostr);
} else {
out.print("error request! the request is not from weixin server");
}
out.flush();
out.close();
逻辑代码就这些,就是按照文档上说的来:
1. 将token、timestamp、nonce三个参数进行字典序排序 2. 将三个参数字符串拼接成一个字符串进行sha1加密 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信