页面按钮
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">授权手机号</button>
js文件
getPhoneNumber: function (e) {
wx.showLoading({
title: '正在授权',
})
var that = this;
if (e.detail.errMsg == "getPhoneNumber:ok") {
wx.request({
url: api.login_getphone,
data: {
openid: that.data.openid,
code:e.detail.code,
},
method: "post",
success: function (res) {
if(res.data.status == '200'){
wx.redirectTo({
url: '/pages/index/index',
})
app.data.phone=true
}else{
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
}
})
}
wx.hideLoading()
},
php文件
//获取用户手机号
public function getphone(){
$code = input('code');
$openid = input('openid');
$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$this->access_token();
$arr = json_encode(array('code'=>$code));
$data = json_decode($this->httpRequest($url,$arr,'POST'),true);
if($data['errcode'] == 0){
$phone = $data['phone_info']['phoneNumber'];
$user = Users::where('openid',$openid)->find();
$user->phone = $phone;
$user->save();
return json(['status'=>'200']);
}else{
return json(['status'=>'201','msg'=>'获取失败']);
}
}
function httpRequest($url,$data='',$method='GET'){
try{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
// curl_setopt($curl, CURLOPT_USERAGENT,CURLOPT_USERAGENT);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
if($method=='POST')
{
curl_setopt($curl, CURLOPT_POST, 1);
if ($data !='')
{
curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
}
}
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}catch(\Exception $e){
abort(config('error_log_code'),$e->getMessage());
// var_dump($e->getMessage());die;
}
}