SendsPagarmeRequests.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. return $response->json() ?? [];
  23. } catch (Throwable $e) {
  24. Log::channel('pagarme')->error('Pagar.me request failed', [
  25. 'method' => strtoupper($method),
  26. 'endpoint' => $endpoint,
  27. 'payload' => $payload,
  28. 'exception' => $e->getMessage(),
  29. ]);
  30. }
  31. }
  32. protected function pagarmeHttp(string $idempotencyKey)
  33. {
  34. $secretKey = config('services.pagarme.secret_key');
  35. if (empty($secretKey)) {
  36. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  37. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  38. }
  39. return Http::withBasicAuth($secretKey, '')
  40. ->withHeaders([
  41. 'Idempotency-Key' => $idempotencyKey,
  42. 'Content-Type' => 'application/json',
  43. 'Accept' => 'application/json',
  44. ]);
  45. }
  46. protected function pagarmeUrl(string $path): string
  47. {
  48. return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
  49. }
  50. }