'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 $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', ]; }) ->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', ]); } }