| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <?php
- namespace App\Services\Integrations\Asaas;
- use App\Models\Unit;
- use App\Models\UnitPaymentAccount;
- use Exception;
- class AsaasAccountService
- {
- protected AsaasClient $client;
- public function __construct(AsaasClient $client)
- {
- $this->client = $client;
- }
- public function ensureSubaccount(Unit $unit): UnitPaymentAccount
- {
- $existingAccount = UnitPaymentAccount::where('unit_id', $unit->id)->first();
-
- if ($existingAccount && $existingAccount->asaas_account_id) {
- return $existingAccount;
- }
- if (empty($unit->cnpj)) {
- throw new Exception("A unidade {$unit->fantasy_name} não possui um CNPJ cadastrado. O CNPJ é obrigatório para criar a subconta.");
- }
- $payload = [
- 'name' => $unit->fantasy_name ?? $unit->social_reason ?? 'Unidade Ginástica do Cérebro',
- 'email' => $unit->email,
- 'cpfCnpj' => preg_replace('/[^0-9]/', '', $unit->cnpj),
- 'mobilePhone' => preg_replace('/[^0-9]/', '', $unit->cell_number ?? $unit->phone_number ?? ''),
- 'address' => $unit->street,
- 'addressNumber' => $unit->address_number ?? 'S/N',
- 'province' => $unit->neighborhood,
- 'postalCode' => preg_replace('/[^0-9]/', '', $unit->postal_code),
- 'companyType' => 'LIMITED',
- 'incomeValue' => 10000.00, // Renda/Faturamento exigido pelo Asaas
- ];
- $response = $this->client->post('/accounts', $payload);
- return UnitPaymentAccount::updateOrCreate(
- ['unit_id' => $unit->id],
- [
- 'asaas_account_id' => $response['id'],
- 'asaas_wallet_id' => $response['walletId'],
- 'asaas_api_key' => \Illuminate\Support\Facades\Crypt::encryptString($response['apiKey']),
- 'status' => 'ACTIVE',
- 'onboarded_at' => now(),
- ]
- );
- }
- }
|