You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8使用Socialite集成谷歌、Facebook登录回调URL重定向次数过多报错

问题排查与修复方案

一、重定向次数过多的核心原因

  • 回调路由被错误配置到了需登录的auth中间件分组中:访问回调时系统判定未登录,跳转至登录页,登录页又触发社交平台跳转,形成死循环。请检查routes/web.php中回调路由的中间件配置,确保回调路由排除在auth中间件之外。
  • 社交平台后台配置的回调地址与Laravel路由中定义的回调地址不一致,也会触发跳转异常,请同步检查谷歌、Facebook开发者后台的OAuth回调地址配置。

二、现有代码的错误修正

你现有代码存在方法调用错误、变量未定义、逻辑判断错误、未设置登录状态、无跳转响应等问题,修正后代码如下:

public function HandleFacebookCallback()
{
    // 正确获取Socialite返回的社交用户信息
    $socialUser = Socialite::driver('facebook')->user();
    
    // 根据邮箱查询是否已有对应账号
    $existingEmail = CustomerEmail::where('email', $socialUser->getEmail())->first();
    
    if (!$existingEmail) {
        // 新增客户主表数据
        $customer = new Customer();
        $customer->contact_person = $socialUser->getName();
        $customer->type = 'Primary';
        $customer->registration_type = 'Facebook';
        $customer->save();
        
        // 新增客户邮箱表数据,关联主表外键(请根据你实际的外键字段名调整,此处假设外键为customer_id)
        $customerEmail = new CustomerEmail();
        $customerEmail->customer_id = $customer->id;
        $customerEmail->email = $socialUser->getEmail();
        $customerEmail->save();
    } else {
        // 已有账号直接取出对应主表数据
        $customer = Customer::find($existingEmail->customer_id);
    }
    
    // 手动设置用户登录状态,若使用自定义customer守卫请替换为 auth('customer')->login($customer)
    auth()->login($customer);
    
    // 跳转至登录成功后的目标页面,可根据需求调整路由
    return redirect()->route('home');
}

三、谷歌登录回调适配

谷歌回调逻辑与Facebook完全一致,仅需将驱动名改为google,registration_type字段值改为对应平台标识即可。

内容的提问来源于stack exchange,提问作者Nabeel Ali Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 14:45:02