微信小程序获取openid unionid Springboot Java
微信小程序获取openid unionid Springboot Java
Controller
@RequestMapping("vx")
public String vxLogin(String code,String encryptedData,String iv) {
val jsonObject = VXUtil.decryptCode(code);
val openid = jsonObject.getString("openid");
val sessionKey = jsonObject.getString("session_key");
String decrypt = VXUtil.decrypt(sessionKey, iv, encryptedData);
JSONObject object = new JSONObject(decrypt);
System.out.println("object = " + object);
return null;
}
VXUtil
public static JSONObject decryptCode(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid={1}&secret={2}&js_code={3}&grant_type={4}";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(url,
String.class,
VXConfig.APP_ID,
VXConfig.SECRET,
code,
VXConfig.GRANT_TYPE);
//解析从微信服务器上获取到的json字符串
return new JSONObject(result);
}
public static String decrypt(String sessionKey, String iv, String encryptData) {
String decryptString = "";
init();
byte[] sessionKeyByte = Base64.decodeBase64(sessionKey);
byte[] ivByte = Base64.decodeBase64(iv);
byte[] encryptDataByte = Base64.decodeBase64(encryptData);
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
Key key = new SecretKeySpec(sessionKeyByte, "AES");
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance("AES");
algorithmParameters.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, key, algorithmParameters);
byte[] bytes = cipher.doFinal(encryptDataByte);
decryptString = new String(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return decryptString;
}
private static boolean hasInited = false;
public static void init() {
if (hasInited) {
return;
}
Security.addProvider(new BouncyCastleProvider());
hasInited = true;
}
WXConfig
public interface VXConfig {
/**
* 在后台
*/
String APP_ID = "wxcbe411f898llllllll";
/**
* 在后台
*/
String SECRET = "b12a7e212a2383lllllllllllllllllll";
/**
* 固定
*/
String GRANT_TYPE = "authorization_code";
}
依赖:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<!--编码-->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
app.js
//app.js
App({
onLaunch: function() {
try {
let res = wx.getStorageInfoSync()
if (res[\'teacher\']) {
return
}
} catch (e) {
// Do something when catch error
}
let that = this
wx.getSetting({
success(res) {
if (res.authSetting[\'scope.userInfo\']) {
that.login()
} else {
wx.redirectTo({
url: \'/pages/info/getUserInfo\',
})
}
}
})
},
login() {
let that = this
// 登录
wx.login({
success(r) {
wx.getUserInfo({
withCredentials:true,
success(res) {
console.log(res)
that.global.userInfo = res.userInfo
wx.request({
url: that.global.host + \'/login/vx\',
data: {
encryptedData: res.encryptedData,
iv: res.iv,
code: r.code
},
success(res) {
console.log(res)
}
})
}
})
}
})
},
global: {
userInfo: null,
host: "http://192.168.1.4"
}
})
请发表评论