微信小程序用戶授權獲取手機號(getPhoneNumber)

前言

小程序有一個獲取用戶很便捷的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: function() {
      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 String deciphering(String encrypdata, 
String ivdata, String sessionkey,
HttpServletRequest request) {

    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();
}
    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("AES/CBC/PKCS5Padding"); 
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); 
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); 
    //解析解密後的字符串 
    return new String(cipher.doFinal(encData),"UTF-8"); 
  }

總結

到此這篇關於微信小程序用戶授權獲取手機號的文章就介紹到這瞭,更多相關小程序授權獲取手機號內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: