php微信公众号登录注册

    public function getwx(){
        $appid = 'wxxxxxxxxxxxxx';
        $secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
        //获取换openid的code
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://www.xxx.com/home/index/index.html';//当前域名
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($baseUrl) . '&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
            header("Location:" . $url);
            exit;
        }
        $code = strval($_GET['code']);
        $state = strval($_GET['state']);
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        //$json_obj = getJson($get_token_url);
        $json_obj=$this->getJson($get_token_url);
        //根据openid和access_token查询用户信息
        $access_token = $json_obj['access_token'];
        $openid = $json_obj['openid'];
        $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        获取openid
        $user_obj=$this->getJson($get_user_info_url);
        //解析json
        $_SESSION['user'] = $user_obj;
        //包含文件
        //实例化Mysqldb类
        $user_id = $user_obj['openid']; //微信登陆号
        $user_pic = addslashes($user_obj['user_pic']); //头像
        $user_name = addslashes($user_obj['nickname']);//名称
        $user_sex = addslashes($user_obj['sex']); //性别
        $user_address = addslashes($user_obj['province']); //地址
        //tp3 存入数据库完成注册登录
        $data['openid'] = $user_id;
        $data['admin_name'] = $user_name;
        $data['user_pic'] = $user_pic;
        $data['sex'] = $user_sex;
        $data['address'] = $user_address;
        $user = M('user');
        $userinfo = $user->where(array('openid' => $user_id))->find();
          if(empty($userinfo)){
            M('user')->add($data);
            $userinfo = $user->where(array('openid' => $user_id))->find();
             $_SESSION['home']=$userinfo;
            $_SESSION['userid'] = $id;
            $_SESSION['openid'] = $userinfo['openid'];
        }else{
            $_SESSION['home']=$userinfo;
            $_SESSION['userid'] = $userinfo['userid'];
            $_SESSION['openid'] = $userinfo['openid'];
        }
    }
    function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

你可能感兴趣的:(php微信公众号登录注册)