AsaasCustomerService.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Services\Integrations\Asaas;
  3. use App\Models\Unit;
  4. use Exception;
  5. class AsaasCustomerService
  6. {
  7. protected AsaasClient $client;
  8. public function __construct(AsaasClient $client)
  9. {
  10. $this->client = $client;
  11. }
  12. /**
  13. * Garante que a Franquia exista como Customer (Cliente) na conta-mãe.
  14. * Retorna o ID do cliente no Asaas (cus_xxxxxx).
  15. */
  16. public function ensureFranchiseeCustomer(Unit $unit): string
  17. {
  18. $cpfCnpj = preg_replace('/[^0-9]/', '', $unit->cnpj);
  19. if (empty($cpfCnpj)) {
  20. throw new Exception("Unidade {$unit->fantasy_name} não possui CNPJ para ser cobrada.");
  21. }
  22. // 1. Tenta buscar no Asaas se já existe o customer com esse CNPJ
  23. $existing = $this->client->get('/customers', ['cpfCnpj' => $cpfCnpj]);
  24. if (isset($existing['data']) && count($existing['data']) > 0) {
  25. return $existing['data'][0]['id'];
  26. }
  27. // 2. Se não existe, cria um novo
  28. $payload = [
  29. 'name' => $unit->social_reason ?? $unit->fantasy_name ?? 'Franquia',
  30. 'cpfCnpj' => $cpfCnpj,
  31. 'email' => $unit->email,
  32. 'postalCode' => preg_replace('/[^0-9]/', '', $unit->postal_code),
  33. 'address' => $unit->street,
  34. 'addressNumber' => $unit->address_number ?? 'S/N',
  35. 'province' => $unit->neighborhood,
  36. ];
  37. // Só envia telefone se for um número que pareça válido (10 a 11 dígitos),
  38. // para não travar a API do Asaas com lixo do cadastro.
  39. $mobilePhone = preg_replace('/[^0-9]/', '', $unit->cell_number ?? $unit->phone_number ?? '');
  40. if (strlen($mobilePhone) >= 10 && strlen($mobilePhone) <= 11) {
  41. $payload['mobilePhone'] = $mobilePhone;
  42. }
  43. $response = $this->client->post('/customers', $payload);
  44. return $response['id'];
  45. }
  46. }