微信小程序如何获取手机号,无需解密版

2023-11-02   阅读:640   分类:后端    标签: 微信小程序

以往我们旧的接口:https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=jscode&grant_type=authorization_code

获取手机号码,需要到服务端引入官方解密方法对手机号进行解密,但是这个解密很不稳定,经常出现-41003: aes 加密数据解密失败问题,现在可以使用下面新的接口获取手机号:

步骤:

1、获取微信凭证access_token

2、动态获取手机号

注:该接口需配合手机号快速验证或手机号实时验证能力一起使用,当用户同意后,可以通过 bindgetphonenumber 或 bindrealtimegetphonenumber 事件回调获取到动态令牌code,再调用该接口将code换取用户手机号。 注意:每个code只能使用一次,code的有效期为5min。

前端代码:

<button class="get_submit" open-type="getPhoneNumber"  v-if="!qcode" bindgetphonenumber="getPhoneNumber">授权手机号</button>

js代码:

async getPhoneNumber (e) {
    var __that = this
    var iv = e.$wx.detail.iv;
    var encryptedData = e.$wx.detail.encryptedData;
    var code = e.$wx.detail.code;

     // 显示加载图标
     wx.showLoading({
      title: '加载中',
     })
    const getUserPhones = await getTriageUserPhone({
      code: code,
      iv: iv,
      encryptedData: encodeURIComponent(encryptedData),
    })
    if(getUserPhones.data.code==200){
     wx.hideLoading();
     __that.qcode = getUserPhones.data.data

    }
}

PHP代码:

public function getUserPhone(Request $request){
  $appid = Env('WECHAT_MINI_PROGRAM_APPID');
  $secret = Env('WECHAT_MINI_PROGRAM_SECRET');
  $encryptedData = urldecode($request->encryptedData);  //包括敏感数据在内的完整用户信息的加密数据
  $code=$request->code;  //用户登录授权获取到的code
  $iv=$request->iv;  //用户登录授权获取到的iv

  $access_token_phone = 'https://api.weixin.qq.com/cgi-bin/token?appid='.$appid.'&secret='.$secret.'&grant_type=client_credential';
  $access_token = $this->curlOpen($access_token_phone);
  $access_token = json_decode($access_token, true);

  $url_phone='https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token['access_token'];
  $data_phone = [
   'code'=>$code
  ];
  $result_phone = $this->curlRequest($url_phone,json_encode($data_phone));
  $result_phone = json_decode($result_phone, true);
  return response ()->json(['code'=>200,'msg'=>'success','data'=>$result_phone]);
}

使用新接口的好处就是不会再出现获取手机号失败问题。

【腾讯云】 爆款2核2G3M云服务器首年 61元,2核2G4M云服务器新老同享 99元/年,续费同价

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://www.tpxhm.com/adetail/1022.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×