刚刚开始处理处理小程序消息推送的时候有点懵,处理完之后也是豁然开朗,所以贴上代码给大家分享。说明一下,我用的是SpringBoot。
实现功能分别用了三个类:1、entity:WeChatMessage.java、2、controller:WeChatMessageController.java、3、service:WeCharMessageService.java
直接上代码: 首先是entity
1 public class WeChatMessage { 2 3 //微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数 4 private String signature; 5 6 //时间戳 7 private String timestamp; 8 9 //随机数 10 private String nonce; 11 12 //随机字符串 13 private String echostr; 14 15 public String getSignature() { 16 return signature; 17 } 18 19 public void setSignature(String signature) { 20 this.signature = signature; 21 } 22 23 public String getTimestamp() { 24 return timestamp; 25 } 26 27 public void setTimestamp(String timestamp) { 28 this.timestamp = timestamp; 29 } 30 31 public String getNonce() { 32 return nonce; 33 } 34 35 public void setNonce(String nonce) { 36 this.nonce = nonce; 37 } 38 39 public String getEchostr() { 40 return echostr; 41 } 42 43 public void setEchostr(String echostr) { 44 this.echostr = echostr; 45 } 46 47 }
其次是controller
@RestController public class WeChatMessageController { @Autowired private WeChatMessageService service; @RequestMapping(value="/getMessage.do", method=RequestMethod.GET) public String getMessage(WeChatMessage message) { return service.checkSignature(message); } }
最后是service:
@Service public class WeChatMessageService { public String checkSignature(WeChatMessage message) { String signature = message.getSignature(); String timestamp = message.getTimestamp(); String nonce = message.getNonce(); String token = "XXXXXXX"; //必须与请求参数中的token一致 //将token、timestamp、nonce三个参数进行字典排序 String[] arr = new String[] {token, timestamp, nonce}; Arrays.sort(arr); StringBuilder content = new StringBuilder(); for (int i = 0; i < arr.length; i++) { content.append(arr[i]); } MessageDigest md = null; String tmpStr = null; try { md = MessageDigest.getInstance("SHA-1"); // 将三个参数字符串拼接成一个字符串进行sha1加密 byte[] digest = md.digest(content.toString().getBytes()); tmpStr = byteToStr(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) ? message.getEchostr() : "" : ""; } /** * 将字节数组转换为十六进制字符串 * @param byteArray * @return */ private String byteToStr(byte[] byteArray) { String strDigest = ""; for (int i = 0; i < byteArray.length; i++) { strDigest += byteToHexStr(byteArray[i]); } return strDigest; } /** * 将字节转换为十六进制字符串 * @param mByte * @return */ private 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; } }
以上代码亲测可用,有不好的地方请朋友们多多指正。