15年软件开发经验 只做源码定制 互联网+定制化解决方案

15年软件开发经验,只做源码定制!

原创设计 定制开发

满足您的个性化需求

微信小程序获取手机号

郭彦东| 发布于 2022-09-21 16:48:46| 271阅读| 0点赞| 0评论
举报

需要将 button 组件 open-type 的值设置为 getPhoneNumber,当用户点击并同意之后,可以通过 bindgetphonenumber 事件回调获取到动态令牌code,然后把code传后台,并在后台调用微信后台提供的 phonenumber.getPhoneNumber 接口,消费code来换取用户手机号。每个code有效期为5分钟,且只能消费一次。

注:getPhoneNumber 返回的 code 与 wx.login 返回的 code 作用是不一样的,不能混用

前端部分:


后端部分

	public  function getPhoneNumber(){
        $token=Cache::get('access_token');
        if(!$token){
            $appID = '';
            $secret = '';
             $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appID.'&secret='.$secret;
             $html = file_get_contents($url);
             $res = json_decode($html,true);
            if(isset($res['access_token'])){
                $token=$res['access_token'];
                Cache::set('access_token',$res['access_token'],$res['expires_in']);
            }
        }
    	$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();
        }
        
	}
	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();
        
    }


0

0条评论

别默默看啦~登录/注册一起参与讨论吧~

热门标签

郭彦东
微信扫一扫立即咨询
账号登录|扫码登录

立即注册 |忘记密码?

欢迎注册

已有账号马上登录

重置密码

扫码绑定微信
微信扫一扫

绑定手机号

分享到-微信

举报

  • 举报类型:

  • 举报描述:

您好,当前积分不足。

在线客服
拨打电话
17330196230 13230981129
顶部