首先一个条件是 公众平台要和开放平台相互关联,否则是获取不到unionid的
前台代码
// 登录
//首次登录时,将code传入后台,获取openid,并且在授权后放入缓存中
wx.login({
success: res => {
console.log("授权页面里的登录参数:")
console.log(res)
// 发送 res.code 到后台换取 openId, sessionKey, unionId
// request({
// 'url':'http://localhost:8080/test1',
// 'data':{
// code:res.code
// }
// }).then(
// (res)=>{
// console.log('哈哈哈哈哈')
// console.log(res);
// }
// )
console.log("code")
console.log(res.code)
wx.request({
url: 'http://localhost:8080/test',
method:'post',
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认值
},
data: {
code: res.code,
encryptedData: e.detail.encryptedData,
iv: e.detail.iv
},success:function(res2){
console.log("res2")
console.log(res2)
}
})
// wx.request({
// url: 'http://localhost:8080/test1?code='+res.code,
// method:'get',
// success:(res1)=>{
// console.log(res1)
// }
// })
//app.globalData.openid="test"
//console.log(app.globalData.openid)
}
})
后台代码
解密工具类
package io.matching.modules.h5.controller;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
public class AesUtil {
static {
//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
Security.addProvider(new BouncyCastleProvider());
}
/**
* AES解密
*
* @param data //密文,被加密的数据
* @param key //秘钥
* @param iv //偏移量
* @param encodingFormat //解密后的结果需要进行的编码
* @return
* @throws Exception
*/
public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
//被加密的数据
byte[] dataByte = Base64.decodeBase64(data);
//加密秘钥
byte[] keyByte = Base64.decodeBase64(key);
//偏移量
byte[] ivByte = Base64.decodeBase64(iv);
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, encodingFormat);
return result;
}
return null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
接口代码
package io.matching.modules.h5.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* @program: matching-security
* @description:
* @author: zhangshulong
* @create: 2020-04-23 20:54
**/
@RestController
public class TestController {
@RequestMapping("/test")
public Map decodeUserInfo(String encryptedData, String iv, String code) {
Map map = new HashMap();
//登录凭证不能为空
if (code == null || code.length() == 0) {
map.put("status", 0);
map.put("msg", "code 不能为空");
return map;
}
//todo 填写你自己的信息
//你自己的appid
String wxspAppid = "";
//小程序的 app secret (在微信小程序管理后台获取)
String wxspSecret = "";
//授权(必填)
String grant_type = "authorization_code";
1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
//请求参数
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
//发送请求
String sr = sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
//解析相应内容(转换成json对象)
JSONObject json = JSONObject.parseObject(sr);
//获取会话密钥(session_key)
String session_key = json.get("session_key").toString();
//用户的唯一标识(openid)
String openid = (String) json.get("openid");
2、对encryptedData加密数据进行AES解密
try {
String result = AesUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
if (null != result && result.length() > 0) {
map.put("status", 1);
map.put("msg", "解密成功");
JSONObject userInfoJSON = JSONObject.parseObject(result);
Map userInfo = new HashMap();
userInfo.put("openId", userInfoJSON.get("openId"));
userInfo.put("nickName", userInfoJSON.get("nickName"));
userInfo.put("gender", userInfoJSON.get("gender"));
userInfo.put("city", userInfoJSON.get("city"));
userInfo.put("province", userInfoJSON.get("province"));
userInfo.put("country", userInfoJSON.get("country"));
userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
userInfo.put("unionId", userInfoJSON.get("unionId"));
map.put("userInfo", userInfo);
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
map.put("status", 0);
map.put("msg", "解密失败");
return map;
}
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
// in = new BufferedReader(new
// InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
@RequestMapping("/test1")
public JSONObject test1(String code){
String jsonId=getopenid("wx2f92050c7deb49ba",code,"f488eb8c6a8a16ca577c47b94d153cb8");
JSONObject jsonObject=JSONObject.parseObject(jsonId);
// JSONObject jsonObject = JSONObject.fromObject(jsonId);
return jsonObject;
}
public String getopenid(String appid,String code,String secret) {
BufferedReader in = null;
//appid和secret是开发者分别是小程序ID和小程序密钥,开发者通过微信公众平台-》设置-》开发设置就可以直接获取,
String url="https://api.weixin.qq.com/sns/jscode2session?appid="
+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
try {
URL weChatUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = weChatUrl.openConnection();
// 设置通用的请求属性
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e1) {
throw new RuntimeException(e1);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
另外需要引入依赖
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.52</version> </dependency>