| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303 |
- <?php
- namespace App\Services\Pagarme;
- use App\Models\Payment;
- use App\Models\PaymentTransfer;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- class PagarmePaymentService
- {
- public function createOrderWithCreditCard(
- Payment $payment, array $items, array $customer, array $creditCard, array $options = []
- ): array {
- $paymentMethod = [
- 'payment_method' => 'credit_card',
- 'credit_card' => $this->buildCreditCardPayload($creditCard),
- ];
- if (! empty($options['split']) && is_array($options['split'])) {
- $paymentMethod['split'] = $options['split'];
- }
- return $this->createOrder(
- payment: $payment,
- items: $items,
- customer: $customer,
- paymentMethod: $paymentMethod,
- options: $options,
- );
- }
- public function createOrderWithPix(
- Payment $payment,
- array $items,
- array $customer,
- array $pix,
- array $options = [],
- ): array {
- $paymentMethod = [
- 'payment_method' => 'pix',
- 'pix' => $this->buildPixPayload($pix),
- ];
- if (! empty($options['split']) && is_array($options['split'])) {
- $paymentMethod['split'] = $options['split'];
- }
- return $this->createOrder(
- payment: $payment,
- items: $items,
- customer: $customer,
- paymentMethod: $paymentMethod,
- options: $options,
- );
- }
- public function createOrder(
- Payment $payment,
- array $items,
- array $customer,
- array $paymentMethod,
- array $options = [],
- ): array {
- if (empty($items)) {
- throw new \InvalidArgumentException('items nao pode estar vazio.');
- }
- if (empty($paymentMethod['payment_method'])) {
- throw new \InvalidArgumentException('payment_method e obrigatorio.');
- }
- $payload = [
- 'code' => $options['order_code'] ?? "payment-{$payment->id}",
- 'items' => $items,
- 'customer' => $customer,
- 'payments' => [$paymentMethod],
- 'closed' => $options['closed'] ?? true,
- 'metadata' => array_merge([
- 'payment_id' => (string) $payment->id,
- 'schedule_id' => (string) $payment->schedule_id,
- 'client_id' => (string) $payment->client_id,
- 'provider_id' => (string) $payment->provider_id,
- ], $options['metadata'] ?? []),
- ];
- if (! empty($options['channel'])) {
- $payload['channel'] = $options['channel'];
- }
- $response = $this->pagarmeRequest($this->idempotencyKey($payment))
- ->post($this->pagarmeUrl('/orders'), $payload);
- if ($response->failed()) {
- Log::channel('pagarme')->error('Pagar.me order creation failed', [
- 'status' => $response->status(),
- 'body' => $response->json() ?? $response->body(),
- 'payload' => $payload,
- ]);
- throw new \RuntimeException('Erro ao criar pedido de pagamento no Pagar.me.');
- }
- $order = $response->json();
- if (empty($order['id'])) {
- Log::channel('pagarme')->error('Pagar.me order creation returned empty id', [
- 'payment_id' => $payment->id,
- 'response' => $order,
- ]);
- throw new \RuntimeException('Pagar.me order creation returned an empty id.');
- }
- return $order;
- }
- public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
- {
- $charge = $orderResponse['charges'][0] ?? [];
- $transaction = $charge['last_transaction'] ?? [];
- $chargeStatus = $charge['status'] ?? null;
- $transactionStatus = $transaction['status'] ?? null;
- $payment->forceFill([
- 'gateway_provider' => 'pagarme',
- 'gateway_entity_reference' => $charge['id'] ?? $orderResponse['id'] ?? null,
- 'gateway_entity_label' => isset($charge['id']) ? 'charge' : 'order',
- 'gateway_operation_reference' => $transaction['id'] ?? $charge['id'] ?? $orderResponse['id'] ?? null,
- 'gateway_operation_label' => isset($transaction['id']) ? 'transaction' : (isset($charge['id']) ? 'charge' : 'order'),
- 'status' => $this->mapPaymentStatus($chargeStatus, $transactionStatus),
- 'paid_at' => $charge['paid_at'] ?? null,
- 'authorized_at' => $this->resolveAuthorizedAt($transactionStatus, $transaction),
- 'gateway_payload' => $orderResponse,
- 'failure_code' => $this->extractFailureCode($transaction),
- 'failure_message' => $this->extractFailureMessage($transaction),
- ])->save();
- return $payment->fresh();
- }
- /**
- * @param Collection<int, PaymentTransfer> $transfers
- * @return array<int, array<string, mixed>>
- */
- public function buildSplitFromTransfers(Collection $transfers): array
- {
- return $transfers
- ->filter(fn (PaymentTransfer $transfer) => ! empty($transfer->gateway_transfer_target_reference))
- ->map(function (PaymentTransfer $transfer) {
- return [
- 'amount' => $this->toGatewayAmountInCents((float) $transfer->gross_amount),
- 'recipient_id' => $transfer->gateway_transfer_target_reference,
- 'type' => 'flat',
- ];
- })
- ->values()
- ->all();
- }
- public function toGatewayAmountInCents(float $amount): int
- {
- return (int) round($amount * 100);
- }
- //
- private function pagarmeUrl(string $path): string
- {
- return rtrim(config('services.pagarme.base_url'), '/').'/'.ltrim($path, '/');
- }
- private function idempotencyKey(Payment $payment): string
- {
- return "payment-{$payment->id}-schedule-{$payment->schedule_id}";
- }
- //
- private function buildCreditCardPayload(array $creditCard): array
- {
- $payload = [];
- foreach ([
- 'installments',
- 'statement_descriptor',
- 'operation_type',
- 'recurrence_cycle',
- 'metadata',
- 'extended_limit_enabled',
- 'extended_limit_code',
- 'merchant_category_code',
- 'authentication',
- 'auto_recovery',
- 'payload',
- 'payment_type',
- 'funding_source',
- 'initiated_type',
- 'recurrence_model',
- 'channel',
- 'payment_origin',
- ] as $field) {
- if (array_key_exists($field, $creditCard)) {
- $payload[$field] = $creditCard[$field];
- }
- }
- $allowedCardOptions = ['card', 'card_id', 'card_token', 'network_token'];
- $provided = array_values(array_filter(
- $allowedCardOptions,
- static fn (string $field) => ! empty($creditCard[$field])
- ));
- if (count($provided) !== 1) {
- throw new \InvalidArgumentException('Informe exatamente uma opcao entre card, card_id, card_token ou network_token.');
- }
- $selected = $provided[0];
- $payload[$selected] = $creditCard[$selected];
- return $payload;
- }
- private function buildPixPayload(array $pix): array
- {
- if (empty($pix['expires_in']) && empty($pix['expires_at'])) {
- throw new \InvalidArgumentException('pix.expires_in ou pix.expires_at e obrigatorio.');
- }
- $payload = [];
- foreach (['expires_in', 'expires_at', 'additional_information'] as $field) {
- if (array_key_exists($field, $pix)) {
- $payload[$field] = $pix[$field];
- }
- }
- return $payload;
- }
- //
- private function resolveAuthorizedAt(?string $transactionStatus, array $transaction): ?string
- {
- if (in_array($transactionStatus, ['authorized_pending_capture', 'captured', 'partial_capture'], true)) {
- return $transaction['created_at'] ?? now()->toISOString();
- }
- return null;
- }
- //
- private function extractFailureCode(array $transaction): ?string
- {
- return $transaction['gateway_response']['code'] ?? null;
- }
- private function extractFailureMessage(array $transaction): ?string
- {
- return $transaction['acquirer_message'] ?? null;
- }
- //
- private function mapPaymentStatus(?string $chargeStatus, ?string $transactionStatus): string
- {
- $status = strtolower((string) ($transactionStatus ?: $chargeStatus));
- return match ($status) {
- 'captured', 'paid' => 'paid',
- 'authorized_pending_capture', 'waiting_capture', 'pending' => 'authorized',
- 'processing' => 'processing',
- 'not_authorized', 'with_error', 'failed' => 'failed',
- 'voided', 'partial_void' => 'cancelled',
- default => 'pending',
- };
- }
- //
- private function pagarmeRequest(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',
- ]);
- }
- }
|