| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace App\Services\Pagarme\Concerns;
- use App\Data\Pagarme\PagarmeData;
- 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|PagarmeData $payload,
- ): array {
- $payload = $payload instanceof PagarmeData ? $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,
- '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,
- '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, '/');
- }
- }
|