微信小程序之获取用户手机号
2024-05-21Web前端
本文介绍了,如何获取用户手机号,并且用手机号登录小程序
wxml端
<view class="login">
<button type="primary" style="width:70%" open-type="getPhoneNumber" data-user_tel="{{user_tel}}" bindgetphonenumber="getPhoneNumber"
> 授权登录 </button>
</view>js端
getPhoneNumber (e) {
var code =e.detail.code // 动态令牌
if (code) {
//发起网络请求
wx.request({
url: 'xxxxx',
method:'post',
data: {
code: code
}
})
}
} /**
* 登录.
*
* @return \think\Response
*/
public function login(Request $request)
{
$data=$request->param();
$code=$data['code'];
$appID='xxx';
$appSecret='xxx';
$url= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appID&secret=$appSecret";//组装api
$tmptoken = json_decode(curlPost($url), true);//发起post请求
$token = $tmptoken['access_token'];//赋值token
$access_tokenB ="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";//组装api
$info = curlPost($access_tokenB,json_encode($data));
$tmpinfo = json_decode($info, true);
if ($tmpinfo['errcode'] == 0 && $tmpinfo['errmsg'] =='ok') {
return json(['status'=>'success','msg'=>'获取成功','phone'=>$tmpinfo['phone_info']['phoneNumber'] ]);
} else {
return json(['status'=>'success','msg'=>'获取失败']);
}
}
function curlPost($url, $data = [], $aHeader = "")
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
if ($aHeader) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
} 很赞哦! ()
