欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序獲取用戶手機(jī)號(hào)碼的詳細(xì)步驟

 更新時(shí)間:2022年07月10日 15:51:06   作者:無極低碼  
最近改了一個(gè)公司項(xiàng)目,新增加了一個(gè)獲取用戶手機(jī)號(hào)功能,里面用到了關(guān)于獲取用戶信息和用戶手機(jī)號(hào)的功能,下面這篇文章主要給大家介紹了關(guān)于微信小程序獲取用戶手機(jī)號(hào)碼的相關(guān)資料,需要的朋友可以參考下

前言

我們?cè)谧鲂〕绦蜷_發(fā)的過程中,經(jīng)常會(huì)涉及到用戶身份的問題,最普遍的就是我們要獲取用戶的手機(jī)號(hào)碼,通過微信獲取手機(jī)號(hào)碼后可以減少很多操作,比如用戶手機(jī)號(hào)碼驗(yàn)證等,我們還可以給用戶發(fā)送提示短信,那么本文主要講解如何獲取用戶手機(jī)號(hào)碼。

獲取用戶手機(jī)號(hào)碼 分為以下幾步:

第一點(diǎn)擊頁面獲取授權(quán)按鈕

第二獲取用戶授權(quán)參數(shù)

第三根據(jù)加解密算法解密手機(jī)號(hào)碼

接下來我們來實(shí)現(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">獲取手機(jī)號(hào)碼</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">注冊(cè)</button>
      </block>
    </view>
  </view>
</view>

大概長(zhǎng)這樣

獲取用戶頭像的我就直接略過了,網(wǎng)上資料也比較多

接下來我們看關(guān)鍵代碼

 此處定義

 getPhoneNumber是微信官方要求,獲取用戶手機(jī)號(hào)碼授權(quán)

onGetPhoneNumber是回調(diào)函數(shù),獲取授權(quán)后會(huì)回調(diào)到該方法,也就是獲取的電話號(hào)碼就在這個(gè)函數(shù)的返回值里面。當(dāng)然這個(gè)函數(shù)是自定義的,名字大家可以隨便起,上面的getPhoneNumber可不能隨便修改。

接下來我們通過服務(wù)器獲取授權(quán)

上代碼:這里是js調(diào)用我們自己的后臺(tái),我們的后臺(tái)再調(diào)用微信服務(wù)端

onGetPhoneNumber(e) {
    var that = this;
    wx.login({
      success (res) {
        if (res.code) {
          console.log('步驟2獲檢查用戶登錄狀態(tài),獲取用戶電話號(hào)碼!', res)
          wx.request({
            url: '這里寫自己的獲取授權(quán)的服務(wù)器地址',
            data: {code: res.code},
            header: {'content-type': 'application/json'},
            success: function(res) {
              console.log("步驟三獲取授權(quán)碼,獲取授權(quán)openid,session_key",res);
              var userphone=res.data.data;
              wx.setStorageSync('userphoneKey',userphone);
              //解密手機(jī)號(hào)
              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') {//這里表示獲取授權(quán)成功
                wx.checkSession({
                  success:function(){
                        //這里進(jìn)行請(qǐng)求服務(wù)端解密手機(jī)號(hào)
                    that.deciyption(sessionID,encryptedData,iv);
                  },
                  fail:function(){
                    // that.userlogin()
                  }
                })
              }
 
            },fail:function(res){
                console.log("fail",res);
            }
          })
        } else {
          console.log('登錄失??!' + res.errMsg)
        }
      }
    })

后臺(tái)調(diào)用微信獲取授權(quán)碼

 下面是我通過自己寫的框架調(diào)用的,不用關(guān)心注解內(nèi)容,大家只關(guān)注自己的框架注解即可,不管是spring還是servlet只要請(qǐng)求能進(jìn)到該方法即可,所以重點(diǎn)關(guān)注中間部分,把參數(shù)值傳正確即可

    /**
     *  回調(diào)微信登錄信息
     * @param request
     * @param response
     */
    @MethodAnnotation(method="miniGetAuth",methoddes="小程序授權(quán)",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請(qǐng)求
	 * @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;
	}

這個(gè)值可以返回給前端,前端可以收到如下參數(shù)

接著我們通過授權(quán)之后,獲取第三個(gè)參數(shù)iv,調(diào)用下面方法進(jìn)行服務(wù)端解密

  that.deciyption(sessionID,encryptedData,iv);

deciyption(sessionID,encryptedData,iv){
    var that = this;
    
    console.log("步驟4根據(jù)秘鑰解密手機(jī)號(hào)碼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是授權(quán)失敗,可按照自己邏輯處理
          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);
      }
    })
  }

服務(wù)端解密代碼

 /**
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    @MethodAnnotation(method="miniGetPhone",methoddes="小程序解密手機(jī)號(hào)",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"); 
    }

 最終效果

總結(jié)

到此這篇關(guān)于微信小程序獲取用戶手機(jī)號(hào)碼的文章就介紹到這了,更多相關(guān)微信小程序獲取用戶手機(jī)號(hào)碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論