微信小程序获取并绑定用户手机号
wxml
<button wx:else class="bindMobile" open-type="getPhoneNumber" bindgetphonenumber="bindMobile">绑定手机号</button>
js
async bindMobile(e){
if (e.detail.errMsg === 'getPhoneNumber:ok') {
const code = e.detail.code;
const openid = wx.getStorageSync('openid');
const data = await api.bindMobile({code:code,openid:openid},true);
if(data.code == 1){
wx.showToast({
title: '绑定成功',
icon: 'success',
})
this.getUserInfo();
}
} else {
console.log('用户拒绝授权');
}
},php
//绑定用户手机号
public function bindMobile(){
$input = safeInput('post.');
$openid = $input['openid'];
$code = $input['code'];
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".env('XCX.appid')."&secret=".env('XCX.secret');
$res = file_get_contents($url);
$res = json_decode($res, true);
$token= $res['access_token'];
$data = json_encode(['code' => $code]);
$url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token;
$response = json_decode(file_get_contents($url, false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => $data
]
])), true);
if($response['errcode'] !== 0) {
return json(['code'=>0,'msg'=>'绑定失败','autoMsg'=>'alert']);
}
$mobile = $response['phone_info']['phoneNumber'];
Db::name('user_snslogin')->where('openid',$openid)->update(['mobile'=>$mobile]);
return json(['code'=>1,'msg'=>'绑定成功']);
}