PagarmeCustomerService.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. ];
  39. if (! empty($phones)) {
  40. $payload['phones'] = $phones;
  41. }
  42. $response = $this->pagarmeRequest($client->id)
  43. ->post($this->pagarmeUrl('/customers'), $payload);
  44. if ($response->failed()) {
  45. Log::channel('pagarme')->error('Pagar.me customer creation failed', [
  46. 'status' => $response->status(),
  47. 'body' => $response->json() ?? $response->body(),
  48. 'payload' => $payload,
  49. ]);
  50. throw new \RuntimeException('Erro ao criar cliente no Pagar.me.');
  51. }
  52. $customerData = $response->json();
  53. $customerId = $customerData['id'] ?? null;
  54. if (! $customerId) {
  55. Log::channel('pagarme')->error('Customer creation returned an empty id.', [
  56. 'client_id' => $client->id,
  57. 'response' => $customerData,
  58. ]);
  59. throw new \RuntimeException('Customer creation returned an empty id.');
  60. }
  61. $client->forceFill([
  62. 'external_customer_id' => $customerId,
  63. 'external_customer_code' => $code,
  64. ])->save();
  65. return $customerId;
  66. }
  67. //
  68. private function pagarmeUrl(string $path): string
  69. {
  70. return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
  71. }
  72. private function idempotencyKey(int $clientId): string
  73. {
  74. return "client-{$clientId}-customer";
  75. }
  76. //
  77. private function buildAddress(array $data): array
  78. {
  79. $zipCode = $this->sanitizeDigits($data['zip_code'] ?? null);
  80. $street = (string) ($data['address'] ?? '');
  81. $number = (string) ($data['number'] ?? '0');
  82. $neighborhood = (string) ($data['district'] ?? '');
  83. $city = (string) ($data['city'] ?? '');
  84. $state = (string) ($data['state'] ?? '');
  85. $country = (string) ($data['country'] ?? 'BR');
  86. $complement = (string) ($data['complement'] ?? '');
  87. $line1Parts = array_filter([$number, $street, $neighborhood], static fn ($value) => $value !== '');
  88. $line1 = implode(', ', $line1Parts);
  89. $line2 = $complement ?: (string) ($data['instructions'] ?? '');
  90. return [
  91. 'line_1' => $line1,
  92. 'line_2' => $line2,
  93. 'zip_code' => $zipCode,
  94. 'city' => $city,
  95. 'state' => $state,
  96. 'country' => $country,
  97. ];
  98. }
  99. private function buildPhones(?string $phone): array
  100. {
  101. $digits = $this->sanitizeDigits($phone);
  102. if (empty($digits)) {
  103. return [];
  104. }
  105. $countryCode = '55';
  106. $areaCode = substr($digits, 0, 2);
  107. $number = substr($digits, 2);
  108. if (strlen($digits) <= 2) {
  109. $areaCode = '';
  110. $number = $digits;
  111. }
  112. return [
  113. 'mobile_phone' => [
  114. 'country_code' => $countryCode,
  115. 'area_code' => $areaCode,
  116. 'number' => $number,
  117. ],
  118. ];
  119. }
  120. //
  121. private function documentType(string $document): string
  122. {
  123. return strlen($document) === 14 ? 'CNPJ' : 'CPF';
  124. }
  125. private function personType(string $document): string
  126. {
  127. return strlen($document) === 14 ? 'company' : 'individual';
  128. }
  129. private function sanitizeDigits(?string $value): string
  130. {
  131. return preg_replace('/\D+/', '', (string) $value) ?? '';
  132. }
  133. //
  134. private function pagarmeRequest(int $clientId)
  135. {
  136. $secretKey = config('services.pagarme.secret_key');
  137. if (empty($secretKey)) {
  138. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  139. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  140. }
  141. return Http::withBasicAuth($secretKey, '')
  142. ->withHeaders([
  143. 'Idempotency-Key' => $this->idempotencyKey($clientId),
  144. 'Content-Type' => 'application/json',
  145. 'Accept' => 'application/json',
  146. ]);
  147. }
  148. }