一.jar包准備
1.在網盤下載
鏈接:https://pan.baidu.com/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文件中添加依賴
<!-- 微信小程序要添加的依賴 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.55</version>
</dependency>
<!-- 本地導入到maven中jar -->
<dependency>
<groupId>fastjson-1.2.47</groupId><!-- 參數2-->
<artifactId>fastjson-1.2.47</artifactId><!-- 參數3-->
<version>1.2.47</version><!-- 參數4-->
</dependency>
<dependency>
<groupId>commons-codec-1.9</groupId>
<artifactId>commons-codec-1.9</artifactId>
<version>1.9</version>
</dependency>
三.添加工具類
1.AesUtil類

package com.briup.apps.app01.util; 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; } }
2.HttpRequest類

package com.briup.apps.app01.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HttpRequest { /** * 向指定URL發送GET方法的請求 * * @param url * 發送請求的URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return URL 所代表遠程資源的響應結果 */ 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())); 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; } /** * 向指定 URL 發送POST方法的請求 * * @param url * 發送請求的 URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return 所代表遠程資源的響應結果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(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 = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader( new InputStreamReader(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(); } } return result; } }
四.后台接口

package com.briup.apps.app01.web.controller; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; import com.briup.apps.app01.util.AesUtil; import com.briup.apps.app01.util.HttpRequest; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/wx") public class TestController { @ApiOperation("獲取微信小程序的openid") @ResponseBody @RequestMapping(value = "/getOpenid", method = RequestMethod.GET) public Map getOpenid(String code, String encryptedData, String iv ) throws Exception{ Map<String,Object> map = new HashMap<String,Object>(); //code = "081ZExyD0qnP4j2LV5yD0hFLyD0ZExyK"; //登錄憑證不能為空 if (code == null || code.length() == 0) { map.put("status", 0); map.put("msg", "code 不能為空"); System.out.println("map1:" + map); return map; } //小程序唯一標識 (在微信小程序管理后台獲取) 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.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"); 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<String,Object> userInfo = new HashMap<String,Object>(); 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); return map; } } catch (Exception e) { e.printStackTrace(); } map.put("status", 0); map.put("msg", "解密失敗"); System.out.println("map3:" + map); return map; } }
五.小程序代碼

// 登錄 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); } }) } }) } } }) } } })