小程序授權(quán)獲取手機(jī)號

這是小程序授權(quán)獲取手機(jī)號的步驟

第一步: wx.login---> 獲取登錄憑著(code)
第二步:將code發(fā)送到后端--->后端用code換session_key和openid
第三步:小程序調(diào)getPhoneNumber--->將encryptedData和iv傳給后臺
第四步:后臺進(jìn)行解密得到j(luò)son--->進(jìn)而獲取到手機(jī)號

第一步:獲取登錄憑證code

這個code碼是使用小程序登錄接口完成后取的,這個wx.request()請求是為了把code發(fā)送到后端,后端用code換取session_key和openid。

//獲取手機(jī)號前先獲取openid和session_key
wx.login({
    success: function (res) {
      if (res.code) { //使用小程序登錄接口完成后端用戶登錄
        wx.request({
          url: app.d.hostUrl + 'getOpenId',//你自己api接口的路徑
          data: {
            code: res.code,
            appid: "你的小程序AppID",
            secret: "你的小程序secret",
          },
          success: function (res) {
            //把openid保存到緩存里
            wx.setStorageSync("openid", res.openid);
            wx.setStorageSync("session_key", res.session_key);
          }
        })
      } else {
        console.log('獲取用戶登錄態(tài)失敗!' + res.errMsg)
      }
    }

前端已經(jīng)把獲取openid和session_key需要的參數(shù)傳給后端了,接下來就是后端的事了

第二步:后端用code換session_key和openid
//獲取微信openId,
    public function getOpenId($dataArr){
        $retArr["ret"] = array("retCod" => "0", "retMsg" => "get openId  is success!");
        $code = $dataArr['code'];
        $appid = $dataArr['appid'];
        $secret = $dataArr['secret']; 
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
        $str = $this->doCurl($api);
        $str = json_decode($str,true);
        $retArr['data']['openid']= $str['openid'];
        $retArr['data']['session_key']= $str['session_key'] ;
        return $retArr;
    }
   //處理接口請求
    public function doCurl($url)
    {
        $curl = curl_init();
        // 使用curl_setopt()設(shè)置要獲取的URL地址
        curl_setopt($curl, CURLOPT_URL, $url);
        // 設(shè)置是否輸出header
        curl_setopt($curl, CURLOPT_HEADER, false);
        // 設(shè)置是否輸出結(jié)果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 設(shè)置是否檢查服務(wù)器端的證書
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // 使用curl_exec()將CURL返回的結(jié)果轉(zhuǎn)換成正常數(shù)據(jù)并保存到一個變量
        $data = curl_exec($curl);
        // 使用 curl_close() 關(guān)閉CURL會話
        curl_close($curl);
        return  $data;//json_decode($data);
    }

這樣,前端success就能拿到openid和session_key了,現(xiàn)在,我們要在后端通過php,用session_key和openid來解密獲取手機(jī)號碼

第三步:調(diào)用getPhoneNumber,將encryptedData和iv傳給后臺

那現(xiàn)在(wxml)需要有一個按鈕觸發(fā),點(diǎn)了那個按鈕就能獲取手機(jī)號碼了

<button class='bottom' 
            type='primary' 
            open-type="getPhoneNumber" 
            lang="zh_CN"                                                    
           bindgetphonenumber="bindGetPhoneNumber">微信登錄授權(quán)
</button>

//點(diǎn)擊獲取用戶手機(jī)號按鈕,這樣手機(jī)號就獲取到了
  bindGetPhoneNumber: function (e) {
    if (e.detail.errMsg== "getPhoneNumber:ok"){
        wx.showLoading({
          title: '授權(quán)登錄中...',
        })
        var that = this;
        var detail = e.detail;
        var iv = detail.iv;
        var encryptedData = detail.encryptedData;
        var appid = app.globalData.appid;
        var userInfo = app.globalData.userInfo;
        var session_key = userInfo.session_key;
        allApi.getUserMobile({
          uid: "",
          v: app.globalData.v,
          imei: app.globalData.imei,
          sid: "",
          sign: "",
          appKey: app.globalData.appKey,
          src: app.globalData.src,
          r: app.globalData.r,
          city_id: app.globalData.city_id,
          city_name: app.globalData.city_name,
          data: { "appid": appid,
                  "session_key": session_key,             
                  "encryptedData": encryptedData,
                  "iv": iv },
       })
      .then((res) => {
        if (res.data.ret.retCod == 0) {
          wx.hideLoading();
          var mobile = res.data.data.mobile;
          var userInfo = that.data.userInfo;
          userInfo.mobile = mobile;
          wx.setStorageSync("wxUserInfo", userInfo);
          app.globalData.userInfo = userInfo;
          that.setData({
            'mobile': mobile,
            'isAuth': false,//改為不需要授權(quán)
            'userInfo': userInfo,
          })
          that.addUserMobile();
        }else{
          wx.showLoading({
            title: '請求超時,請重試',
          })
          setTimeout(this.hideLoadTip, 2000);
        }

      }).catch(function (error) {
        wx.hideLoading()
        wx.showToast({ icon: "none", title: "授權(quán)失敗", duration: 1000 })
      })
    }
},
第四步:通過傳參appid、session_key、encryptedData、iv解密獲取手機(jī)號

因?yàn)樯婕暗浇饷苁謾C(jī)號,所以先看下官方文檔
小程序開發(fā)文檔流程
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

下載解密文件.png

這個官方的demo文件很簡單,大家可以根據(jù)自己的業(yè)務(wù)需求是更改


image.png
 public function getUserMobile($dataArr) {
    $retArr["ret"] = array("retCod" => "0", "retMsg" => "get wx user mobile is success!");
    $appid = $dataArr['appid'];
    $sessionKey = $dataArr['session_key'];
    $encryptedData = $dataArr['encryptedData'];
    $iv = $dataArr['iv'];
    //WxBizDataCrypt該類是官方提供的那個
    $pc = new WxBizDataCrypt($appid, $sessionKey);
    $errCode = $pc->decryptData($encryptedData, $iv, $data);
    if ($errCode == 0) {
          $phone = json_decode($data)->phoneNumber;
        $retArr['data']['mobile']= $phone;
    } else {
        $retArr["ret"] = array("retCod" => "-1", "retMsg" => "get wx user info  is fail!");
    }
    return $retArr;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容