SendsPagarmeRequests.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. $result = $response->json() ?? [];
  23. if (app()->environment('local', 'development')) {
  24. Log::channel('pagarme')->info('Pagar.me request succeeded', [
  25. 'method' => strtoupper($method),
  26. 'endpoint' => $endpoint,
  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. 'payload' => $payload,
  38. 'exception' => $e->getMessage(),
  39. 'result' => $responseBody,
  40. ]);
  41. throw new \RuntimeException($errorMessage, previous: $e);
  42. }
  43. }
  44. protected function pagarmeHttp(string $idempotencyKey)
  45. {
  46. $secretKey = config('services.pagarme.secret_key');
  47. if (empty($secretKey)) {
  48. Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
  49. throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
  50. }
  51. return Http::withBasicAuth($secretKey, '')
  52. ->withHeaders([
  53. 'Idempotency-Key' => $idempotencyKey,
  54. 'Content-Type' => 'application/json',
  55. 'Accept' => 'application/json',
  56. ]);
  57. }
  58. protected function pagarmeUrl(string $path): string
  59. {
  60. return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
  61. }
  62. }