'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.'); } if (! in_array($paymentMethod['payment_method'], ['credit_card', 'pix'], true)) { throw new \InvalidArgumentException('payment_method deve ser credit_card ou pix.'); } $customerPayload = $options['customer_id'] ?? null; if (! $this->filled($customerPayload)) { $customerPayload = $this->filterFilledRecursive($customer); } if (empty($customerPayload)) { throw new \InvalidArgumentException('customer ou customer_id e obrigatorio.'); } $payload = [ 'code' => $options['order_code'] ?? "payment-{$payment->id}", 'items' => $this->validateItems($items), 'payments' => [$this->filterFilledRecursive($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 (is_string($customerPayload)) { $payload['customer_id'] = $customerPayload; } else { $payload['customer'] = $customerPayload; } 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' => $this->filledArrayValue($charge, 'paid_at'), '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 $transfers * @return array> */ 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', 'options' => [ 'charge_processing_fee' => false, 'charge_remainder_fee' => false, 'liable' => false, ], ]; }) ->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) && $this->filled($creditCard[$field])) { $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 (! $this->filled($pix['expires_in'] ?? null) && ! $this->filled($pix['expires_at'] ?? null)) { 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) && $this->filled($pix[$field])) { $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 $this->filledArrayValue($transaction, 'created_at'); } return null; } // private function extractFailureCode(array $transaction): ?string { return $this->filledArrayValue($transaction['gateway_response'] ?? [], 'code'); } private function extractFailureMessage(array $transaction): ?string { return $this->filledArrayValue($transaction, 'acquirer_message'); } /** * @param array> $items * @return array> */ private function validateItems(array $items): array { return collect($items) ->map(function (array $item, int $index) { foreach (['code', 'amount', 'quantity'] as $field) { if (! array_key_exists($field, $item) || ! $this->filled($item[$field])) { throw new \InvalidArgumentException("items.{$index}.{$field} e obrigatorio."); } } if ((int) $item['amount'] <= 0 || (int) $item['quantity'] <= 0) { throw new \InvalidArgumentException("items.{$index}.amount e quantity devem ser maiores que zero."); } return $this->filterFilledRecursive($item); }) ->values() ->all(); } private function filledArrayValue(array $data, string $field): ?string { if (! array_key_exists($field, $data) || ! $this->filled($data[$field])) { return null; } return (string) $data[$field]; } /** * @param array $data * @return array */ private function filterFilledRecursive(array $data): array { $filtered = []; foreach ($data as $key => $value) { if (is_array($value)) { $value = $this->filterFilledRecursive($value); } if ($this->filled($value)) { $filtered[$key] = $value; } } return $filtered; } private function filled(mixed $value): bool { return $value !== null && $value !== '' && $value !== []; } // 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', ]); } }