【1】不说废话 直接上图 上代码。
公众号登录传送门:https://mp.weixin.qq.com
写一个服务接口
@RequestMapping("xxxxx/wx")
public void weChatDocking(HttpServletResponse response,HttpServletRequest request) throws IOException{
/**
* 微信加密字符串
*/
String signatureStr = request.getParameter("signature");
/**
* 时间戳
*/
String timestampStr = request.getParameter("timestamp");
/**
* 随机数
*/
String nonceStr = request.getParameter("nonce");
/**
* 随机字符串
*/
String echostrStr = request.getParameter("echostr");
/**
* 1. 将token、timestamp、nonce三个参数进行字典序排序
* 2. 将三个参数字符串拼接成一个字符串进行sha1加密
* 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
*/
PrintWriter writer = response.getWriter();
if(SignUtil.checkSignatureStr(signatureStr, timestampStr, nonceStr)){
writer.write(echostrStr);
}
}
package com.zcj.portal.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* 完成秒信宝微信对接 工具类
* @author ldd
*
*/
public class SignUtil {
/**
* token 要和你在微信公众号里配置的哪个token一样
*/
private static final String tokenStr = "lcnm";
public static boolean checkSignatureStr(String signature, String timestamp,String nonce){
// 1.将token、timestamp、nonce三个参数进行字典序排序
String [] arr = new String []{tokenStr,timestamp,nonce};
Arrays.sort(arr);
// 2. 将三个参数字符串拼接成一个字符串进行sha1加密
StringBuffer buffer = new StringBuffer();
for (String str : arr) {
buffer.append(str);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
//将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(buffer.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return tmpStr != null?tmpStr.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;
}
}
很简单的东西直接贴代码了。