SendsPagarmeRequests.php 2.9 KB

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