PagarmeCustomerService.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. <?php
  2. namespace App\Services\Pagarme;
  3. use App\Models\Client;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Support\Facades\Log;
  6. class PagarmeCustomerService
  7. {
  8. public function createCustomerForClient(Client $client, array $data): ?string
  9. {
  10. if (!empty($client->external_customer_id)) {
  11. return $client->external_customer_id;
  12. }
  13. $client->loadMissing('user');
  14. $name = $client->user?->name ?? $data['name'] ?? 'Cliente';
  15. $email = $client->user?->email ?? $data['email'] ?? null;
  16. $document = $this->sanitizeDigits($client->document ?? $data['document'] ?? null);
  17. if (empty($email) || empty($document)) {
  18. Log::channel('pagarme')->warning(
  19. 'Skipping customer creation because the client is missing email or document.',
  20. [
  21. 'client_id' => $client->id,
  22. 'user_id' => $client->user_id,
  23. ]
  24. );
  25. return null;
  26. }
  27. $address = $this->buildAddress($data);
  28. $phones = $this->buildPhones($client->user?->phone ?? $data['phone'] ?? null);
  29. $code = $client->external_customer_code ?? "client-{$client->id}";
  30. $payload = [
  31. 'name' => $name,
  32. 'email' => $email,
  33. 'document' => $document,
  34. 'type' => $this->personType($document),
  35. 'document_type' => $this->documentType($document),
  36. 'code' => $code,
  37. 'address' => $address,
  38. 'phones' => $phones,
  39. 'metadata' => [
  40. 'client_id' => (string) $client->id,
  41. 'user_id' => (string) ($client->user_id ?? ''),
  42. ],
  43. ];
  44. $response = $this->pagarmeRequest($client->id)
  45. ->post($this->pagarmeUrl('/customers'), $payload);
  46. if ($response->failed()) {
  47. Log::channel('pagarme')->error('Pagar.me customer creation failed', [
  48. 'status' => $response->status(),
  49. 'body' => $response->json() ?? $response->body(),
  50. 'client' => [
  51. 'id' => $client->id,
  52. 'email' => $email,
  53. 'document' => $document,
  54. ],
  55. ]);
  56. throw new \RuntimeException('Erro ao criar cliente no Pagar.me.');
  57. }
  58. $customerData = $response->json();
  59. $customerId = $customerData['id'] ?? null;
  60. if (!$customerId) {
  61. Log::channel('pagarme')->error('Customer creation returned an empty id.', [
  62. 'client_id' => $client->id,
  63. 'response' => $customerData,
  64. ]);
  65. throw new \RuntimeException('Customer creation returned an empty id.');
  66. }
  67. $client->forceFill([
  68. 'external_customer_id' => $customerId,
  69. 'external_customer_code' => $code,
  70. ])->save();
  71. return $customerId;
  72. }
  73. //
  74. private function pagarmeUrl(string $path): string
  75. {
  76. return rtrim(config('services.pagarme.base_url'), '/') . '/' . ltrim($path, '/');
  77. }
  78. private function idempotencyKey(int $clientId): string
  79. {
  80. return "client-{$clientId}-customer";
  81. }
  82. //
  83. private function buildAddress(array $data): array
  84. {
  85. $zipCode = $this->sanitizeDigits($data['zip_code'] ?? null);
  86. $street = (string) ($data['address'] ?? '');
  87. $number = (string) ($data['number'] ?? '0');
  88. $neighborhood = (string) ($data['district'] ?? '');
  89. $city = (string) ($data['city'] ?? '');
  90. $state = (string) ($data['state'] ?? '');
  91. $country = (string) ($data['country'] ?? 'BR');
  92. $complement = (string) ($data['complement'] ?? '');
  93. $line1Parts = array_filter([$number, $street, $neighborhood], static fn ($value) => $value !== '');
  94. $line1 = implode(', ', $line1Parts);
  95. $line2 = $complement ?: (string) ($data['instructions'] ?? '');
  96. return [
  97. 'street' => $street,
  98. 'number' => $number,
  99. 'zip_code' => $zipCode,
  100. 'neighborhood' => $neighborhood,
  101. 'city' => $city,
  102. 'state' => $state,
  103. 'country' => $country,
  104. 'complement' => $complement,
  105. 'line_1' => $line1,
  106. 'line_2' => $line2,
  107. 'metadata' => [
  108. 'source' => 'register-client',
  109. ],
  110. ];
  111. }
  112. private function buildPhones(?string $phone): array
  113. {
  114. $digits = $this->sanitizeDigits($phone);
  115. if (empty($digits)) {
  116. return [];
  117. }
  118. $countryCode = '55';
  119. $areaCode = substr($digits, 0, 2);
  120. $number = substr($digits, 2);
  121. if (strlen($digits) <= 2) {
  122. $areaCode = '';
  123. $number = $digits;
  124. }
  125. return [
  126. 'mobile_phone' => [
  127. 'country_code' => $countryCode,
  128. 'area_code' => $areaCode,
  129. 'number' => $number,
  130. 'type' => 'mobile',
  131. ],
  132. ];
  133. }
  134. //
  135. private function documentType(string $document): string
  136. {
  137. return strlen($document) === 14 ? 'CNPJ' : 'CPF';
  138. }
  139. private function personType(string $document): string
  140. {
  141. return strlen($document) === 14 ? 'company' : 'individual';
  142. }
  143. private function sanitizeDigits(?string $value): string
  144. {
  145. return preg_replace('/\D+/', '', (string) $value) ?? '';
  146. }
  147. //
  148. private function pagarmeRequest(int $clientId)
  149. {
  150. $secretKey = config('services.pagarme.secret_key');
  151. if (empty($secretKey)) {
  152. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  153. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  154. }
  155. return Http::withBasicAuth($secretKey, '')
  156. ->withHeaders([
  157. 'Idempotency-Key' => $this->idempotencyKey($clientId),
  158. 'Content-Type' => 'application/json',
  159. 'Accept' => 'application/json',
  160. ]);
  161. }
  162. }