微信小程式使用者授權獲取手機號(getPhoneNumber)
阿新 • • 發佈:2021-03-15
前言
小程式有一個獲取使用者很便捷的api,就是通過getPhoneNumber獲取使用者的已經繫結微信的手機號碼。有一點要大家注意,現在微信和注重使用者體驗,有些方法都是需要使用者主動去觸發才能呼叫的,比如getPhoneNumber。
實現思路:
1、通過wx.login獲取code,從而獲取到使用者的openID和sessionKey
2、通過getPhoneNumber獲取encryptedData,iv
3、通過引數【encryptedData】、【iv】 、【sessionKey】 請求後臺解密獲取使用者手機號
直接上乾貨:
1、使用者點選獲取使用者手機號碼按鈕
<button class='pop_btn' plain="true" open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">獲取使用者手機號</button>
2、彈出授權圖片:
3、通過解密獲取手機號碼
直接上程式碼:
wxlogin: function() { //獲取使用者的openID和sessionKey var that = this; wx.login({ //獲取code 使用wx.login得到的登陸憑證,用於換取openid success: (res) = >{ wx.request({ method: "GET",url: 'https://xxxwx/wxlogin.do',data: { code: res.code,appId: "appIdSbcx",appKey: "appKeySbcx" },header: { 'content-type': 'application/json' // 預設值 },success: (res) = >{ console.log(res); that.setData({ 程式設計客棧 sessionKey: res.data.session_key }); } }); } }); } getPhoneNumber: function(e) { //點選獲取手機號碼按鈕 var that = this; wx.checkSession({ success: func程式設計客棧tion() { console.log(e.detail.errMsg) console.log(e.detail.iv) console.log(e.detail.encryptedData) var ency = e.detail.encryptedData; var iv = e.detail.iv; var sessionk = that.data.sessionKey; if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { that.setData({ modalstatus: true }); } else { //同意授權 wx.request({ method: "GET",url: 'https://xxx/wx/deciphering.do',data: { encrypdata: ency,ivdata: iv,sessionkey: sessionk },header: { 'content-type': 'application/json' // 預設值 },success: (res) = >{ console.log("解密成功~~~~~~~將解密的號碼儲存到本地~~~~~~~~"); console.log(res); var phone = res.data.phoneNumber; console.log(phone); },fail: function(res) { console.log("解密失敗~~~~~~~~~~~~~"); console.log(res); } }); } },fail: function() { console.log("session_key 已經失效,需要重新執行登入流程"); that.wxlogin(); //重新登入 } }); }
後臺程式碼:
/** * 解密並且獲取使用者手機號碼 * @param encrypdata * @param ivdata * @param sessionkey * @param request * @return * @throws Exception */ @RequestMapping(value = "deciphering",method = RequestMethod.GET) public @ResponseBody S程式設計客棧tring deciphering(String encrypdata,String ivdata,String sessionkey,HttpServletRequest request) { byte[] encrypData = Base64.decode(encrypdata); www.cppcns.com byte[] ivData = Base64.decode(ivdata); byte[] sessionKey = Base64.decode(sessionkey); String str=""; try { str = decrypt(sessionKey,ivData,encrypData); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(str); return str; } public static String decrypt(byte[] key,byte[] iv,byte[] encData) throws Exception { AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AEwww.cppcns.comS/CBC/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key,"AES"); cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec); //解析解密後的字串 return new String(cipher.doFinal(encData),"UTF-8"); }
總結
到此這篇關於微信小程式使用者授權獲取手機號的文章就介紹到這了,更多相關小程式授權獲取手機號內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!