| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256 |
- <?php
- namespace App\Services\Pagarme;
- use App\Models\Client;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- class PagarmeCustomerService
- {
- public function createCustomerForClient(Client $client, array $data): ?string
- {
- if (! empty($client->external_customer_id)) {
- return $client->external_customer_id;
- }
- $client->loadMissing('user');
- $name = $client->user?->name ?? $data['name'] ?? 'Cliente';
- $email = $client->user?->email ?? $data['email'] ?? null;
- $document = $this->sanitizeDigits($client->document ?? $data['document'] ?? null);
- if (empty($email) || empty($document)) {
- Log::channel('pagarme')->warning(
- 'Skipping customer creation because the client is missing email or document.',
- [
- 'client_id' => $client->id,
- 'user_id' => $client->user_id,
- ]
- );
- return null;
- }
- $address = $this->buildAddress($data);
- $phones = $this->buildPhones($client->user?->phone ?? $data['phone'] ?? null);
- $code = $client->external_customer_code ?? "client-{$client->id}";
- $payload = $this->filterFilledRecursive([
- 'name' => $name,
- 'email' => $email,
- 'document' => $document,
- 'type' => $this->personType($document),
- 'document_type' => $this->documentType($document),
- 'code' => $code,
- 'address' => $address,
- ]);
- if (! empty($phones)) {
- $payload['phones'] = $phones;
- }
- $endpoint = $this->pagarmeUrl('/customers');
- PagarmeHttpLogger::logRequest('POST', $endpoint, $payload);
- $response = $this->pagarmeRequest($client->id)
- ->post($endpoint, $payload);
- if ($response->failed()) {
- Log::channel('pagarme')->error('Pagar.me customer creation failed', [
- 'status' => $response->status(),
- 'body' => $response->json() ?? $response->body(),
- 'payload' => $payload,
- ]);
- throw new \RuntimeException('Erro ao criar cliente no Pagar.me.');
- }
- $customerData = $response->json();
- $customerId = $customerData['id'] ?? null;
- if (! $customerId) {
- Log::channel('pagarme')->error('Customer creation returned an empty id.', [
- 'client_id' => $client->id,
- 'response' => $customerData,
- ]);
- throw new \RuntimeException('Customer creation returned an empty id.');
- }
- $client->forceFill([
- 'external_customer_id' => $customerId,
- 'external_customer_code' => $code,
- ])->save();
- return $customerId;
- }
- //
- public function updateCustomer(string $customerId, int $clientId, array $data): void
- {
- $payload = $this->filterFilledRecursive([
- 'name' => $data['name'] ?? null,
- 'email' => $data['email'] ?? null,
- 'document' => $this->sanitizeDigits($data['document'] ?? null),
- 'type' => $data['type'] ?? null,
- 'document_type' => $data['document_type'] ?? null,
- 'code' => $data['code'] ?? null,
- 'address' => $data['address'] ?? null,
- 'phones' => $data['phones'] ?? null,
- ]);
- if (empty($payload)) {
- return;
- }
- $endpoint = $this->pagarmeUrl("/customers/{$customerId}");
- PagarmeHttpLogger::logRequest('PATCH', $endpoint, $payload);
- $request = $this->pagarmeRequest($clientId, "customer-update-{$customerId}");
- $response = $request->patch($endpoint, $payload);
- if ($response->status() === 405) {
- PagarmeHttpLogger::logRequest('PUT', $endpoint, $payload);
- $response = $request->put($endpoint, $payload);
- }
- if ($response->failed()) {
- Log::channel('pagarme')->error('Pagar.me customer update failed', [
- 'status' => $response->status(),
- 'body' => $response->json() ?? $response->body(),
- 'payload' => $payload,
- 'customer_id' => $customerId,
- 'client_id' => $clientId,
- ]);
- throw new \RuntimeException('Erro ao atualizar cliente no Pagar.me.');
- }
- }
- //
- private function idempotencyKey(int $clientId, string $suffix = 'customer'): string
- {
- return "client-{$clientId}-{$suffix}";
- }
- private function pagarmeRequest(int $clientId, string $suffix = 'customer')
- {
- $secretKey = config('services.pagarme.secret_key');
- if (empty($secretKey)) {
- Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
- throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
- }
- return Http::withBasicAuth($secretKey, '')
- ->withHeaders([
- 'Idempotency-Key' => $this->idempotencyKey($clientId, $suffix),
- 'Content-Type' => 'application/json',
- 'Accept' => 'application/json',
- ]);
- }
- private function pagarmeUrl(string $path): string
- {
- return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
- }
- //
- private function buildAddress(array $data): array
- {
- $zipCode = $this->sanitizeDigits($data['zip_code'] ?? null);
- $street = (string) ($data['address'] ?? '');
- $number = (string) ($data['number'] ?? '0');
- $neighborhood = (string) ($data['district'] ?? '');
- $city = (string) ($data['city'] ?? '');
- $state = (string) ($data['state'] ?? '');
- $country = (string) ($data['country'] ?? 'BR');
- $complement = (string) ($data['complement'] ?? '');
- $line1Parts = array_filter([$number, $street, $neighborhood], static fn ($value) => $value !== '');
- $line1 = implode(', ', $line1Parts);
- $line2 = $complement ?: (string) ($data['instructions'] ?? '');
- return [
- 'line_1' => $line1,
- 'line_2' => $line2,
- 'zip_code' => $zipCode,
- 'city' => $city,
- 'state' => $state,
- 'country' => $country,
- ];
- }
- private function buildPhones(?string $phone): array
- {
- $digits = $this->sanitizeDigits($phone);
- if (empty($digits)) {
- return [];
- }
- $countryCode = '55';
- $areaCode = substr($digits, 0, 2);
- $number = substr($digits, 2);
- if (strlen($digits) <= 2) {
- $areaCode = '';
- $number = $digits;
- }
- return [
- 'mobile_phone' => [
- 'country_code' => $countryCode,
- 'area_code' => $areaCode,
- 'number' => $number,
- ],
- ];
- }
- private function documentType(string $document): string
- {
- return strlen($document) === 14 ? 'CNPJ' : 'CPF';
- }
- private function filterFilledRecursive(array $data): array
- {
- $filtered = [];
- foreach ($data as $key => $value) {
- if (is_array($value)) {
- $value = $this->filterFilledRecursive($value);
- }
- if ($value !== null && $value !== '' && $value !== []) {
- $filtered[$key] = $value;
- }
- }
- return $filtered;
- }
- private function personType(string $document): string
- {
- return strlen($document) === 14 ? 'company' : 'individual';
- }
- private function sanitizeDigits(?string $value): string
- {
- return preg_replace('/\D+/', '', (string) $value) ?? '';
- }
- }
|