序言:目前该接口针对非个人开发者,且完成了认证的小程序开放(不包含海外主体)。需谨慎使用,若用户举报较多或被发现在不必要场景下使用,微信有权永久回收该小程序的该接口权限。
文档地址:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
需求:授权手机号
实现方法:
wxml
<button class="name line1 my_money phone11" open-type='getPhoneNumber' bindgetphonenumber='getPhoneNumber' >授权手机号</button>
因为需要用户主动触发才能发起获取手机号接口,所以该功能不由 API 来调用,需用 button 组件的点击来触发。
js
/**
* 手机号授权
*/
getPhoneNumber:function(e){
console.log(e);
if(e.detail.errMsg != 'getPhoneNumber:ok'){
if(e.detail.errMsg == 'getPhoneNumber:fail user deny' || e.detail.errMsg == 'getPhoneNumber:fail:user deny'){
wx.showToast({
title: '用户取消',
icon: 'none'
})
}else{
wx.showToast({
title: e.detail.errMsg,
icon: 'none'
})
}
return false;
}
var encryptedData = e.detail.encryptedData;
var iv = e.detail.iv;
this.phone_session(encryptedData,iv);
},
//获取手机号session
phone_session:function(encryptedData,iv){
wx.showLoading({ title: '加载中' ,'mask' : false });
var that = this;
var token = wx.getStorageSync('TOKEN');
var host = HTTP_REQUEST_URL;
wx.login({
success: function (r) {
var params2 = {};
params2.code = r.code;
wx.request({
url: host+'/api/common/get_session_key',
data:params2,
method:'post',
success: function (rr) {
if(rr['data']['status'] == 200) {
var session_key = rr['data']['data']['session_key'];
wx.request({
url: host+'/api/user/phone',
method: 'POST',
data: {
session_key: session_key,
encryptedData: encryptedData,
iv: iv,
},
header: {
'Accept': 'application/json',
'Authori-zation' : 'Bearer ' + token,
},
success(res3) {
// 绑定成功
wx.hideLoading();
if(res3.data.status == 200) {
that.setData({
userInfo: res3.data.data.user_info
})
} else {
wx.showToast({
title: res3.data.msg,
icon: 'none'
})
}
},
fail(res3) {
// 绑定失败
wx.showToast({
title: res3.data.msg,
icon: 'none'
})
}
})
} else {
wx.showToast({
title: rr['data']['msg'],
icon: 'none'
})
}
},
})
}
})
},
php
/**
* 授权手机号
*/
public function phone(Request $request){
//开发者如需要获取敏感数据,需要对接口返回的加密数据( encryptedData )进行对称解密
$encryptedData = input('param.encryptedData');
$iv = input('param.iv');
$session_key = input('param.session_key');
require_once $root_path.'/extend/wxbizdatacrypt/wxBizDataCrypt.php';
$pc = new \WXBizDataCrypt($wechat["routine_appId"], $session_key);
$errCode = $pc->decryptData($encryptedData, $iv, $result); //其中$data包含用户的所有数据
if ($errCode != 0) {
return_json("网络错误,请重试",100);
}else{
$result = json_decode($result,true);
Db::name("user")->where(["uid"=>$user_info["uid"]])->update(["phone"=>$result["phoneNumber"],"zt_phone"=>$result["phoneNumber"]]);
}
}
获取微信用户绑定的手机号,需先调用wx.login接口。
实现功能后如下
我是小程序软件开发,每天分享开发过程中遇到的知识点,如果对你有帮助的话,帮忙点个赞再走呗,非常感谢。
往期文章分享: