用戶授權登陸並獲取用戶的數據,
小程序可以通過微信官方提供的登錄能力方便地獲取微信提供的用戶身份標識,快速建立小程序內的用戶體系。
官方API給出的是這樣的
https://developers.weixin.qq.com/miniprogram/dev/api/signature.html
說明:
小程序調用wx.login() 獲取 臨時登錄憑證code ,並回傳到開發者服務器。
開發者服務器以code換取 用戶唯一標識openid 和 會話密鑰session_key。
之后開發者服務器可以根據用戶標識來生成自定義登錄態,用於后續業務邏輯中前后端交互時識別用戶身份。
具體API里說的很清楚了,下面直接上代碼,具體用到什么會直接上鏈接
具體流程(可直接看3)
1、(客戶端 JS部分)微信小程序客戶端調用接口wx.login() 獲取臨時登錄憑證(code)
//1、調用微信登錄接口,獲取code wx.login({ success: function (r) { var code = r.code;//登錄憑證 if (code) { //2、調用獲取用戶信息接口 //... } else { console.log('獲取用戶登錄態失敗!' + r.errMsg) } }, fail: function () { callback(false) } })
2、(客戶端 JS部分)微信小程序客戶端校驗用戶當前session_key是否有效,調用 wx.getUserInfo()接口獲取 用戶基本信息、encryptedData(用戶敏感信息加密數據) 和 iv(加密算法的初始向量 )
//1、調用微信登錄接口,獲取code wx.login({ success: function (r) { var code = r.code;//登錄憑證 if (code) { //2、調用獲取用戶信息接口 wx.getUserInfo({ success: function (res) { console.log({encryptedData: res.encryptedData, iv: res.iv, code: code}) //3.解密用戶信息 獲取unionId //... }, fail: function () { console.log('獲取用戶信息失敗') } }) } else { console.log('獲取用戶登錄態失敗!' + r.errMsg) } }, fail: function () { callback(false) } })
3、(客戶端 JS部分/WXML部分)將前面獲取到的 code 、encryptedData、iv發送到自己的服務器(開發者服務器),通過自己的服務器(開發者服務器)解密獲取信息
<!--wxml--> <!-- 如果只是展示用戶頭像昵稱,可以使用 <open-data /> 組件 --> <open-data type="userAvatarUrl"></open-data> <open-data type="userNickName"></open-data> <!-- 需要使用 button 來授權登錄 --> <button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授權登錄</button> <view wx:else>請升級微信版本</view>
//js Page({ data: { canIUse: wx.canIUse('button.open-type.getUserInfo') }, onLoad: function() { // 查看是否授權 wx.getSetting({ success: function(res){ if (res.authSetting['scope.userInfo']) { // 已經授權,可以直接調用 getUserInfo 獲取頭像昵稱 wx.getUserInfo({ success: function(res) { console(res.userInfo) } }) } } }) }, bindGetUserInfo: function (event) { console.log(event.detail.userInfo) //使用 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已經授權,可以直接調用 getUserInfo 獲取頭像昵稱,不會彈框 wx.login({ success: function (res) { var code = res.code;//登錄憑證 if (code) { //2、調用獲取用戶信息接口 wx.getUserInfo({ success: function (res) { console.log({ encryptedData: res.encryptedData, iv: res.iv, code: code }) //3.請求自己的服務器,解密用戶信息 獲取unionId等加密信息 wx.request({ url: 'https://xxxx.com/wxsp/decodeUserInfo',//自己的服務接口地址 method: 'post', header: { 'content-type': 'application/x-www-form-urlencoded' }, data: { encryptedData: res.encryptedData, iv: res.iv, code: code }, success: function (data) { //4.解密成功后 獲取自己服務器返回的結果 if (data.data.status == 1) { var userInfo_ = data.data.userInfo; console.log(userInfo_) } else { console.log('解密失敗') } }, fail: function () { console.log('系統錯誤') } }) }, fail: function () { console.log('獲取用戶信息失敗') } }) } else { console.log('獲取用戶登錄態失敗!' + r.errMsg) } }, fail: function () { console.log('登陸失敗') } }) } else { console.log('獲取用戶信息失敗') } } }) } })
4、(服務端 java部分)自己的服務器發送code到微信服務器獲取openid(用戶唯一標識)和session_key(會話密鑰),最后將encryptedData、iv、session_key通過AES解密獲取到用戶敏感數據 (整段復制即可無需修改)
解密這里官方也給出了參照示例API,微信官方提供了多種編程語言的示例代碼(點擊下載)。每種語言類型的接口名字均一致。調用方式可以參照示例。但沒有JAVA的,
a、獲取秘鑰並處理解密的controller(這里用的是springMVC)
/** * @Title: decodeUserInfo * @author:lizheng * @date:2018年3月25日 * @Description: 解密用戶敏感數據 * @param encryptedData 明文,加密數據 * @param iv 加密算法的初始向量 * @param code 用戶允許登錄后,回調內容會帶上 code(有效期五分鍾),開發者需要將 code 發送到開發者服務器后台,使用code 換取 session_key api,將 code 換成 openid 和 session_key * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/decodeUserInfo", method = RequestMethod.POST) @ResponseBody 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; } // 小程序唯一標識 (在微信小程序管理后台獲取) String wxspAppid = "wx18385lalalala"; // 小程序的 app secret (在微信小程序管理后台獲取) String wxspSecret = "bef47459d81a6eflalalalala"; // 授權(必填) 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 = new JSONObject(sr); // 獲取會話密鑰(session_key) String session_key = json.get("session_key").toString(); // 用戶的唯一標識(openid) String openid = (String) json.get("openid"); //////////////// 2、對encryptedData加密數據進行AES解密 //////////////// try { String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8"); if (null != result && result.length() > 0) { map.put("status", 1); map.put("msg", "解密成功"); JSONObject userInfoJSON = new JSONObject(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")); // 解密unionId & openId; userInfo.put("unionId", userInfoJSON.get("unionId")); map.put("userInfo", userInfo); } else { map.put("status", 0); map.put("msg", "解密失敗"); } } catch (Exception e) { e.printStackTrace(); } return map; }
解密第二種方法:
pom引入依賴:
<!--微信小程序進行解密加密的用戶信息 --> <dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-core</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk16</artifactId> <version>1.46</version> </dependency>
解密代碼:
import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; import com.alibaba.fastjson.JSONObject; 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; private String decryptNew(String encryptedData, String sessionKey, String iv) throws Exception { String result = ""; // 被加密的數據 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", "BC"); 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) { result = new String(resultByte, "UTF-8"); } } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); } catch (NoSuchPaddingException e) { LOGGER.error(e.getMessage(), e); } catch (InvalidParameterSpecException e) { LOGGER.error(e.getMessage(), e); } catch (IllegalBlockSizeException e) { LOGGER.error(e.getMessage(), e); } catch (BadPaddingException e) { LOGGER.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { LOGGER.error(e.getMessage(), e); } catch (InvalidKeyException e) { LOGGER.error(e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { LOGGER.error(e.getMessage(), e); } catch (NoSuchProviderException e) { LOGGER.error(e.getMessage(), e); } return result; }
添加兩個工具類:
b、AesCbcUtil.java 工具類 (整段復制即可無需修改)
package com.yfs.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; /** * Created by yfs on 2018/3/25. * <p> * AES-128-CBC 加密方式 * 注: * AES-128-CBC可以自己定義“密鑰”和“偏移量“。 * AES-128是jdk自動生成的“密鑰”。 */ public class AesCbcUtil { 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 { // initialize(); //被加密的數據 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; } }
c、HttpRequest.java 工具類 (整段復制即可無需修改)
package com.yfs.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 { public static void main(String[] args) { //發送 GET 請求 String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", ""); System.out.println(s); // //發送 POST 請求 // String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", ""); // JSONObject json = JSONObject.fromObject(sr); // System.out.println(json.get("data")); } /** * 向指定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; } }
備注
代碼中需要用到的jar包,請自行下載並添加到項目中。
這里需要注意的是,AES解密的時候需要用到javax.crypto.*包的類,在jdk的 jce.jar中提供,是jdk自帶的庫。如果是MAVEN項目,則需要在pom.xml文件中配置指定編譯路徑jce.jar