1、公众号后台配置:点击基本配置-修改配置
URL:填写服务端建立的接口地址(接口要能接受get/post请求)
token:随便写
秘钥:自动生成
配好之后,点击提交,微信会往接口发送一条get请求的数据,服务端校验后,把微信发送的数据中的echoStr字段原样返回,微信接收到会提示修改成功。
2、配置服务端接口
/**
* 接受微信发送的消息
* @param request 公参
* @return 返回结果
*/
@SneakyThrows
@RequestMapping(value = "/getTencentMsg", method = {RequestMethod.POST, RequestMethod.GET})
@ApiIgnore
public void getTencentMsg(HttpServletRequest request, HttpServletResponse response) {
String method = request.getMethod();
if(RequestMethodEnum.GET.getDesc().equals(method)){
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echoStr = request.getParameter("echostr");
String token = "weiyouzz";
boolean checkSignature = wxUtils.checkSignature(signature, timestamp, nonce, token);
if (checkSignature) {
response.getWriter().write(echoStr+"");
}
}else {
//post请求跟消息相关,往下翻到第三点
}
}
//校验微信请求
/**
* 验证微信签名
*/
public boolean checkSignature(String signature, String timestamp,String nonce, String token) {
// 1.将token、timestamp、nonce三个参数进行字典序排序
String[] arr = new String[]{token, timestamp, nonce};
Arrays.sort(arr);
// 2. 将三个参数字符串拼接成一个字符串进行sha1加密
StringBuil