SendsPagarmeRequests.php 2.7 KB

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