| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace App\Services\Pagarme\Concerns;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- use Throwable;
- trait SendsPagarmeRequests
- {
- protected function pagarmeRequest(
- string $method,
- string $path,
- string $idempotencyKey,
- string $errorMessage,
- array|Data $payload,
- ): array {
- $payload = $payload instanceof Data ? $payload->toArray() : $payload;
- $endpoint = $this->pagarmeUrl($path);
- try {
- $response = $this->pagarmeHttp($idempotencyKey)
- ->send($method, $endpoint, ['json' => $payload])
- ->throw();
- $result = $response->json() ?? [];
- if (app()->environment('local', 'development')) {
- Log::channel('pagarme')->info('Pagar.me request succeeded', [
- 'method' => strtoupper($method),
- 'endpoint' => $endpoint,
- 'origin_ip' => $this->pagarmeOriginIp(),
- 'payload' => $payload,
- 'result' => $result,
- ]);
- }
- return $result;
- } catch (Throwable $e) {
- $responseBody = method_exists($e, 'getResponse') ? $e->getResponse()?->json() : null;
- Log::channel('pagarme')->error('Pagar.me request failed', [
- 'method' => strtoupper($method),
- 'endpoint' => $endpoint,
- 'origin_ip' => $this->pagarmeOriginIp(),
- 'payload' => $payload,
- 'exception' => $e->getMessage(),
- 'result' => $responseBody,
- ]);
- throw new \RuntimeException($errorMessage, previous: $e);
- }
- }
- protected function pagarmeHttp(string $idempotencyKey)
- {
- $secretKey = config('services.pagarme.secret_key');
- if (empty($secretKey)) {
- Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
- throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
- }
- return Http::withBasicAuth($secretKey, '')
- ->withHeaders([
- 'Idempotency-Key' => $idempotencyKey,
- 'Content-Type' => 'application/json',
- 'Accept' => 'application/json',
- ]);
- }
- protected function pagarmeUrl(string $path): string
- {
- return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
- }
- protected function pagarmeOriginIp(): ?string
- {
- try {
- return trim(Http::timeout(3)->get('https://api.ipify.org')->body()) ?: null;
- } catch (Throwable) {
- return null;
- }
- }
- }
|