HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/comfama.sports-crowd.com/app/Http/Controllers/CulqiController.php
<?php

namespace App\Http\Controllers;

use App\Address;
use App\Http\Controllers\Interfaces\PaymentGatewayControllerInterface;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\PaymentGatewayBridgeController;

class CulqiController extends PaymentGatewayBridgeController implements PaymentGatewayControllerInterface
{
    private $util;

    public function __construct()
    {
        $this->determinateWebService('Culqi_prd', 'Culqi_sandbox');
        $this->util = new UtilController();
    }

    public function index($order)
    {
        if ($order->gw_state == 'CONFIRMED') {
            return $this->webcheckoutDone($order);
        }

        $data = [
            'price' => $order->total_price * 100, //Valor en centimos
            'reference' => $order->gw_code_transaction,
            'origin' => 'order',
            'client_id' => $order->client_id,
            'gateway_payments_id' => $order->gateway_payments_id
        ];

        $this->updatePendingStatus($order);
        return view('culqi.webcheckout')
            ->with('apiKey', $this->publicKey)
            ->with('currency', $this->currency)
            ->with('data', $data)
            ->with('team', $this->team);
    }

    public function ticketIndex($ticket)
    {
        if ($ticket->payment_state == 'CONFIRMED') {
            return $this->webcheckoutDone(null, $ticket);
        }

        $data = [
            'price' => $ticket->total * 100, //Valor en centimos
            'reference' => $ticket->payment_reference,
            'origin' => 'ticket',
            'client_id' => $ticket->user_id_log,
            'gateway_payments_id' => $ticket->gateway_payments_id
        ];

        $this->updatePendingStatus($ticket);
        return view('culqi.webcheckout')
            ->with('apiKey', $this->publicKey)
            ->with('currency', $this->currency)
            ->with('data', $data)
            ->with('team', $this->team);
    }

    public function genericIndex($paymentTransaction, $price, $origin, $clientId, $description)
    {
        if ($paymentTransaction->state == 'CONFIRMED') {
            return $this->webcheckoutDone(null, $paymentTransaction);
        }

        $data = [
            'price' => $price * 100, //Valor en centimos
            'reference' => $paymentTransaction->reference,
            'origin' => $origin,
            'client_id' => $clientId,
            'gateway_payments_id' => $paymentTransaction->gateway_payments_id
        ];

        return view('culqi.webcheckout')
            ->with('apiKey', $this->publicKey)
            ->with('currency', $this->currency)
            ->with('data', $data)
            ->with('team', $this->team);
    }

