目录
- 1、访问微信公众号平台
- 2、扫码登录
- 3、登录后进行接口信息配置
- 4、完成以上配置和代码,将代码部署到服务器上,后台就可以接收到公众号的关注、取关、用户发送的消息等等事件拉!
1、访问微信公众号平台
微信公众号测试地址
2、扫码登录
3、登录后进行接口信息配置
外网IP和端口对应的后台服务器需要定义配置的端口,并且使用配置的token值进行验证
@GetMapping("/wx/portal/{appId}/{appSecret}")
public void verifyToken(@PathVariable("appId") String appId,@PathVariable("appSecret") String appSecret,HttpServletRequest request,HttpServletResponse response) throws IOException {log.info("【签名验证】appId:{},appSecret:{}", appId, appSecret);String method = request.getMethod();if ("GET".equalsIgnoreCase(method)) {String signature = request.getParameter("signature");String timestamp = request.getParameter("timestamp");String nonce = request.getParameter("nonce");String echoStr = request.getParameter("echostr");//排序String sortString = sort(TOKEN, timestamp, nonce);//加密String myString = sha1(sortString);//校验if (myString != null && myString != "" && myString.equals(signature)) {System.out.println("签名校验通过");//如果检验成功原样返回echostr,微信服务器接收到此输出,才会确认检验完成。response.getWriter().write(echoStr + "");} else {System.out.println("签名校验失败");response.getWriter().write("");}}
}
使用到的方法
public String sort(String token, String timestamp, String nonce) {String[] strArray = {token, timestamp, nonce};Arrays.sort(strArray);StringBuilder sb = new StringBuilder();for (String str : strArray) {sb.append(str);}return sb.toString();
}public String sha1(String str) {try {MessageDigest digest = MessageDigest.getInstance("SHA-1");digest.update(str.getBytes());byte messageDigest[] = digest.digest();// Create Hex StringStringBuffer hexString = new StringBuffer();// 字节数组转换为 十六进制数for (int i = 0; i < messageDigest.length; i++) {String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);if (shaHex.length() < 2) {hexString.append(0);}hexString.append(shaHex);}return hexString.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return "";
}