SendsPagarmeRequests.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. Log::channel('pagarme')->error('Pagar.me request failed', [
  32. 'method' => strtoupper($method),
  33. 'endpoint' => $endpoint,
  34. 'origin_ip' => $this->pagarmeOriginIp(),
  35. 'payload' => $payload,
  36. 'exception' => $e->getMessage(),
  37. 'result' => $responseBody,
  38. ]);
  39. throw new \RuntimeException($errorMessage, previous: $e);
  40. }
  41. }
  42. protected function pagarmeHttp(string $idempotencyKey)
  43. {
  44. $secretKey = config('services.pagarme.secret_key');
  45. if (empty($secretKey)) {
  46. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  47. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  48. }
  49. return Http::withBasicAuth($secretKey, '')
  50. ->withHeaders([
  51. 'Idempotency-Key' => $idempotencyKey,
  52. 'Content-Type' => 'application/json',
  53. 'Accept' => 'application/json',
  54. ]);
  55. }
  56. protected function pagarmeUrl(string $path): string
  57. {
  58. return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
  59. }
  60. protected function pagarmeOriginIp(): ?string
  61. {
  62. try {
  63. return trim(Http::timeout(3)->get('https://api.ipify.org')->body()) ?: null;
  64. } catch (Throwable) {
  65. return null;
  66. }
  67. }
  68. }