前端:
Page({
getPhoneNumber(e){
//console.log(e.detail.code); //最新官方文档里是这个参数,很重要;
wx.request({
url: 'https://demo.xxxxx.com/frontapi/getphonenumber.php',
data:{"code":e.detail.code},
success:(res)=>{
console.log(res.data.phoneNumber);
}
})
}
})
后端:
/*获取access_token,不能用于获取用户信息的token*/
function getAccessToken()
{
$appid = '填写自己的appID';
$secret = '填写自己的秘钥';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
return $res;
exit();
}
//图片合法性验证
function http_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
return $output;
exit();
}
// 获取手机号
function getPhoneNumber(){
$tmp = getAccessToken();
$tmptoken = json_decode($tmp);
$token = $tmptoken->access_token;
$data['code'] = $_GET['code'];
$url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
$info = http_request($url,json_encode($data),'json');
// 一定要注意转json,否则汇报47001错误
$tmpinfo = json_decode($info);
$code = $tmpinfo->errcode;
$phone_info = $tmpinfo->phone_info;
$phoneNumber = $phone_info->phoneNumber;
if($code == '0'){
echo json_encode(['code'=>1,'msg'=>'请求成功','phoneNumber'=>$phoneNumber]);
die();
}else{
echo json_encode(['code'=>2,'msg'=>'请求失败']);
die();
}
}
getPhoneNumber();