在获取手机号需要让用户进行登录获取session_key进行解密的

首先需要让用户进行登录



uniapp


<button type=”primary” class=”weixin” style=”height: 83rpx;text-align: center;line-height: 83rpx;padding: 0;font-size: 30rpx;” open-type=”getUserInfo” @getuserinfo=”onLogin”>
        微信快速登录
      </button>
uni.showLoading({
        title: ‘登陆中…’
      });
      //获取用户基本信息
      let logInfo = {};
      let that = this;
      uni.login({
        provider: ‘weixin’,
        success: function(loginRes) {
          logInfo.code = loginRes.code;
          uni.getUserInfo({
            provider: ‘weixin’,
            success: function(infoRes) {
              logInfo.nickName = infoRes.userInfo.nickName;
              logInfo.avatarUrl = infoRes.userInfo.avatarUrl;
              uni.hideLoading();
              that.loginfo = logInfo;
  //这里获取到登录code,从而去换取openid与session_key
              login(‘mobile’, logInfo.code, logInfo.nickName)
                .then(res => {
                  if (res.code != 0) {
                    //登录失败,接口返回错误信息
                    uni.showModal({
                      title: ‘提示’,
                      content: res.msg,
                      showCancel: false,
                      success: function(res) {}
                    });
                  } else if (res.msg == ‘未授权手机号’) {
                    that.loginfo.sessionkey = res.data.sessionkey;
                    that.loginfo.openid = res.data.openid;
                    that.show = true
                  } else {
                    // 登录成功
                    uni.showModal({
                      title: ‘提示’,
                      content: res.msg,
                      showCancel: false,
                      success: function(res) {
                        uni.navigateBack({ delta: 1 });
                      }
                    });
                  }
                })
                .catch(err => {
                  console.log(err);
                  uni.showModal({
                    title: ‘提示’,
                    content: ‘登录失败,请检查网络’,
                    showCancel: false,
                    success: function(res) {}
                  });
                });
            },
            fail: function(res) {
              uni.hideLoading();
              uni.showModal({
                title: ‘提示’,
                content: ‘获取登录所需的随机用户标识失败’,
                showCancel: false,
                success: function(res) {}
              });
            }
          });
        },
        fail: function(res) {
          uni.hideLoading();
          uni.showModal({
            title: ‘提示’,
            content: ‘获取基本信息失败’,
            showCancel: false,
            success: function(res) {}
          });
        }
      });

 

 

后端(PHP进行处理)

 


$strUrl = “https://api.weixin.qq.com/sns/jscode2session?appid=” . ‘AppId’ . “&secret=” . “Select”. “&js_code=” . “用户CODE” . “&grant_type=authorization_code”;
                    $strCurlRequest = curlRequest($strUrl);
                    if (!$strCurlRequest[‘ok’]) result([], 1, ‘从微信获取用户唯一标识失败’);
                    $arrCurlData = array();
                    $isErr = false;
                    try {
                        $arrCurlData = json_decode($strCurlRequest[‘data’], true);
                    } catch (\Throwable $e) {
                        $isErr = true;
                    }
/**
 * CURL请求
 *
 * @param [type] $strUrl        访问地址
 * @param string $strMethod     请求方式
 * @param array $arrData        请求发送的数据
 * @param array $arrHeader      请求时发送的header
 * @param boolean $isJson       是否JSON请求
 * @param boolean $strFilePath  PUT形式上传的文件
 * @param integer $intTimeOut   超时时间
 * @return void
 * @author 一颗大萝北 [email protected]
 */
