相关推荐recommended
微信公众平台配置提示“token验证失败”(几乎全部踩坑贴,SpringBoot返回字符串,多双引号)
作者:mmseoamin日期:2024-04-27
  1. 首先先要检验自己的服务器是否可以连接成功,不然就是报错系统错误。如果服务器可以连接成功,就是到了这一步,配置失败或者token验证失败。

  2. 到了这步,一般是因为返回的echostr是有问题的,检查自己写的@GetMapping是否正确,而不是使用默认的JSON 字符串。正确配置如下(后面粘贴源代码):微信公众平台配置提示“token验证失败”(几乎全部踩坑贴,SpringBoot返回字符串,多双引号),第1张

    1. /**
           * 用于验证微信服务器发来的get请求,进行签名验证
           * https://33186bde.r1.cpolar.top/wx/portal/wxe136919795d575a1
           *
           * @param appid     这个是通过微信服务器访问的url路径上的appId进行获取,
           * @param signature 微信加密签名
           * @param timestamp 时间戳
           * @param nonce     随机数
           * @param echostr   随机字符串,这个验证成功返回即可
           * @return echostr 随机字符串,这个验证成功返回即可
           * @description @GetMapping(produces = "text/plain; charset=UTF-8")这个意思是返回一个用于指定请求处理方法返回的响应内容类型和字符编码
           */
          @GetMapping(produces = "text/plain;charset=utf-8")
          public String validate(@PathVariable String appid,
                                 @RequestParam(value = "signature", required = false) String signature,
                                 @RequestParam(value = "timestamp", required = false) String timestamp,
                                 @RequestParam(value = "nonce", required = false) String nonce,
                                 @RequestParam(value = "echostr", required = false) String echostr) {
              try {
                  //首先先进行判断参数是否为null
                  log.info("微信公众号验签信息{}开始 [{}, {}, {}, {}]", appid, signature, timestamp, nonce, echostr);
                  if (StrUtil.isAllBlank(signature, timestamp, nonce, echostr)) {
                      log.error("微信验证签名参数非法为空");
                  }
                  System.out.println(echostr);
                  return echostr;
              } catch (Exception e) {
                  log.error("微信验证签名异常{} [{}{}{}{}]", appid, signature, timestamp, nonce, echostr);
                  return null;
              }
    2. 自己也可以使用测试工具如apifox,查看返回的数据是否为不带双引号的数据微信公众平台配置提示“token验证失败”(几乎全部踩坑贴,SpringBoot返回字符串,多双引号),第2张
  3. 然后是我个人的错误解决,本人配置了WebMvcConfiguer导致返回的Json之类的格式修改加上了双引号所以就出现问题。个人是暂时先不用这个配置,不过网上也有对应的修改如:
    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
        @Bean
        public StringHttpMessageConverter stringHttpMessageConverter() {
            return new StringHttpMessageConverter();
        }
        @Override
        public void configureMessageConverters(List> converters) {
            converters.add(stringHttpMessageConverter());
        }
    }
  4. 附上官方及其他解决贴:​​​​​​https://bbs.csdn.net/topics/390991193
    公众号接入-填写服务器配置-token验证失败? | 微信开放社区