package com.example.hyh; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @RestController public class HelloController { @RequestMapping(value = "/wxcheck", method = RequestMethod.GET) public void check(HttpServletRequest request, HttpServletResponse response) throws IOException { String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); if (SignUtil.checkSignature(signature, timestamp, nonce)) { response.getWriter().write(echostr); // 直接写入响应体 } else { response.getWriter().write("验证失败"); } } } package com.example.hyh; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; public class SignUtil { // 与微信公众平台配置的Token一致 private static final String TOKEN = "hyh"; public static boolean checkSignature(String signature, String timestamp, String nonce) { // 检查参数是否为空 if (signature == null || timestamp == null || nonce == null) { return false; } // 1. 将token、timestamp、nonce按字典序排序 String[] arr = new String[]{TOKEN, timestamp, nonce}; Arrays.sort(arr); // 2. 将三个参数字符串拼接成一个字符串 StringBuilder content = new StringBuilder(); for (String s : arr) { content.append(s); } // 3. 对拼接后的字符串进行SHA-1加密 String encryptedStr = sha1(content.toString()); // 4. 将加密后的字符串与signature对比 return encryptedStr != null && encryptedStr.equals(signature); } private static String sha1(String str) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(str.getBytes()); return byteToHexStr(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("SHA-1算法不可用", e); } } private static String byteToHexStr(byte[] byteArray) { StringBuilder hexStr = new StringBuilder(); for (byte b : byteArray) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hexStr.append("0"); } hexStr.append(hex); } return hexStr.toString(); } }用的ngrok,一直token验证失败
微信公众号服务器配置一直提示token验证失败?本地使用postman,请求了要设置在微信公众号服务器回调的URL,可以正常返回echostr,点击提交,一直报错token验证失败,请问这个是什么原因呢?
03-19