PHP、tp最新微信小程序获取手机号,获取手机号报47001

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 是 手机号获取凭证

示例

/*获取access_token,不能用于获取用户信息的token*/
    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');
        // 一定要注意转json,否则汇报47001错误
        $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();
        }
        
	}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦夏木禾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值