SendsPagarmeRequests.php 2.8 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 = method_exists($e, 'getResponse') ? $e->getResponse()?->json() : null;
  31. $errorDetail = $errorMessage;
  32. if ($responseBody) {
  33. $errorDetail .= ' | '.json_encode($responseBody);
  34. }
  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($errorDetail, 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. }