一.jar包准备
1.在网盘下载
链接:/s/15HAAWOg_yn768g4s9IrcPg
提取码:hgj0
二.在pom文件中添加依赖
1.将外部的引入的包放到本地仓库(本地测试可以不用添加,后期打包需要用到检测pom文件的依赖)
1).使用cmd进入maven安装目录下的bin
运行命令的参数说明(红字部分)
mvn install:install-file -Dfile="本地jar包的位置(参数1)" -DgroupId=gruopId中的内容(参数2) -DartifactId=actifactId的内容(参数3) -Dversion=version的内容(参数4) -Dpackaging=jar
2.在pom文件中添加依赖
org.bouncycastle
bcprov-jdk15on
1.55
fastjson-1.2.47
fastjson-1.2.47
1.2.47
commons-codec-1.9
commons-codec-1.9
1.9
三.添加工具类
1.AesUtil类
packagecom.briup.apps.app01.util;mons.codec.binary.Base64;importorg.bouncycastle.jce.provider.BouncyCastleProvider;importjavax.crypto.BadPaddingException;importjavax.crypto.Cipher;importjavax.crypto.IllegalBlockSizeException;importjavax.crypto.NoSuchPaddingException;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importjava.io.UnsupportedEncodingException;import java.security.*;importjava.security.spec.InvalidParameterSpecException;public classAesUtil {static{//BouncyCastle是一个开源的加解密解决方案,主页在/
Security.addProvider(newBouncyCastleProvider());
}/*** AES解密
*
*@paramdata //密文,被加密的数据
*@paramkey //秘钥
*@paramiv //偏移量
*@paramencodingFormat //解密后的结果需要进行的编码
*@return*@throwsException*/
public static String decrypt(String data, String key, String iv, String encodingFormat) throwsException {//被加密的数据
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(newIvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);//初始化
byte[] resultByte =cipher.doFinal(dataByte);if (null != resultByte && resultByte.length > 0) {
String result= newString(resultByte, encodingFormat);returnresult;
}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;
}
}
View Code
2.HttpRequest类
packagecom.briup.apps.app01.util;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;.URL;.URLConnection;importjava.util.List;importjava.util.Map;public classHttpRequest {/*** 向指定URL发送GET方法的请求
*
*@paramurl
* 发送请求的URL
*@paramparam
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
*@returnURL 所代表远程资源的响应结果*/
public staticString sendGet(String url, String param) {
String result= "";
BufferedReader in= null;try{
String urlNameString= url + "?" +param;
URL realUrl= newURL(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> map =connection.getHeaderFields();//遍历所有的响应头字段
for(String key : map.keySet()) {
System.out.println(key+ "--->" +map.get(key));
}//定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(newInputStreamReader(
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();
}
}returnresult;
}/*** 向指定 URL 发送POST方法的请求
*
*@paramurl
* 发送请求的 URL
*@paramparam
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
*@return所代表远程资源的响应结果*/
public staticString sendPost(String url, String param) {
PrintWriter out= null;
BufferedReader in= null;
String result= "";try{
URL realUrl= newURL(url);//打开和URL之间的连接
URLConnection conn =realUrl.openConnection();//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);//获取URLConnection对象对应的输出流
out = newPrintWriter(conn.getOutputStream());//发送请求参数
out.print(param);//flush输出流的缓冲
out.flush();//定义BufferedReader输入流来读取URL的响应
in = newBufferedReader(newInputStreamReader(conn.getInputStream()));
String line;while ((line = in.readLine()) != null) {
result+=line;
}
}catch(Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}//使用finally块来关闭输出流、输入流
finally{try{if(out!=null){
out.close();
}if(in!=null){
in.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
}returnresult;
}
}
View Code
四.后台接口
packagecom.briup.apps.app01.web.controller;importjava.util.HashMap;importjava.util.Map;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.bind.annotation.RestController;importcom.alibaba.fastjson.JSONObject;importcom.briup.apps.app01.util.AesUtil;importcom.briup.apps.app01.util.HttpRequest;importio.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/wx")public classTestController {
@ApiOperation("获取微信小程序的openid")
@ResponseBody
@RequestMapping(value= "/getOpenid", method =RequestMethod.GET)public Map getOpenid(String code, String encryptedData, String iv ) throwsException{
Map map = new HashMap();//code = "081ZExyD0qnP4j2LV5yD0hFLyD0ZExyK";//登录凭证不能为空
if (code == null || code.length() == 0) {
map.put("status", 0);
map.put("msg", "code 不能为空");
System.out.println("map1:" +map);returnmap;
}//小程序唯一标识 (在微信小程序管理后台获取)
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 = HttpRequest.sendGet("https://api./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");
System.out.println("openid:" +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);
System.out.println("map2:" +map);returnmap;
}
}catch(Exception e) {
e.printStackTrace();
}
map.put("status", 0);
map.put("msg", "解密失败");
System.out.println("map3:" +map);returnmap;
}
}
View Code
五.小程序代码
//登录
wx.login({
success: res=>{//发送 res.code 到后台换取 openId, sessionKey, unionId
if(res.code) {var code =res.code;
console.log(res.code);//获取用户信息
wx.getSetting({
success: ures=>{if (ures.authSetting['scope.userInfo']) {//已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: ures2=>{//可以将 ures2 发送给后台解码出 unionId
this.globalData.userInfo =ures2.userInfo;
console.log("获取到的用户数据:");
console.log(ures2)
JSON.stringify(ures2)//由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
//所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {this.userInfoReadyCallback(ures2)
}
wx.request({
url: getApp().globalData.urlPath+ "wx/getOpenid",
data: {
code: code,
encryptedData: ures2.encryptedData,
iv: ures2.iv
},
method:"Get",
header: {'content-type': 'application/x-www-form-urlencoded',
},
success:function(res) {
console.log("登录返回的数据:");
console.log(res);
},
fail:function(error) {
console.log(error);
}
})
}
})
}
}
})
}
}
})
View Code