微信接入笔记记录

第一步:填写服务器配置

第二步:验证消息的确来自微信服务器

 

这两步是什么意思呢,就是微信要验证你的服务器地址是否正确,所以会向你你的服务器请求一次,你得根据微信要求的规则,返回相应的数据

 

微信的规则如下

开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:

1)将token、timestamp、nonce三个参数进行字典序排序

2)将三个参数字符串拼接成一个字符串进行sha1加密

3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

 

看起来有点复杂,我们可以直接上代码

==============================================================

我们先定义一个给微信请求的接口,接受微信的参数

 1 @RequestMapping(value = "check")
 2     public String check(HttpServletRequest request, HttpServletResponse response) throws IOException {
 3         System.out.println("开始验证token");
 4 
 5         // 微信加密签名
 6         String signature = request.getParameter("signature");
 7         // 时间戳
 8         String timestamp = request.getParameter("timestamp");
 9         // 随机数
10         String nonce = request.getParameter("nonce");
11         // 随机字符串
12         String echostr = request.getParameter("echostr");
13         // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
14         if (SignUtil.checkSignature(signature, timestamp, nonce)) {
15             System.out.print("echostr="+echostr);
16             return echostr;
17         }else{
18             return "fail";
19         }
20     }

根据微信要求的规则进行排序加密

 

 1 public static boolean checkSignature(String signature, String timestamp,String nonce) {
 2         // 1.将token、timestamp、nonce三个参数进行字典序排序
 3         String[] arr = new String[] { token, timestamp, nonce };
 4         Arrays.sort(arr);
 5 
 6         // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
 7         StringBuilder content = new StringBuilder();
 8         for (int i = 0; i < arr.length; i++) {
 9             content.append(arr[i]);
10         }
11         System.out.println(content.toString());
12 
13         String tmpStr = DigestUtils.sha1Hex(content.toString());
14         System.out.println("tmpStr="+tmpStr);
15 
16         // 3.将sha1加密后的字符串可与signature对比,标识该请求来源于微信
17         return tmpStr != null ? tmpStr.equals(signature) : false;
18     }

这里我们可以导入jar包帮我们加密

import org.apache.commons.codec.digest.DigestUtils;

 

好了,我们可以把项目发到服务器,用域名替换ip和端口,把对外接口地址填到配置URL中

 

具体的项目地址可以看我的git

摸我

posted @ 2018-01-05 14:39  XuMinzhe  阅读(199)  评论(0编辑  收藏  举报