微信H5后台授权登录

15 篇文章 0 订阅
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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值