微信小程序獲取用戶手機號碼的詳細步驟
前言
我們在做小程序開發(fā)的過程中,經(jīng)常會涉及到用戶身份的問題,最普遍的就是我們要獲取用戶的手機號碼,通過微信獲取手機號碼后可以減少很多操作,比如用戶手機號碼驗證等,我們還可以給用戶發(fā)送提示短信,那么本文主要講解如何獲取用戶手機號碼。
獲取用戶手機號碼 分為以下幾步:
第一點擊頁面獲取授權按鈕
第二獲取用戶授權參數(shù)
第三根據(jù)加解密算法解密手機號碼
接下來我們來實現(xiàn)以上三步
先看前端頁面
<!--index.wxml--> <view class="container"> <view > <button class="authbtn" type="primary" open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="getUserProfile" bindtap="getUserProfile">獲取用戶信息</button> <button class="authbtn" open-type="getPhoneNumber" type="primary" bindgetphonenumber="onGetPhoneNumber">獲取手機號碼</button> <view class="userinfo"> <block> <view class="userinfo-avatar" bindtap="bindViewTap"> <image class="userinfo-avatar" type="userAvatarUrl" src="{{userInfo.avatarUrl}}" mode="cover" ></image> </view> <Text class="userinfo-nickname" >{{userInfo.nickName}}</Text> <text class="userinfo-phone" >{{userInfo.phone}}</text> <text class="userinfo-phone" wx:if="{{userInfo.gender==0}}">男</text> <text class="userinfo-phone" wx:if="{{userInfo.gender==1}}">女</text> <picker bindchange="bindPickerLingyuChange" value="{{index}}" range="{{array}}"> <view wx:if="{{showLingyu==true}}" class="tips">選擇職業(yè) </view> <text class="tips"> {{array[index]}}</text> </picker> <picker bindchange="bindPickerAearaChange" value="{{i}}" range="{{items}}" range-key="name"> <view wx:if="{{showAeara==true}}"class="tips">選擇地區(qū) </view> <text class="tips">{{items[i].name}}</text> </picker> <button class="authbtn" type="primary" bindtap="bindViewTap">注冊</button> </block> </view> </view> </view>
大概長這樣
獲取用戶頭像的我就直接略過了,網(wǎng)上資料也比較多
接下來我們看關鍵代碼
此處定義
getPhoneNumber是微信官方要求,獲取用戶手機號碼授權
onGetPhoneNumber是回調函數(shù),獲取授權后會回調到該方法,也就是獲取的電話號碼就在這個函數(shù)的返回值里面。當然這個函數(shù)是自定義的,名字大家可以隨便起,上面的getPhoneNumber可不能隨便修改。
接下來我們通過服務器獲取授權
上代碼:這里是js調用我們自己的后臺,我們的后臺再調用微信服務端
onGetPhoneNumber(e) { var that = this; wx.login({ success (res) { if (res.code) { console.log('步驟2獲檢查用戶登錄狀態(tài),獲取用戶電話號碼!', res) wx.request({ url: '這里寫自己的獲取授權的服務器地址', data: {code: res.code}, header: {'content-type': 'application/json'}, success: function(res) { console.log("步驟三獲取授權碼,獲取授權openid,session_key",res); var userphone=res.data.data; wx.setStorageSync('userphoneKey',userphone); //解密手機號 var msg = e.detail.errMsg; var sessionID=wx.getStorageSync("userphoneKey").session_key; var encryptedData=e.detail.encryptedData; var iv=e.detail.iv; if (msg == 'getPhoneNumber:ok') {//這里表示獲取授權成功 wx.checkSession({ success:function(){ //這里進行請求服務端解密手機號 that.deciyption(sessionID,encryptedData,iv); }, fail:function(){ // that.userlogin() } }) } },fail:function(res){ console.log("fail",res); } }) } else { console.log('登錄失敗!' + res.errMsg) } } })
后臺調用微信獲取授權碼
下面是我通過自己寫的框架調用的,不用關心注解內容,大家只關注自己的框架注解即可,不管是spring還是servlet只要請求能進到該方法即可,所以重點關注中間部分,把參數(shù)值傳正確即可
/** * 回調微信登錄信息 * @param request * @param response */ @MethodAnnotation(method="miniGetAuth",methoddes="小程序授權",methodWay="ALL") public void miniGetAuth(HttpServletRequest request, HttpServletResponse response) throws Exception{ String url="https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code"; String code= request.getParameter("code"); if(empty(code))return; url=url.replaceAll("APPID", PropertiesUtil.wx_appid) .replaceAll("SECRET", PropertiesUtil.wx_appsecret) .replaceAll("JSCODE", code); qury(request, response, WeixinUtil.doGetStr(url), false, 0); }
下面是工具類方法 WeixinUtil.doGetStr(url)
/** * get請求 * @param url * @return * @throws ParseException * @throws IOException */ public static JSONObject doGetStr(String url) throws ParseException, IOException{ DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); JSONObject jsonObject = null; HttpResponse httpResponse = client.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); if(entity != null){ String result = EntityUtils.toString(entity,"UTF-8"); jsonObject = JSONObject.fromObject(result); } return jsonObject; }
這個值可以返回給前端,前端可以收到如下參數(shù)
接著我們通過授權之后,獲取第三個參數(shù)iv,調用下面方法進行服務端解密
that.deciyption(sessionID,encryptedData,iv);
deciyption(sessionID,encryptedData,iv){ var that = this; console.log("步驟4根據(jù)秘鑰解密手機號碼sessionID:",sessionID); wx.request({ url: '解密地址', data: { sessionID: sessionID, encryptedData:encryptedData, iv: iv }, header: {'content-type': 'application/json'}, success: function(res) { console.log("79",(res.data.code==20001)); if(res.data.code==20001){//這里不用管,可以刪掉,我的框架里返回值20001是授權失敗,可按照自己邏輯處理 console.log("獲取失敗,重新獲取",res); that.setData({ showPhone:true, }) }else{ console.log("line 79", JSON.parse(res.data.data)); var json= JSON.parse(res.data.data); wx.setStorageSync('userphone', JSON.parse(res.data.data).phoneNumber); console.log("步驟5解密成功",res.data.data); that.setData({ showPhone:false, "userInfo.phone":wx.getStorageSync('userphone') }) } },fail:function(res){ console.log("fail",res); } }) }
服務端解密代碼
/** * * @param request * @param response * @throws Exception */ @MethodAnnotation(method="miniGetPhone",methoddes="小程序解密手機號",methodWay="ALL") public void miniGetPhone(HttpServletRequest request, HttpServletResponse response) throws Exception{ String encrypdata= request.getParameter("encryptedData"); String ivdata= request.getParameter("iv"); String sessionkey= request.getParameter("sessionID"); if(empty(encrypdata,ivdata,sessionkey))return; qury(request, response, deciphering(encrypdata, ivdata, sessionkey), false, 0); }
deciphering解密方法
public static String deciphering(String encrypdata,String ivdata, String sessionkey) { byte[] encrypData = Base64.decode(encrypdata); 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(); } return str; } public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception { AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); return new String(cipher.doFinal(encData),"UTF-8"); }
最終效果
總結
到此這篇關于微信小程序獲取用戶手機號碼的文章就介紹到這了,更多相關微信小程序獲取用戶手機號碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript數(shù)據(jù)結構與算法之二叉樹實現(xiàn)查找最小值、最大值、給定值算法示例
這篇文章主要介紹了JavaScript數(shù)據(jù)結構與算法之二叉樹實現(xiàn)查找最小值、最大值、給定值算法,涉及javascript二叉樹定義、賦值、遍歷、查找等相關操作技巧,需要的朋友可以參考下2019-03-03深入理解JavaScript系列(31):設計模式之代理模式詳解
這篇文章主要介紹了深入理解JavaScript系列(31):設計模式之代理模式詳解,代理模式使得代理對象控制具體對象的引用,代理幾乎可以是任何對象:文件,資源,內存中的對象,或者是一些難以復制的東西,需要的朋友可以參考下2015-03-03微信小程序 子級頁面返回父級并把子級參數(shù)帶回父級實現(xiàn)方法
這篇文章主要介紹了微信小程序 子級頁面返回父級并把子級參數(shù)帶回父級實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08ionic2自定義cordova插件開發(fā)以及使用(Android)
這篇文章主要為大家詳細介紹了ionic2自定義cordova插件開發(fā)以及使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06JS控件bootstrap suggest plugin使用方法詳解
這篇文章主要介紹了JS控件bootstrap suggest plugin的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03