MOON
Server: Apache
System: Linux server.royaltuning.hu 4.18.0-425.13.1.el8_7.x86_64 #1 SMP Tue Feb 21 04:20:52 EST 2023 x86_64
User: royaltuning (1001)
PHP: 8.2.32
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //var/www/html/Modules/Checkout/Http/Controllers/CheckoutCompleteController.php
<?php

namespace Modules\Checkout\Http\Controllers;

use EonVisualMedia\LaravelKlaviyo\Klaviyo;
use EonVisualMedia\LaravelKlaviyo\TrackEvent;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Modules\Order\Entities\Order;
use Modules\Payment\Facades\Gateway;
use Modules\Checkout\Events\OrderPlaced;
use Modules\Checkout\Services\OrderService;
use Modules\Checkout\Http\Controllers\TrustedShop;
use Modules\Product\Entities\Product;
use Modules\Product\Http\Controllers\Api\Webshippy\WebshippyOrderController;

class CheckoutCompleteController
{
    /**
     * Store a newly created resource in storage.
     *
     * @param int $orderId
     * @param \Modules\Checkout\Services\OrderService $orderService
     * @return \Illuminate\Http\Response
     */
    public function store($orderId, OrderService $orderService)
    {
        $order = Order::findOrFail($orderId);

        $gateway = Gateway::get(request('paymentMethod'));

        if (request('paymentMethod') == "barion") {

            $id = request()->input("paymentId");
            $payment = call_user_func(['Barion', 'getPaymentState'], $id);
            //dd($payment);
            if ($payment->Status == "Canceled" || $payment->Status == "Failed" || $payment->Status == "Expired" || $payment->Status == "PartiallySucceeded") {
                if (!request()->ajax()) {
                    return redirect()->route('checkout.payment_canceled.store', [$orderId]);
                }
            } else {

                try {
                    $response = $gateway->complete($order);
                } catch (Exception $e) {
                    $orderService->delete($order);

                    return response()->json([
                        'message' => $e->getMessage(),
                    ], 403);
                }

                $order->storeTransaction($response);

                event(new OrderPlaced($order));

                $webshippy = new WebshippyOrderController();

                $webShip = $webshippy->addUpdateOrder($orderId);

                if ($webShip != "OK") {
                    DB::table("orders")->where("id", $orderId)->update([
                        "webshippy_error" => 1
                    ]);
                }

                $this->sendToKlaviyo($orderId);

                $this->sendToArukereso($orderId);

                if (!request()->ajax()) {
                    return redirect()->route('checkout.complete.show');
                }
            }
        } else {
            try {
                $response = $gateway->complete($order);
            } catch (Exception $e) {
                $orderService->delete($order);

                return response()->json([
                    'message' => $e->getMessage(),
                ], 403);
            }

            $order->storeTransaction($response);

            event(new OrderPlaced($order));

            $webshippy = new WebshippyOrderController();

            $webShip = $webshippy->addUpdateOrder($orderId);

            if ($webShip != "OK") {
                DB::table("orders")->where("id", $orderId)->update([
                    "webshippy_error" => 1
                ]);
            }

            $this->sendToKlaviyo($orderId);
            $this->sendToArukereso($orderId);
            if (!request()->ajax()) {
                return redirect()->route('checkout.complete.show');
            }
        }
    }

    public function sendToArukereso($orderId)
    {

        $order = Order::find($orderId);

        try {

            /** Provide your own WebAPI key. You can find your WebAPI key on your partner portal. */
            $Client = new TrustedShop(env("MEGBIZHATO_API"));

            /** Provide the e-mail address of your customer. You can retrieve the e-amil address from the webshop engine. */
            $Client->SetEmail($order->customer_email);

            /** Customer's cart example. */
            $Cart = $this->getArukeresoDatas($order);

            Storage::disk('arukereso')->put('megbizhato-bolt-kosar.json', json_encode($Cart));


            /** Provide the name and the identifier of the purchased products.
             * You can get those from the webshop engine.
             * It must be called for each of the purchased products. */
            foreach ($Cart as $ProductIdentifier => $ProductName) {
                /** If both product name and identifier are available, you can provide them this way: */
                $Client->AddProduct($ProductName, $ProductIdentifier);
                /** If only product name is available, you can provide it with the following call: */
                $Client->AddProduct($ProductName);
                /** If neither is available, you can leave out these calls. */
            }

            /** This method perpares to send us the e-mail address and the name of the purchased products set above.
             *  It returns an HTML code snippet which must be added to the webshop's source.
             *  After the generated code is downloaded into the customer's browser it begins to send purchase information. */
            Storage::disk('arukereso')->put('megbizhato-bolt-code.json', json_encode($Client->Prepare()));
            Storage::disk('arukereso')->put($orderId . '-code.json', json_encode($Client->Prepare()));
            return $Client->Prepare();

            /** Here you can implement error handling. The error message can be obtained in the manner shown below. This step is optional. */
        } catch (Exception $Ex) {
            $ErrorMessage = $Ex->getMessage();
            Storage::disk('arukereso')->put('megbizhato-bolt-error.json', json_encode($Ex));
        }
    }

    public function sendToKlaviyo($orderId)
    {

        $order = Order::find($orderId);

        $data = self::getDatas($order);

        Klaviyo::track(TrackEvent::make(
            'Placed Order',
            $data,
            [
                '$email' => $order->customer_email,
                '$first_name' => $order->billing_first_name,
                '$last_name' => $order->billing_last_name
            ],
        ));
    }

