SendsPagarmeRequests.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Services\Pagarme\Concerns;
  3. use App\Data\Pagarme\PagarmeData;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Support\Facades\Log;
  6. use Throwable;
  7. trait SendsPagarmeRequests
  8. {
  9. protected function pagarmeRequest(
  10. string $method,
  11. string $path,
  12. string $idempotencyKey,
  13. string $errorMessage,
  14. array|PagarmeData $payload,
  15. ): array {
  16. $payload = $payload instanceof PagarmeData ? $payload->toArray() : $payload;
  17. $endpoint = $this->pagarmeUrl($path);
  18. try {
  19. $response = $this->pagarmeHttp($idempotencyKey)
  20. ->send($method, $endpoint, ['json' => $payload])
  21. ->throw();
  22. $result = $response->json() ?? [];
  23. if (app()->environment('local', 'development')) {
  24. Log::channel('pagarme')->info('Pagar.me request succeeded', [
  25. 'method' => strtoupper($method),
  26. 'endpoint' => $endpoint,
  27. 'origin_ip' => $this->pagarmeOriginIp(),
  28. 'payload' => $payload,
  29. 'result' => $result,
  30. ]);
  31. }
  32. return $result;
  33. } catch (Throwable $e) {
  34. $responseBody = method_exists($e, 'getResponse') ? $e->getResponse()?->json() : null;
  35. Log::channel('pagarme')->error('Pagar.me request failed', [
  36. 'method' => strtoupper($method),
  37. 'endpoint' => $endpoint,
  38. 'origin_ip' => $this->pagarmeOriginIp(),
  39. 'payload' => $payload,
  40. 'exception' => $e->getMessage(),
  41. 'result' => $responseBody,
  42. ]);
  43. throw new \RuntimeException($errorMessage, previous: $e);
  44. }
  45. }
  46. protected function pagarmeHttp(string $idempotencyKey)
  47. {
  48. $secretKey = config('services.pagarme.secret_key');
  49. if (empty($secretKey)) {
  50. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  51. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  52. }
  53. return Http::withBasicAuth($secretKey, '')
  54. ->withHeaders([
  55. 'Idempotency-Key' => $idempotencyKey,
  56. 'Content-Type' => 'application/json',
  57. 'Accept' => 'application/json',
  58. ]);
  59. }
  60. protected function pagarmeUrl(string $path): string
  61. {
  62. return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
  63. }
  64. protected function pagarmeOriginIp(): ?string
  65. {
  66. try {
  67. return trim(Http::timeout(3)->get('https://api.ipify.org')->body()) ?: null;
  68. } catch (Throwable) {
  69. return null;
  70. }
  71. }
  72. }