网络知识 娱乐 微信小程序新版本与旧版本授权用户手机号的教程

微信小程序新版本与旧版本授权用户手机号的教程

开发微信小程序会有些场景是需要授权用户手机号的,微信小程序授权用户手机号是通过getPhoneNumber接口授权的,因为需要用户主动触发才能发起获取手机号接口,所以该功能不由 API 来调用,需用 button 组件的点击来触发。另外,新版本接口不再需要提前调用wx.login进行登录。从基础库 2.21.2 (微信版本8.0.16)开始,对获取手机号的接口进行了安全升级,也就是说基础库 2.21.2 以前的版本是旧版本,新版本和旧版本的区别是多了code参数,以后旧版本接口可能会摒弃,建议大家使用新版本的手机号授权。

小程序授权手机号获取的参数

首先先讲一下旧版本如何授权用户手机号,旧版本授权手机号点击授权时,会出现第一次授权不成功的现象,什么原因呢?code过期了,有人会问我获取的code是点击授权手机号时一起获取的,怎么会过期呢?这个就是这么神奇,可能是微信的bug问题吧,反正一直没决解,但也不是没有解决的方法,解决方法就是在onLoad页面加载时就wx.login获取code值;

微信小程序手机号操作流程

旧版本授权手机号的代码示例

微信小程序wxml页面

<button open-type="getPhoneNumber" bindgetphonenumber="getUserMobileInfo"></button>

微信小程序js页面