    public function getArukeresoDatas($order)
    {

        $data = [];

        foreach ($order->products as $product) {

            $prod = Product::find($product->product_id);

            $data[$prod->sku] = $prod->name;

        }

        return $data;
    }

    public function getDatas($order)
    {
        $products = $order->products;
        $taxes = $order->taxes;

        $data = [];

        $data["ItemNames"] = self::getItemsName($products);
        $data["ProductNames"] = self::getItemsName($products);
        $data["ItemCategories"] = self::getCategories($products);
        $data["ShippingMethods"] = $order->shipping_method;
        $data["\$value"] = $order->total->convertToCurrentCurrency()->amount();
        $data["extra"]["OrderId"] = $order->id;
        $data["extra"]["OrderNumber"] = $order->id;
        $data["extra"]["TotalShipping"] = $order->shipping_cost->convertToCurrentCurrency()->amount();
        $data["extra"]["TotalTax"] = $order->total->convertToCurrentCurrency()->amount() * 0.2126;
        $data["extra"]["TotalDiscount"] = $order->discount->convertToCurrentCurrency()->amount();
        $data["extra"]["currency"] = "HUF";

        $data["extra"]["Items"] = $this->getItems($order);
        $data["extra"]["BillingAddress"] = [
            "FirstName" => $order->billing_first_name,
            "LastName" => $order->billing_last_name,
            "Address1" => $order->billing_address_1,
            "Address2" => $order->billing_address_2,
            "City" => $order->billing_city,
            "State" => "",
            "Country" => "HU",
            "PostCode" => $order->billing_zip,
        ];
        if ($order->shipping_method == "PACKETA Csomagpont") {
            $csomagpont = json_decode($order->csomagpont);

            $data["extra"]["ShippingAddress"] = [
                "FirstName" => $order->shipping_first_name,
                "LastName" => $order->shipping_last_name,
                "Address1" => $csomagpont->street,
                "Address2" => $csomagpont->name,
                "City" => $csomagpont->city,
                "State" => "",
                "Country" => "HU",
                "PostCode" => $csomagpont->zip,
            ];

        } else if ($order->shipping_method == "FOXPOST csomagpont") {
            $csomagpont = json_decode($order->csomagpont);

            $data["extra"]["ShippingAddress"] = [
                "FirstName" => $order->shipping_first_name,
                "LastName" => $order->shipping_last_name,
                "Address1" => $csomagpont->street,
                "Address2" => $csomagpont->name,
                "City" => $csomagpont->city,
                "State" => "",
                "Country" => "HU",
                "PostCode" => $csomagpont->zip,
            ];

        } else if ($order->shipping_method == "GLS Csomagpont") {
            $csomagpont = json_decode($order->csomagpont);

            $data["extra"]["ShippingAddress"] = [
                "FirstName" => $order->shipping_first_name,
                "LastName" => $order->shipping_last_name,
                "Address1" => $csomagpont->contact->address,
                "Address2" => $csomagpont->name,
                "City" => $csomagpont->contact->city,
                "State" => "",
                "Country" => "HU",
                "PostCode" => $csomagpont->contact->postalCode,
            ];

        } else {
            $data["extra"]["ShippingAddress"] = [
                "FirstName" => $order->shipping_first_name,
                "LastName" => $order->shipping_last_name,
                "Address1" => $order->shipping_address_1,
                "Address2" => $order->shipping_address_2,
                "City" => $order->shipping_city,
                "State" => "",
                "Country" => "HU",
                "PostCode" => $order->shipping_zip,
            ];
        }

        return $data;
    }

    public function getItems($order)
    {
        $data = [];
        foreach ($order->products as $product) {

            $prod = Product::find($product->product_id);

            $data[] = [
                "ProductId" => $prod->id,
                "SKU" => $prod->sku,
                "Quantity" => $product->qty,
                "LineTotalTax" => $prod->selling_price->convertToCurrentCurrency()->amount() * 0.2126 * $product->qty,
                "LineSubTotal" => $prod->selling_price->convertToCurrentCurrency()->amount() * 0.7874 * $product->qty,
                "LineTotal" => $prod->selling_price->convertToCurrentCurrency()->amount() * $product->qty,
                "Name" => $prod->name,
                "Variant" => [],
                "Price" => $prod->selling_price->convertToCurrentCurrency()->amount(),
                "ProductName" => $prod->name,
                "Categories" => self::getSimpleCategories($prod),
                "Metadata" => [],
                "\$extra" => [
                    "URL" => "https://royaltuning.hu/termek/" . $prod->slug,
                    "Images" => [
                        0 => [
                            "URL" => $prod->base_image->path
                        ]
                    ],
                ],
            ];

        }

        return $data;

    }

    public function getSimpleCategories($product)
    {
        $data = [];
        foreach ($product->categories as $category) {
            $data[] = $category->name;
        }

        return $data;
    }

    public function getCategories($products)
    {

        $data = [];
        foreach ($products as $product) {
            $prod = Product::find($product->product_id);
            foreach ($prod->categories as $category) {
                $data[] = $category->name;
            }
        }

        return $data;
    }

    public function getItemsName($products)
    {

        $data = [];
        foreach ($products as $product) {
            $data[] = $product->name;
        }

        return $data;


    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show()
    {

        $order = session('placed_order');

        $code = $order ? json_decode(Storage::disk('arukereso')->get($order->id . '-code.json')) : NULL;


        if (is_null($order)) {
            return redirect()->route('home');
        }

        return view('public.checkout.complete.show', array('order' => $order, "code" => $code));
    }
}