在小程序的项目中,对小程序授权获取的code值进行解析是一个必要的操作,因为需要获取到其中的openid、session_key、unionid进行一个身份的验证。判断该用户是新用户或是其它操作(具体根据自己的业务需求修改就行)。
其中unionid需要主体账户绑定了小程序后才可以获取到。所以在没有绑定的时候,我们解析code是只能获取到openid和session_key两个参数的。
在微信小程序的官方开发文档中,对wx.getUserProfile 接口 和 wx.getUserInfo 接口 做出了说明,详细可见“微信官方文档说明”
下面来详细看一下Java通过微信小程序的code获取openid、session_key、unionid的详细代码:
1.pom.xml
<!--微信公众平台-->
<!-- 微信框架 参考:https://github.com/Wechat-Group/weixin-java-tools -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.8.0</version>
</dependency>
2.Java代码
System.out.println("code参数:"+pram.getCode());
Map<String, Object> map=new HashMap<>();
String url = "https://api.weixin.qq.com/sns/jscode2session" +
"?appid=" + APPID +// appId更换成自己的appid
"&secret=" + APPSECRET +// appSecret 更换成自己的appSecret
"&js_code=" + pram.getCode() +
"&grant_type=authorization_code";
String result_url="";
try {
result_url = HttpUtil.doGet(url);
}catch (Exception e){
throw new BaseErrorException(BaseErrorCode.DO_ERROR, "后台授权失败~");
}
//System.out.println("请求获取access_token:" + result_url);
//返回结果的json对象
JSONObject resultObject = JSON.parseObject(result_url);
byte[] resultByte;
String userString;
JSONObject userJson;
String openID;
try{
//这是老方法,通过 wx.getUserProfile或者wx.getUserInfo
resultByte= AESTools.decrypt(Base64.decodeBase64(pram.getEncryptedData()),
Base64.decodeBase64(resultObject.getString("session_key")),
Base64.decodeBase64(pram.getIv()));
userString=new String(resultByte, "UTF-8");
//System.out.println("user: "+userString);
userJson= JSON.parseObject(userString);
//这是老方法,通过 wx.getUserProfile或者wx.getUserInfo
//wx.login 高版本的获取到的就能为默认的头像和“微信用户”这样的昵称了
openID=resultObject.getString("openid");
}catch (Exception e){
throw new BaseErrorException(BaseErrorCode.DO_ERROR, "后台授权失败~请重新打开小程序");
}
微信后期做了版本升级之后,将会获取不到授权用户的头像和昵称了
详细可见官方文档!