获取手机号第一次不能在开发工具中使用,需要在真机上获取,第一次需要用户获取短信验证码。
微信小程序代码:
getPhoneNumber: function (e) {
if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
that.callBackError(e.detail.errMsg);
} else {
let params = {
open_id: wx.getStorageSync('wx_openid'),//用户open_id,不一定需要
sessionKey: wx.getStorageSync('session_key'),//调用wx.loign接口 获取code 上传服务器获取用户open_id ,session_key
encryptedData: e.detail.encryptedData,//调用获取用户手机号组件,直接获取
iv: e.detail.iv,//调用获取用户手机号组件,直接获取
userType: 3//不一定需要
}
console.log(params);
return;
https.user(config.user, params).then((res) => {
console.log(res)
}).catch(e => {
that.callBackError(e.message);
});
}
},
thinkPHP5代码
use applibwxlibwxBizDataCrypt;
private function getUserPhone($user)
{
$appid = Config::get("WXAPPID");
$sessionKey = $_POST['sessionKey'];
$encryptedData = $_POST['encryptedData'];
$iv = $_POST['iv'];
$wx = new wxBizDataCrypt($appid, $sessionKey);//微信解密函数,微信提供了php代码dome
$errCode = $wx->decryptData($encryptedData, $iv, $data);//微信解密函数
if ($errCode == 0) {
$data = json_decode($data, ture);
$phoneNumber = $data['phoneNumber'];
$user->where('open_id',$_POST['wx_openid'])->update(['phone' => $phoneNumber]);
return json_encode(['errorCode' => 0,"phone" => $phoneNumber]);
} else {
return $data;
}
}
微信解密函数https://developers.weixin.qq.com/miniprogram/dev/api/signature.html#wxchecksessionobject