execute(function () use ($request, $domains) { $data = $request->validate([ 'agent_code' => ['nullable', 'string', 'max:32', 'required_without:domain'], 'domain' => ['nullable', 'string', 'max:255', 'required_without:agent_code'], ]); $agent = $domains->resolve($data['agent_code'] ?? null, $data['domain'] ?? null); if (!$agent) throw new \RuntimeException('代理推广信息不存在或已禁用'); return [ 'agent_id' => (int) $agent->id, 'agent_code' => $agent->invitation_code, 'agent_name' => $agent->username, ]; }); } public function bind(Request $request, AgentDomainService $domains) { return $this->execute(function () use ($request, $domains) { $data = $request->validate([ 'agent_code' => ['nullable', 'string', 'max:32', 'required_without:domain'], 'domain' => ['nullable', 'string', 'max:255', 'required_without:agent_code'], ]); $agent = $domains->resolve($data['agent_code'] ?? null, $data['domain'] ?? null); if (!$agent) { throw new \RuntimeException('代理推广信息不存在或已禁用'); } return DB::transaction(function () use ($request, $agent) { $user = User::query()->lockForUpdate()->findOrFail($request->user->id); if ($user->agent_id !== null && (int) $user->agent_id !== (int) $agent->id) { throw new \RuntimeException('会员已绑定其他代理,不能重复修改'); } if ($user->agent_id !== null) { return ['user_id' => (int) $user->id, 'agent_id' => (int) $agent->id]; } $createdAt = $user->getRawOriginal('created_at'); if (!$createdAt || Carbon::parse($createdAt)->lt(now()->subMinutes(config('agent.referral_bind_minutes', 30)))) { throw new \RuntimeException('推广归属只能在新会员注册后及时绑定'); } $user->agent_id = $agent->id; $user->save(); return ['user_id' => (int) $user->id, 'agent_id' => (int) $agent->id]; }); }); } }