springboot实现公众号接入,遇到一直token认证失败的原因

1、封装微信加密认证工具类
public class CheckUtil {public static final String tooken = "pxtoken"; //开发者自行定义Tooken要与公众号平台输入的token保持一致public static boolean checkSignature(String signature, String timestamp, String nonce) {//1.定义数组存放tooken,timestamp,nonceString[] arr = new String[]{tooken, timestamp, nonce};//2.对数组进行排序Arrays.sort(arr);//3.生成字符串StringBuffer sb = new StringBuffer();for (String s : arr) {sb.append(s);}String temp = getSha1(sb.toString());//加密成一个字符串再与signature对比logger.info("\n----------执行微信签名加密认证---------------"+temp.equals(signature));System.out.println("----------执行微信签名加密认证---------------"+temp.equals(signature));//5.将加密后的字符串,与微信传来的加密签名比较,返回结果return temp.equals(signature);}public static String getSha1(String str) {if (str == null || str.length() == 0) {return null;}char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f'};try {MessageDigest mdTemp = MessageDigest.getInstance("SHA1");mdTemp.update(str.getBytes("UTF-8"));byte[] md = mdTemp.digest();int j = md.length;char buf[] = new char[j * 2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 = md[i];buf[k++] = hexDigits[byte0 >>> 4 & 0xf];buf[k++] = hexDigits[byte0 & 0xf];}return new String(buf);} catch (Exception e) {// TODO: handle exceptionreturn null;}}}
2、层的代码
@Controllerpublic class Uhtml {@ResponseBody@GetMapping(value = "http://www.kingceram.com/wx/check",produces = "text/plain;charset=utf-8")public void wxCheck(@RequestParam(name = "signature", required = false) String signature,@RequestParam(name = "timestamp", required = false) String timestamp,@RequestParam(name = "nonce", required = false) String nonce,@RequestParam(name = "echostr", required = false) String echostr,HttpServletResponse response){System.out.println("-----------验证微信订阅号信息开始------------");logger.info("\n-----------验证微信订阅号信息开始------------");try {System.out.println("signature = "+signature);logger.info("\nsignature = "+signature);System.out.println("timestamp = "+timestamp);logger.info("\ntimestamp = "+timestamp);System.out.println("nonce = "+nonce);logger.info("\nnonce = "+nonce);System.out.println("echostr = "+echostr);logger.info("\nechostr = "+echostr);if (CheckUtil.checkSignature(signature, timestamp, nonce)) {System.out.println("-----------验证微信订阅号信息结束------------");logger.info("\n-----------验证微信订阅号信息结束------------");BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());out.write(echostr.getBytes());out.flush();out.close();}else{System.out.println("-----------不是微信服务器发送过来的请求------------");logger.info("\n-----------不是微信服务器发送过来的请求------------");}}catch (Exception e){e.printStackTrace();}}}
3、为了避免修改代码后频繁的部署测试,我选用的是实现内网穿透,下载地址:,根据自己实际情况下载对应版本 。
4、下载完客户端之后,还需要下载一个.ini文件,如下图:
5、安装完之后需要先登录,官网右上角有登录,登进去之后购买免费隧道,如下图:
6、购买完之后点击我的隧道就可以查看到隧道信息,如下图:
7、进行隧道配置,如下图:

springboot实现公众号接入,遇到一直token认证失败的原因

文章插图
8、复制隧道,打开下载好的.ini,将token复制到指定位置,如下图:
9、最后再双击下载好的.exe客户端启动,至此我们已经实现了内网穿透,可以通过本地映射出来的地址进行外网访问,如图所示: