小程序请求后端java接口两种code之间的差别

178 阅读1分钟

记录一下最近项目开发过程中的问题: 小程序调用后端接口获取用户openid的时候,需要传递code值,但是前端获取的code直接传递成了获取用户手机号码的code,这就导致后端解析的时候出现了解析错误,code无效等返回信息,下面我将附上开发过程中的部分代码,根据实际情况进行使用。 1.项目中导入小程序开发的maven依赖(注意,尽量使用高版本,不然在调用过程中,可能找不到封装的方法)

<!--微信小程序-->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-miniapp</artifactId>
    <version>4.5.0</version>
</dependency>

2.配置yml文件,也就是小程序相关的appid和秘钥,这两个东西都可以在小程序管理平台找到的这里就不再明确说明

 wx:
     applet:
         appid: xxxxxxxxxxxxxxxxxx
         secret: XXXXXXXXXXXXXX

3.编写代码

    public void wechatSession(String code) {
    try {
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        UserSessionResult userSessionResult = new UserSessionResult(sessionInfo.getSessionKey(), sessionInfo.getOpenid(), sessionInfo.getUnionid());
        log.info(userSessionResult);
    } catch (WxErrorException e) {
        log.error("获取用户openId出错:{}",e.getMessage());
    }
}