前端
提示: 官方提示需使用 botton 按钮的类型为 open-type="getPhoneNumber"
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
Page({
getPhoneNumber (e) {
// code 是换取手机号码的令牌
console.log(e.detail.code)
if (e.detail.errMsg == 'getPhoneNumber:ok') {
wx.request({
method: 'post',
url: 'https://demo.com/getPhoneNumber.php', // 后端地址
header: { "Content-Type": "application/x-www-form-urlencoded" }
data: { type: 'getPhoneNumber', code: e.detail.code },
success: (res) => {
console.log(res.data.phoneNumber);
}
})
}
}
})
PHP
提示:要获取手机号码需要用两个参数分别 code 令牌和 access_token, 所以要先获取 access_token
换取手机号的地址: https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
// getPhoneNumber.php
class GetPhoneNumber {
/*
获取 access_token
*/
public function getAccessToken() {
$appid = ''; // 填写自己的 AppId
$secret = ''; // 填写自己的秘钥
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=". $secret;
// 把 access_token 返回出去
return json_decode(file_get_contents($url), true);
}
/*
PHP 请求
*/
public function httpRequest($url, $data) {
$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($phoneCode)) {
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-type:application/json;",
"Accept:application/json"
));
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
$output = json_decode($output,true);
return $output;
}
/*
获取手机号码
*/
public function getPhoneNumber() {
// 获取前端传过来的 code 令牌
$code = isset($_POST['code']) ? $_POST['code'] : '';
// 先获取 access_token
$accessToken = $this -> getAccessToken();
$token = $accessToken['access_token'];
// 组装获取手机号的请求地址
$url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $token;
// 这里的 code 令牌必须是用数组格式, 并且要转成 JSON, 否则会报 47001 错误
$phoneInfo = $this -> httpRequest($url, json_encode([ 'code' => $code ]));
echo $phoneInfo['phone_info']['phoneNumber'];
}
}
$getPhoneNumber = new GetPhoneNumber();
$type = isset($_POST['type']) ? $_POST['type'] : '';
// 判断一下类型, 要执行哪个
if($type == 'getPhoneNumber') {
$getPhoneNumber -> getPhoneNumber();
}