CompanyPaymentAccountService.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\AsaasException;
  4. use App\Models\CompanyPaymentAccount;
  5. use App\Services\Integrations\Asaas\AsaasWebhookService;
  6. use Illuminate\Support\Facades\Log;
  7. use Illuminate\Validation\ValidationException;
  8. /**
  9. * Conta Asaas da franqueadora (matriz). Linha única, editável pela UI —
  10. * a franqueadora pode trocar a própria chave sem depender do .env nem do suporte.
  11. */
  12. class CompanyPaymentAccountService
  13. {
  14. public function __construct(
  15. protected AsaasWebhookService $webhookService,
  16. ) {}
  17. public function current(): CompanyPaymentAccount
  18. {
  19. return CompanyPaymentAccount::current();
  20. }
  21. public function upsertAsaasApiKey(?string $apiKey): CompanyPaymentAccount
  22. {
  23. $apiKey = $apiKey !== null ? trim($apiKey) : null;
  24. $hasKey = $apiKey !== null && $apiKey !== '';
  25. $model = CompanyPaymentAccount::current();
  26. if (!$hasKey) {
  27. $this->removeWebhook($model);
  28. $model->asaas_api_key = null;
  29. $model->asaas_webhook_id = null;
  30. $model->status = CompanyPaymentAccount::STATUS_PENDING;
  31. $model->onboarded_at = null;
  32. $model->save();
  33. return $model->fresh();
  34. }
  35. if ($model->exists && $model->asaas_api_key === $apiKey && $model->asaas_webhook_id) {
  36. return $model->fresh();
  37. }
  38. try {
  39. $this->webhookService->validateKey($apiKey);
  40. } catch (AsaasException $e) {
  41. throw ValidationException::withMessages([
  42. 'asaas_api_key' => 'Chave Asaas inválida ou sem permissão. Verifique e tente novamente.',
  43. ]);
  44. }
  45. $this->removeWebhook($model);
  46. try {
  47. $webhookId = $this->webhookService->register($apiKey);
  48. } catch (AsaasException $e) {
  49. Log::error('Falha ao registrar webhook Asaas da matriz: ' . $e->getMessage());
  50. throw ValidationException::withMessages([
  51. 'asaas_api_key' => 'Não foi possível registrar o webhook na Asaas. Tente novamente.',
  52. ]);
  53. }
  54. $model->asaas_api_key = $apiKey;
  55. $model->asaas_webhook_id = $webhookId;
  56. $model->status = CompanyPaymentAccount::STATUS_ACTIVE;
  57. $model->onboarded_at = $model->onboarded_at ?? now();
  58. $model->save();
  59. return $model->fresh();
  60. }
  61. private function removeWebhook(CompanyPaymentAccount $model): void
  62. {
  63. if (!$model->asaas_api_key || !$model->asaas_webhook_id) {
  64. return;
  65. }
  66. try {
  67. $this->webhookService->delete($model->asaas_api_key, $model->asaas_webhook_id);
  68. } catch (\Throwable $e) {
  69. Log::warning('Não foi possível remover webhook Asaas da matriz: ' . $e->getMessage());
  70. }
  71. }
  72. }