| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
- namespace App\Services\Integrations\Asaas;
- use App\Models\Unit;
- use Exception;
- class AsaasCustomerService
- {
- protected AsaasClient $client;
- public function __construct(AsaasClient $client)
- {
- $this->client = $client;
- }
- /**
- * Garante que a Franquia exista como Customer (Cliente) na conta-mãe.
- * Retorna o ID do cliente no Asaas (cus_xxxxxx).
- */
- public function ensureFranchiseeCustomer(Unit $unit): string
- {
- $cpfCnpj = preg_replace('/[^0-9]/', '', $unit->cnpj);
- if (empty($cpfCnpj)) {
- throw new Exception("Unidade {$unit->fantasy_name} não possui CNPJ para ser cobrada.");
- }
- // Tenta buscar no Asaas se já existe o customer com esse CNPJ
- $existing = $this->client->get('/customers', ['cpfCnpj' => $cpfCnpj]);
- if (isset($existing['data']) && count($existing['data']) > 0) {
- return $existing['data'][0]['id'];
- }
- // Se não existe, cria um novo
- $payload = [
- 'name' => $unit->social_reason ?? $unit->fantasy_name ?? 'Franquia',
- 'cpfCnpj' => $cpfCnpj,
- 'email' => $unit->email,
- 'postalCode' => preg_replace('/[^0-9]/', '', $unit->postal_code),
- 'address' => $unit->street,
- 'addressNumber' => $unit->address_number ?? 'S/N',
- 'province' => $unit->neighborhood,
- ];
- $mobilePhone = preg_replace('/[^0-9]/', '', $unit->cell_number ?? $unit->phone_number ?? '');
-
- if (strlen($mobilePhone) >= 10 && strlen($mobilePhone) <= 11) {
- $payload['mobilePhone'] = $mobilePhone;
- }
- $response = $this->client->post('/customers', $payload);
- return $response['id'];
- }
- /**
- * Garante que o Aluno exista como Customer na Subconta da Franquia.
- * Retorna o ID do cliente no Asaas (cus_xxxxxx).
- */
- public function ensureStudentCustomer(\App\Models\Student $student, string $apiKey): string
- {
- $client = new AsaasClient($apiKey);
- $cpf = preg_replace('/[^0-9]/', '', $student->document_number);
- if (empty($cpf)) {
- throw new Exception("Aluno {$student->name} não possui CPF cadastrado para cobrança.");
- }
- // Tenta buscar no Asaas se já existe
- $existing = $client->get('/customers', ['cpfCnpj' => $cpf]);
- if (isset($existing['data']) && count($existing['data']) > 0) {
- return $existing['data'][0]['id'];
- }
- // Se não existe, cria um novo
- $payload = [
- 'name' => $student->name,
- 'cpfCnpj' => $cpf,
- 'email' => $student->email,
- 'postalCode' => preg_replace('/[^0-9]/', '', $student->postal_code ?? ''),
- 'address' => $student->street,
- 'addressNumber' => $student->address_number ?? 'S/N',
- 'province' => $student->neighborhood,
- ];
- $mobilePhone = preg_replace('/[^0-9]/', '', $student->phone ?? '');
-
- if (strlen($mobilePhone) >= 10 && strlen($mobilePhone) <= 11) {
- $payload['mobilePhone'] = $mobilePhone;
- }
- $response = $client->post('/customers', $payload);
- return $response['id'];
- }
- }
|