欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信H5后台授权登录

程序员文章站 2022-04-03 08:54:46
...
class Login extends Common {
    public function login(){
        $appid = Config::get('app.appid');
        $secret = Config::get('app.secret');
        $path = input('path');
        $code = input('code');
        if(!$code){
            $redirect_uri = urlencode(Config::get('app.url').'/api/login/login?path='.$path);//重定向地址
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
            header("Location:" . $url);
        }else{
            $code = input('code');
            $path = input('path');
            
            $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=$code&grant_type=authorization_code";
        
	        $output = $this->curl_get($oauth2Url);
	    	
	        $res = json_decode($output, true);
	        if($res['openid']){
	        	$access_token = $res['access_token'];
	        	$openid = $res['openid'];
	        	$user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
	        	$user_info = $this->curl_get($user_info_url);
	        	$user_info = json_decode($user_info,true);
	        	$user = Huashiusers::where('openid',$openid)->find();
	        	if(!$user){
	        		$user = new Huashiusers();
	        		$user->openid = $user_info['openid'];
	        		$user->create_time = time();
	        		$user->is_bit = 0;
	        		$user->huadou = 0;
	        		$user->money = 0;
	        		$user->name = $user_info['nickname'];
	        	}
	        	$user->nickname = $user_info['nickname'];
	        	$user->img = $user_info['headimgurl'];
	        	$user->save();
	        	$u = Config::get('app.url').$path.'?user_id='.$user['id'].'&openid='.$user['openid'];
	        	header("Location:" . $u);
	        }else{
	            return '登陆失败';
	        }
        }

    }
    
    public function curl_get($url)
    {
        $curl = curl_init();
        $removeBom = function($url) { return preg_replace('/\\0/', "", $url); };
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl,CURLOPT_URL,$removeBom($url));
        curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
}
相关标签: php tp php h5