function curlRequest($strUrl, $strMethod = “GET”, $arrData = array(), $arrHeader = array(), $isJson = false, $strFilePath = false, $intTimeOut = 60)
{
    $arrHeaders = array();
    if ($isJson == true && empty($arrHeader[‘Content-Type’])) $arrheader[] = ‘Content-Type:application/json; charset=utf-8’; //当为JSON提交时header没有设置类型时补充设置
    if ($isJson == true && empty($arrHeader[‘Content-Length’])) $arrheader[] = ‘Content-Length:’ . strlen(json_encode($arrData, JSON_UNESCAPED_UNICODE)); //当为JSON提交时header没有设置长度时补充设置
    foreach ($arrHeader as $k => $v) $arrHeaders[] = $k . ‘:’ . $v; //拼接header
    $objCh = curl_init();
    curl_setopt($objCh, CURLOPT_SSL_VERIFYPEER, false); //跳过证书检查
    curl_setopt($objCh, CURLOPT_SSL_VERIFYHOST, false);  //从证书中检查SSL加密算法是否存在
    curl_setopt($objCh, CURLOPT_RETURNTRANSFER, true);   //返回字符串,而不直接输出
    curl_setopt($objCh, CURLOPT_HTTPHEADER, $arrHeaders); //设置header
    curl_setopt($objCh, CURLOPT_TIMEOUT, $intTimeOut);      //设置超时时间
    curl_setopt($objCh, CURLOPT_URL, $strUrl);
    $strMethod = strtoupper($strMethod); //统一转为大写
    // if (!empty($arrData) && !$isJson) $objCurlData =  http_build_query($arrData);
    if (!empty($arrData) && $isJson) $arrData =  json_encode($arrData, JSON_UNESCAPED_UNICODE);
    if ($strFilePath !== false && !is_file($strFilePath) && $strMethod != ‘PUT’) return [‘ok’ => false, ‘msg’ => ‘选择的文件不存在或请求方式不是PUT’];
    switch ($strMethod) {
        case ‘PUT’:
            curl_setopt($objCh, CURLOPT_PUT, true);
            if (is_file($strFilePath) && $strFilePath !== false) {
                //存在文件上传
                curl_setopt($objCh, CURLOPT_INFILE, fopen($strFilePath, ‘rb’)); //设置资源句柄
                curl_setopt($objCh, CURLOPT_INFILESIZE, filesize($strFilePath));
            }
            break;
        case ‘POST’:
            curl_setopt($objCh, CURLOPT_POST, true);
            break;
        case ‘GET’:
            curl_setopt($objCh, CURLOPT_CUSTOMREQUEST, $strMethod);
            if (!empty($arrData) && !$isJson) $arrData =  http_build_query($arrData);
            break;
        default:
            curl_setopt($objCh, CURLOPT_CUSTOMREQUEST, $strMethod);
            break;
    }
    curl_setopt($objCh, CURLOPT_POSTFIELDS, $arrData);
    $response = curl_exec($objCh);
    if ($error = curl_error($objCh)) {
        return [‘ok’ => false, ‘msg’ => curl_error($objCh)];
    }
    curl_close($objCh);
    return [‘ok’ => true, ‘msg’ => ‘成功!’, ‘data’ => $response];
}

这里获取到了openid与session_key,将其保存回来之后进行申请手机号操作

 




<button
                  class=”weixin”
                  style=”text-align: center;line-height: 73rpx;height: 73rpx;padding: 0;font-size: 30rpx;”
                  open-type=”getPhoneNumber”
                  @getphonenumber=”getPhoneNumber”
                >
                  手机号授权
                </button>
 getPhoneNumber(e) {
      if (‘getPhoneNumber:ok’ != e.detail.errMsg) {
        uni.showModal({
          title: ‘提示’,
          content: ‘手机号授权获取失败!’,
          showCancel: false,
          success: function(res) {}
        });
      } else {
        login(‘mobile’, this.loginfo.code, this.loginfo.nickName, {
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData,
          sessionkey: this.loginfo.sessionkey,
          openid: this.loginfo.openid
        })
          .then(res => {
            if (res.code != 0) {
              //登录失败,接口返回错误信息
              uni.showModal({
                title: ‘提示’,
                content: res.msg,
                showCancel: false,
                success: function(res) {}
              });
            }else {
              // 登录成功
              uni.showModal({
                title: ‘提示’,
                content: res.msg,
                showCancel: false,
                success: function(res) {
                  uni.navigateBack({ delta: 1 });
                }
              });
            }
          })
          .catch(err => {
            console.log(err);
            uni.showModal({
              title: ‘提示’,
              content: ‘登录失败,请检查网络’,
              showCancel: false,
              success: function(res) {}
            });
          });
      }
    },

 

获取到encryptedData,sessionkey后进行解密

 


//解密手机号
                    if (strlen($strSessionKey) != 24) {
                        result([], 1, “获取手机号授权密匙错误,请重试!”);
                    }
                    $aesKey = base64_decode($strSessionKey);//session_key
                    if (strlen($strIv) != 24) {
                        result([], 1, “获取手机号授权校验错误,请重试!”); //IV
                    }
                    $aesIV = base64_decode($strIv);
                    $aesCipher = base64_decode($strEncryptedData);
                    $result = openssl_decrypt($aesCipher, “AES-128-CBC”, $aesKey, 1, $aesIV);
                    $dataObj = json_decode($result);
                    if ($dataObj  == NULL) {
                        result([], 1, “获取手机号授权解密错误,请重试!”);
                    }
                    if ($dataObj->watermark->appid != “APPID”) {
                        result([], 1, “获取手机号授权解密错误,请重试!”);
                    }
                    $arrResult = [];
                    try {
                        $arrResult = json_decode($result, true);
                    } catch (\Throwable $e) {
                        result([], 1, “获取手机号授权解密错误,请重试!”);
                    }
解密后就可以获取到手机号了

官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

官方加解密文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#%E5%8A%A0%E5%AF%86%E6%95%B0%E6%8D%AE%E8%A7%A3%E5%AF%86%E7%AE%97%E6%B3%95

 

 

说点什么
支持Markdown语法
好耶,沙发还空着ヾ(≧▽≦*)o
Loading...