    public function payment(Request $request)
    {
        $token = $request['token'];
        $email = $request['email'];
        $amount = $request['amount'];
        $paymentReference = $request['order'];
        $origin = $request['origin'];
        $clientId = $request['clientId'];

        $client = User::find($clientId)->first();
        $clientAddress = Address::where([['user_id', $clientId], ['last_used', 1]])->with('city')->first();

        if ($client && $clientAddress) {
            $body = array(
                "amount" => $amount,
                "currency_code" => $this->currency,
                "email" => $email,
                "antifraud_details" => array(
                    "address" => $clientAddress->direction,
                    "address_city" => $clientAddress->city->name,
                    "country_code" => strtoupper(substr($clientAddress->city->state->country->name, 0, 2)),
                    "first_name" => $client->first_name,
                    "last_name" => $client->last_name,
                    "phone_number" => $client->phone,
                ),
                "source_id" => $token,
                "metadata" => array(
                    "order_id" => $paymentReference
                )
            );
        } else {
            $body = array('product' => array(
                "amount" => $amount,
                "currency_code" => $this->currency,
                "email" => $email,
                "source_id" => $token,
                "metadata" => array(
                    "order_id" => $paymentReference
                )
            ));
        }

        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->post($this->urlApi . "/charges", [
                \GuzzleHttp\RequestOptions::JSON      => $body,
                'headers' => ['Authorization' => 'Bearer ' . $this->privateKey]
            ]);

            $body = (string) $response->getBody();
            $body = json_decode($body);

            if ($body && $body->outcome && $body->outcome->type == 'venta_exitosa') {
                $this->updatePayment($paymentReference, 'CONFIRMED', 1, $body->outcome->type, $body->id);
                $webcheckoutConfirmData = ['state' => 'CONFIRMED', 'comment' => $body->outcome->type, 'origin' => $origin];
            }
        } catch (\Exception $e) {
            if ($e->getResponse()) {
                $response = (string) $e->getResponse()->getBody();
                $response = json_decode($response);
                $this->updatePayment($paymentReference, strtoupper($response->object), 1, $response->user_message, null);
                $webcheckoutConfirmData = [
                    'state' => strtoupper($response->object),
                    'comment' =>  $response->user_message,
                    'origin' => $origin
                ];
            }
        }
        return $this->webcheckoutConfirm($webcheckoutConfirmData);
    }

    public function webhooksListener(Request $request)
    {
        $this->util->logFile($request);
        $requestContent = json_decode($request->getContent(), true);

        $data = json_decode($requestContent['data'], true);
        $paymentReference = $data['metadata']['order_id'];

        if (!isset($paymentReference)) {
            return response(array('r' => false, 'm' => "Recibido", 'd' => 'El evento no tiene referenceCode'));
        }

        switch ($requestContent['type']) {
            case 'charge.creation.succeeded':
            case 'charge.update.succeeded':
            case 'charge.capture.succeeded':
                $this->updatePayment(
                    $paymentReference,
                    'CONFIRMED',
                    2,
                    'Transacción confirmada por webhook',
                    $data['id']
                );
                break;

            case 'charge.creation.failed':
            case 'charge.expired':
            case 'charge.update.fail':
            case 'charge.capture.failed':
                $this->updatePayment($paymentReference, 'REJECTED', 7, $data['userMessage'], $data['chargeId']);
                break;
        }

        return response(array('r' => true, 'm' => "Recibido", 'd' => null));
    }

    public function getTransactionByReference(Request $request)
    {
        try {
            $data = response()->json(array(
                'r' => true,
                'm' => 'Transacción obtenida con éxito',
                'd' => $this->getTransactionById($request["refTransaction_value"] ?? $request["idTransaction_value"])
            ));
            $response = array('r' => true, 'd' => array('data' => $data));
        } catch (\Throwable $th) {
            $response = array("r" => false, "type" => "error", "title" => "Oops...", "m" => $th->getMessage());
        }
        return response()->json($response);
    }

    public function getTransactionById($id)
    {
        $httpClient = new \GuzzleHttp\Client();
        $response = $httpClient->get($this->urlApi . "/charges/" . $id, [
            'headers' => ['Authorization' => 'Bearer ' . $this->privateKey]
        ]);

        return json_decode($response->getBody()->getContents());
    }

    public function validatePayment($transactionId, $reference)
    {
        $payment = $this->getTransactionById($transactionId);

        if ($transactionId) {
            $this->validateIndividualPayment($payment);
            return;
        }

        foreach ($payment->data as $individualPayment) {
            $this->validateIndividualPayment($individualPayment);
        }
    }

    private function validateIndividualPayment($payment)
    {
        $outcome = $payment->outcome;
        if (!isset($outcome->type) && isset($outcome->code)) {
            $outcome->type = $outcome->code;
        }
        if (!isset($outcome->type)) {
            return;
        }
        switch ($outcome->type) {
            case 'venta_exitosa':
                $this->updatePayment(
                    $payment->metadata->order_id ?? null,
                    'CONFIRMED',
                    2,
                    $outcome->user_message ?? $outcome->merchant_message ?? 'Transacción confirmada por validación',
                    $payment->id
                );
                break;

            case 'card_declined':
                $this->updatePayment(
                    $payment->metadata->order_id ?? null,
                    'DECLINED',
                    7,
                    $outcome->user_message ?? $outcome->merchant_message ?? 'Transacción declinada',
                    $payment->id
                );
                break;

            case 'card_error':
                $this->updatePayment(
                    $payment->metadata->order_id ?? null,
                    'ERROR',
                    7,
                    $outcome->user_message ?? $outcome->merchant_message ?? 'Error en la transacción',
                    $payment->id
                );
                break;
        }
    }
    /**
     * @param Request $request
     * @return mixed
     */
    public function responseTransaction(Request $request)
    {
    }
}