/**n * 页面的初始数据n */n data: {n code: '',n },n/**n * 获取手机号n */n getUserMobileInfo: function (e) {n var that = this,n code = that.data.code,n encryptedData = e.detail.encryptedData,n iv = e.detail.iv;n wx.checkSession({n success() {n //session_key 未过期,并且在本生命周期一直有效n },n fail() {n wx.login({n success: res => {n that.setData({n code: res.coden })n }n })n },n complete() {n if (e.detail.errMsg == "getPhoneNumber:ok") {n userService.getTelephoneNumber(code, encodeURIComponent(encryptedData), encodeURIComponent(iv)).then(function (data) {n wx.hideLoading();n var mobileValue = data.datan that.setData({n mobileValue: mobileValue,n })n }, function (data) {n wx.hideLoading();n wx.showToast({n title: data.message,n icon: 'none'n });n });n } else {n wx.showModal({n title: '提示',n content: '需获取手机号才可提交信息',n })n }n }n })n },n /**n * 生命周期函数--监听页面加载n */n onLoad: function (options) {n wx.login({n success: res => {n this.setData({n code: res.coden })n }n })n },n

用户同意授权,我们可以根据wx.login时获取到的code来通过后台以及微信处理拿到session_key,最后通过app_id,session_key,iv,encryptedData(用户同意授权errMsg返回‘getPhoneNumber:ok')

传给后台的参数:code参数传到后台需要换取session_key;encryptedData包括敏感数据在内的完整用户信息的加密数据,iv加密算法的初始向量,这两个参数后台需要解密的,解密的方法可以去微信官方开发文档查看,有很详细说明,这里就不讲述了。

后台处理后返回的参数

后台处理后返回的参数

phoneNumber:用户绑定的手机号(国外手机号会有区号);

purePhoneNumber :没有区号的手机号;

countryCode:区号

新版本授权手机号的代码示例

微信小程序wxml页面

<button open-type="getPhoneNumber" bindgetphonenumber="getUserMobileInfo"></button>

微信小程序js页面

/**n * 获取手机号n */n getUserMobileInfo: function (e) {n var that = this,n code = e.detail.code;n if (e.detail.errMsg == "getPhoneNumber:ok") {n userService.getTelephoneNumber(code).then(function (data) {n wx.hideLoading();n var mobileValue = data.datan that.setData({n mobileValue: mobileValue,n })n }, function (data) {n wx.hideLoading();n wx.showToast({n title: data.message,n icon: 'none'n });n });n } else {n wx.showModal({n title: '提示',n content: '需获取手机号才可提交信息',n })n }n }

php后端的逻辑处理

/**n * 获取access_tokenn * @return arrayn */n private function getSession() {n $params = [n 'appid' => '你的小程序appid',n 'secret' => '你的小程序appsecret',n 'grant_type' => 'client_credential'n ];n $result = $this->httpGet("https://api.weixin.qq.com/cgi-bin/token", $params);n return json_decode($result, true);n }n /**n * code获取用户手机信息n */n public function getTelephoneNumber() {n if (IS_POST) {n $raw_json = file_get_contents("php://input");n $post_data = json_decode($raw_json, true);n $code = $post_data['code'];n $session_res = $this->getSession($code);n if ($session_res['errcode']) {n $this->apiReturn('0', $session_res['errmsg']);n }n $param_data = [n 'code' => $code,n ];n $res_data = $this->httpJsonPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$session_res['access_token'], $param_data);n $info = json_decode($res_data, true);n if($info['errcode'] != 0){n $this->apiReturn($info['errcode'], $info['errmsg']);n }n $this->apiReturn('1', '', $info['phone_info']['phoneNumber']);n }n }n /**n * json 请求n * @param string $urln * @param array $datan */n protected function httpJsonPost($url, $data = NULL)n {nn $curl = curl_init();nn curl_setopt($curl, CURLOPT_URL, $url);n curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);n curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);n if(!$data){n return 'data is null';n }n if(is_array($data))n {n $data = json_encode($data);n }n curl_setopt($curl, CURLOPT_POST, 1);n curl_setopt($curl, CURLOPT_POSTFIELDS, $data);n curl_setopt($curl, CURLOPT_HEADER, 0);n curl_setopt($curl, CURLOPT_HTTPHEADER,array(n 'Content-Type: application/json; charset=utf-8',n 'Content-Length:' . strlen($data),n 'Cache-Control: no-cache',n 'Pragma: no-cache'n ));n curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);n $res = curl_exec($curl);n $errorno = curl_errno($curl);n if ($errorno) {n return $errorno;n }n curl_close($curl);n return $res;nn }n /**n * GET 请求n * @param string $urln * @param array $paramn */n protected function httpGet($url, $param) {n $url = $url . '?' . http_build_query($param);n $curl = curl_init();n if (stripos($url, 'https://') !== FALSE) {n curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);n curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);n curl_setopt($curl, CURLOPT_SSLVERSION, 1);n }n curl_setopt($curl, CURLOPT_URL, $url);n curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);n $content = curl_exec($curl);n $status = curl_getinfo($curl);n curl_close($curl);n if (intval($status['http_code']) == 200) {n return $content;n } else {n return false;n }n }

接口成功返回的整体数据结构,如下图:

接口成功返回的整体数据结构

写后台逻辑时我遇到两个错误反馈

第一种反馈:{"errcode":47001,"errmsg":"data format error hint: [AgoBsDOre-c6ouia] rid: 626b7164-1d9c3b08-076fdbdb"},这个错误是因为没有用请求头 Content-Type为application/json,所以我改成了json数据post请求,这个报错解决了。

第二种反馈:{"errcode":41001,"errmsg":"access_token missing rid: 626b7285-31e3f8d7-3556ca83"},这个错误是因为access_token参数,我没写在url上,是和code一起写在数组中传值的,这样是不对,应该写到url上的,这个报错解决了。

旧版本的后台逻辑没有写出来,是因为微信以后要摒弃旧版本的写法,这里就没必要写了,如果有不会的,可以网上搜索一下,建议大家还是用新版本获取用户手机号的写法!小程序js文件中request请求,我用的是封装后的写法传参的,你可以微信小程序原生的wx.request传参写法。以上就是微信小程序新版本与旧版本授权用户手机号的教程了,仅供参考!!!