微信小程序API文檔:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html
openId : 用戶在當前小程序的唯一標識 unionid:用戶的唯一標識,當你綁定多個公眾號或者微信時,這是唯一的,
但是有這個參數的前提是,你綁定了
微信開放平台
一下是官方的流程
也許這個看起來有點懵懂,看代碼
微信客戶端的代碼實現是這樣的
- wx.login({
- success: function (r) {
- if (r.code) {
- var code = r.code;//登錄憑證
- if (code) {
- //2、調用獲取用戶信息接口
- wx.getUserInfo({
- success: function (res) {
- //發起網絡請求
- wx.request({
- url: that.data.net + '/decodeUser.json',
- header: {
- "content-type": "application/x-www-form-urlencoded"
- },
- method: "POST",
- data: {
- encryptedData: res.encryptedData,
- iv: res.iv,
- code: code
- },
- success: function (result) {
- // wx.setStorage({
- // key: 'openid',
- // data: res.data.openid,
- // })
- console.log(result)
- }
- })
- },
- fail: function () {
- console.log('獲取用戶信息失敗')
- }
- })
- } else {
- console.log('獲取用戶登錄態失敗!' + r.errMsg)
- }
- } else {
- }
- }
- })
小程序端獲取用戶信息的順序很重要,先獲取到code,再去獲取用戶信息,否則會偶爾出現這個問題:pad block corrupted,密鑰不對的錯誤,
下面的是java的controller類了,
- public Map<String,String> decodeUserInfo(HttpServletResponse response,String encryptedData, String iv, String code) {
- System.out.println("encryptedData: " + encryptedData);
- System.out.println("iv: " + iv);
- System.out.println("code: " + code);
- Map<String,String> map = new HashMap<>();
- // 小程序唯一標識 (在微信小程序管理后台獲取)
- String wxspAppid = WxBasicMsg.appIdX;
- // 小程序的 app secret (在微信小程序管理后台獲取)
- String wxspSecret = WxBasicMsg.appSecretX;
- // 授權(必填)
- 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.fromObject(sr);
- // 獲取會話密鑰(session_key)
- String session_key = json.getString("session_key");
- System.out.println("session_key: "+session_key);
- // 用戶的唯一標識(openid)
- String openid = json.getString("openid");
- map.put("openid", openid);
- // 2、對encryptedData加密數據進行AES解密
- String status = null;
- try {
- String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
- PrintWriter out = response.getWriter();
- if (null != result && result.length() > 0) {
- response.setCharacterEncoding("utf-8");
- JSONObject userInfoJSON = JSONObject.fromObject(result);
- map.put("unionid", userInfoJSON.getString("unionId"));
- status = "1";
- boolean flag = false;
- FchlUser user = new FchlUser();
- user.setUserOpenid(map.get("openid"));
- user.setUserUnionid(map.get("unionid"));
- //查詢用戶是否保存
- queryAndinsert(map, flag, user);
- }else{
- map.put("openid", "");
- status = "0";
- }
- map.put("status", status);
- out.print(JSONObject.fromObject(map));
- System.out.println("給前端的map:" +map.toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
還有解密的方法:
- public static String decrypt(String encryptedData, String sessionKey, String iv, String encodingFormat)
- throws Exception {
- // 被加密的數據
- byte[] dataByte = Base64.decode(encryptedData);
- // 加密秘鑰
- byte[] keyByte = Base64.decode(sessionKey);
- // 偏移量
- byte[] ivByte = Base64.decode(iv);
- try {
- // 如果密鑰不足16位,那么就補足. 這個if 中的內容很重要
- int base = 16;
- if (keyByte.length % base != 0) {
- int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
- byte[] temp = new byte[groups * base];
- Arrays.fill(temp, (byte) 0);
- System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
- keyByte = temp;
- }
- // 初始化
- Security.addProvider(new BouncyCastleProvider());
- 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, "UTF-8");
- return JSONObject.fromObject(result).toString();
- }
以及http工具類:
- 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;
- }
關於小程序解密的基本上就這些了,希望能幫到各位
