问题:单独拿sessionKey和encryptedData、iv三个参数可以正常解析小程序用户报文信息;但在程序运行时却始终提示解密失败;
场景:
使用java语言做微信小程序授权用户登录并存储用户信息;
框架采用是springboot
最终解决方法:
因单独传入main方法执行时是直接字符串赋值;而程序运行时采用传入参数形式;
这里传入参数的方式开始是RequestParam 结果是解析是否;
传入参数更换为RequestBody方式,解析正常;
附上个人代码;
请求controller
@Api(tags = "微信小程序端登录认证接口")
@RestController
@Validated
public class SmmAuthController {
@Autowired
private IAuthService authService;
@ApiOperation("微信小程序登录授权获取用户信息")
@PostMapping("/auth/smm/wx/ma/login")
public ResultModel<MaLoginResult> volunteeSpwWxMaLogin(@ApiIgnore @NotNull(message = "AppId不能为空") @RequestHeader(Constants.HEADER_APPID) Integer appId,
@RequestBody MaLoginRo maLoginRo ){
try {
return ResponseUtil.ok(authService.wxMaLogin(appId, maLoginRo), ResultCode.FAILURE);
} catch (WxErrorException e) {
e.printStackTrace();
throw new BusinessException(ResultCode.FAILURE.getCode(),e.getError().getErrorMsg());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ResponseUtil.failure();
}
}
Service实现代码
/**
* 微信小程序授权获取用户信息完成登录验证
* @param appId 内部应用id
* @param maLoginRo 参数对象
* @return openid和token
* @throws WxErrorException
*/
@Override
public MaLoginResult wxMaLogin(Integer appId, MaLoginRo maLoginRo) throws WxErrorException{
// 这里是我动态配置了微信参数在数据库中,查询根据我内部设置的appid查询对应配置;实际应用可直接将小程序的appid和secret赋值;
WxMpConfig wxMpConfig = wxMpConfigService.getById(appId);
BizExceptionUtil.throwEx(wxMpConfig,ResultCode.APP_NO_MA);
final WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
// 设置微信小程序的appid
config.setAppid(wxMpConfig.getMpAppId());
// 设置微信小程序的app corpSecret
config.setSecret(wxMpConfig.getMpSecret());
WxMaService wxMaService = new WxMaServiceImpl();
wxMaService.setWxMaConfig(config);
WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(maLoginRo.getCode());
String sessionKey = session.getSessionKey();
//解密
WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey,maLoginRo.getEncryptedData(), maLoginRo.getIv());
System.out.println("userInfo");
System.out.println(userInfo);
if(null==userInfo){
BizExceptionUtil.throwEx(ResultCode.USER_NOT_EXIST.getCode(),"授权信息失败!");
}
String openId = userInfo.getOpenId();
User user = userService.saveOrUpdateByWxMaAuth(appId,userInfo);
if(null==user){
BizExceptionUtil.throwEx(ResultCode.USER_NOT_EXIST.getCode(),"授权信息失败!");
}
MaLoginResult loginResult = new MaLoginResult();
loginResult.setAppletOpenid(openId);
return loginResult;
}
传入对象实体
@Data
@ToString(callSuper = true)
@ApiModel("小程序授权返回结果参数")
public class MaLoginRo {
@ApiModelProperty(value = "微信小程序code")
private String code;
@ApiModelProperty("用户加密数据")
private String encryptedData;
@ApiModelProperty("解密偏移量iv")
private String iv;
}
我这里应用的jar及版本
<weixin-java-miniapp.version>3.6.0</weixin-java-miniapp.version>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>${weixin-java-miniapp.version}</version>
</dependency>
解析成功的报文截图
请求示例(postman);
请求方式:post