AsaasAccountService.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Services\Integrations\Asaas;
  3. use App\Models\Unit;
  4. use App\Models\UnitPaymentAccount;
  5. use Exception;
  6. class AsaasAccountService
  7. {
  8. protected AsaasClient $client;
  9. public function __construct(AsaasClient $client)
  10. {
  11. $this->client = $client;
  12. }
  13. public function ensureSubaccount(Unit $unit): UnitPaymentAccount
  14. {
  15. $existingAccount = UnitPaymentAccount::where('unit_id', $unit->id)->first();
  16. if ($existingAccount && $existingAccount->asaas_account_id) {
  17. return $existingAccount;
  18. }
  19. if (empty($unit->cnpj)) {
  20. throw new Exception("A unidade {$unit->fantasy_name} não possui um CNPJ cadastrado. O CNPJ é obrigatório para criar a subconta.");
  21. }
  22. $payload = [
  23. 'name' => $unit->fantasy_name ?? $unit->social_reason ?? 'Unidade Ginástica do Cérebro',
  24. 'email' => $unit->email,
  25. 'cpfCnpj' => preg_replace('/[^0-9]/', '', $unit->cnpj),
  26. 'mobilePhone' => preg_replace('/[^0-9]/', '', $unit->cell_number ?? $unit->phone_number ?? ''),
  27. 'address' => $unit->street,
  28. 'addressNumber' => $unit->address_number ?? 'S/N',
  29. 'province' => $unit->neighborhood,
  30. 'postalCode' => preg_replace('/[^0-9]/', '', $unit->postal_code),
  31. 'companyType' => 'LIMITED',
  32. 'incomeValue' => 10000.00, // Renda/Faturamento exigido pelo Asaas
  33. ];
  34. $response = $this->client->post('/accounts', $payload);
  35. return UnitPaymentAccount::updateOrCreate(
  36. ['unit_id' => $unit->id],
  37. [
  38. 'asaas_account_id' => $response['id'],
  39. 'asaas_wallet_id' => $response['walletId'],
  40. 'asaas_api_key' => \Illuminate\Support\Facades\Crypt::encryptString($response['apiKey']),
  41. 'status' => 'ACTIVE',
  42. 'onboarded_at' => now(),
  43. ]
  44. );
  45. }
  46. }