47001报错说明
如果报47001,一定要注意将参数json处理
获取手机号
从基础库 2.21.2 开始,对获取手机号的接口进行了修改
流程
需要将 button 组件 open-type 的值设置为 getPhoneNumber,当用户点击并同意之后,可以通过 bindgetphonenumber 事件回调获取到动态令牌code,然后把code传到开发者后台,并在开发者后台调用微信后台提供的 phonenumber.getPhoneNumber 接口,消费code来换取用户手机号。每个code有效期为5分钟,且只能消费一次。
注:getPhoneNumber 返回的 code 与 wx.login 返回的 code 作用是不一样的,不能混用
服务端
phonenumber.getPhoneNumber
POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
请求参数 code string 是 手机号获取凭证
示例
public function getAccessToken()
{
$appid = 'appid';
$secret = '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();
}
public 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();
}
public function getPhoneNumber(){
$tmp = $this->getAccessToken();
$tmptoken = json_decode($tmp);
$token = $tmptoken->access_token;
$data['code'] = input('code');;
$url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
$info = $this->http_request($url,json_encode($data),'json');
$tmpinfo = json_decode($info);
$code = $tmpinfo->errcode;
$phone_info = $tmpinfo->phone_info;
$phoneNumber = $phone_info->phoneNumber;
if($code == '0'){
echo json_encode(['status'=>1,'msg'=>'请求成功','phoneNumber'=>$phoneNumber]);
die();
}else{
echo json_encode(['status'=>2,'msg'=>'请求失败']);
die();
}
}
|