美文网首页
微信小程序checkSessionKey接口报错87009

微信小程序checkSessionKey接口报错87009

作者: 小罗不吃菜 | 来源:发表于2024-05-16 08:50 被阅读0次

    微信小程序在校验用户登录有效性时会调用他的【检验登录态】接口checkSessionKey
    其中使用时如果报错:"errcode":87009,"errmsg":"invalid signature rid: …………"
    那大概率是 请求中的signature参数有问题,我们可以看一下微信接口文档中对于这个字段的描述:


    image.png

    文档中的意思是使用一个有效的sessionKey给一个空串使用hmac_sha256方式签名,但是实际使用时需要注意,签名生成时是byte[]我们需要将它转为字符串,这里不能用new String的方式来转换,也不能用 Base64.getEncoder().encodeToString方法转换,我们需要将它转化为16进制串:

        public static String hmacSha256Encrypt(String message, String sessionKey) {
            try {
                Mac hmacSha256 = Mac.getInstance("HmacSHA256");
                byte[] encodedKey = sessionKey.getBytes(StandardCharsets.UTF_8);
    
                // 使用字节数组创建SecretKey对象
                SecretKey secretKey = new SecretKeySpec(encodedKey, "HmacSHA256");
                hmacSha256.init(secretKey);
                byte[] digest = hmacSha256.doFinal(message.getBytes());
                StringBuilder sb = new StringBuilder();
                for (byte b : digest) {
                    sb.append(String.format("%02x", b));
                }
                return sb.toString();
            } catch (Exception e) {
                throw CommonErrorCode.SERVER_EXCEPTION.error(e, "hmac加密失败");
            }
        }
    

    这里可以看到,我们最终是使用了十六进制的方式将byte数组转字符串,请求微信,可以正确获得返回信息了。

    相关文章

      网友评论

          本文标题:微信小程序checkSessionKey接口报错87009

          本文链接:https://www.haomeiwen.com/subject/jrxbfjtx.html