公众号---获取用户openid,用户信息

//首页登录-注册
    public function get_wx_code_new(){
        $request = Request();
        $domain = $request->domain();
        $url = $domain; //跳转绑定手机号页

        $code = input('code');
        $wechat = $this->getOpenID($code);

        $data=[
            'nickName'=>$wechat['nickname'],
            'gender'=>$wechat['sex'] ? $wechat['sex'] : '0', //0=保密,1=男,2=女
            'avatarUrl'=>$wechat['headimgurl'],
            'unionId'=>$wechat['unionid'],
            'openId'=>$wechat['openid'],
        ];
        error_log(date('Y-m-d H:i:s').' $wechat==='.json_encode($wechat,320).' '.PHP_EOL,3,'../runtime/get_wx_code.log');

        $str=http_build_query($data, '', '&');
        $url.='?'.$str;
        $this->redirect($url);
    }
    //获取openid
    protected function getOpenID($code) {
//        $WeChat_config = addons_config('WeChat');
        $WeChat_config = Db::name('member_config')->where('name','wechat')->value('value');
        $WeChat_config = json_decode($WeChat_config,true);
        $appid = $WeChat_config['code_appid'];
        $appsecret = $WeChat_config['code_appsecret'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code";
        $weixin = file_get_contents($url); //通过code换取网页授权access_token
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode); //转换成数组

        error_log(date('Y-m-d H:i:s').' getOpenID---$array==='.json_encode($array,320).' '.PHP_EOL,3,'../runtime/get_wx_code.log');

//        halt($array);
        //通过access_token获取用户信息
        $access_token=$this->getWeChatUserInfo($array['access_token'],$array['openid']);

        return $access_token;
    }

//获取$access_token,$openid换取微信用户信息
    public function getWeChatUserInfo($access_token,$openid){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $output = file_get_contents($url);
        $weChatUserInfo = json_decode($output,true);
        return $weChatUserInfo;
    }



  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值