removeWebhook($model); $model->asaas_api_key = null; $model->asaas_webhook_id = null; $model->status = CompanyPaymentAccount::STATUS_PENDING; $model->onboarded_at = null; $model->save(); return $model->fresh(); } if ($model->exists && $model->asaas_api_key === $apiKey && $model->asaas_webhook_id) { return $model->fresh(); } try { $this->webhookService->validateKey($apiKey); } catch (AsaasException $e) { throw ValidationException::withMessages([ 'asaas_api_key' => 'Chave Asaas inválida ou sem permissão. Verifique e tente novamente.', ]); } $this->removeWebhook($model); try { $webhookId = $this->webhookService->register($apiKey); } catch (AsaasException $e) { Log::error('Falha ao registrar webhook Asaas da matriz: ' . $e->getMessage()); throw ValidationException::withMessages([ 'asaas_api_key' => 'Não foi possível registrar o webhook na Asaas. Tente novamente.', ]); } $model->asaas_api_key = $apiKey; $model->asaas_webhook_id = $webhookId; $model->status = CompanyPaymentAccount::STATUS_ACTIVE; $model->onboarded_at = $model->onboarded_at ?? now(); $model->save(); return $model->fresh(); } private function removeWebhook(CompanyPaymentAccount $model): void { if (!$model->asaas_api_key || !$model->asaas_webhook_id) { return; } try { $this->webhookService->delete($model->asaas_api_key, $model->asaas_webhook_id); } catch (\Throwable $e) { Log::warning('Não foi possível remover webhook Asaas da matriz: ' . $e->getMessage()); } } }