<?php
/*获取access_token,不能用于获取用户信息的token*/
function getAccessToken()
{
$appid = 'AppId';
$secret = 'AppSecret';
$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'];//前端获取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();
?>