![]() Server : Apache System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64 User : corals ( 1002) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /home/corals/mcoil.corals.io/app/Http/Controllers/Front/ |
<?php namespace App\Http\Controllers\Front; use App\Shop\Addresses\Repositories\Interfaces\AddressRepositoryInterface; use App\Shop\Carts\Requests\CartCheckoutRequest; use App\Shop\Carts\Repositories\Interfaces\CartRepositoryInterface; use App\Shop\Carts\Requests\PayPalCheckoutExecutionRequest; use App\Shop\Carts\Requests\StripeExecutionRequest; use App\Shop\Couriers\Repositories\Interfaces\CourierRepositoryInterface; use App\Shop\Customers\Customer; use App\Shop\Customers\Repositories\CustomerRepository; use App\Shop\Customers\Repositories\Interfaces\CustomerRepositoryInterface; use App\Shop\Orders\Repositories\Interfaces\OrderRepositoryInterface; use App\Shop\PaymentMethods\Paypal\Exceptions\PaypalRequestError; use App\Shop\PaymentMethods\Paypal\Repositories\PayPalExpressCheckoutRepository; use App\Shop\PaymentMethods\Stripe\Exceptions\StripeChargingErrorException; use App\Shop\PaymentMethods\Stripe\StripeRepository; use App\Shop\Products\Repositories\Interfaces\ProductRepositoryInterface; use App\Shop\Products\Transformations\ProductTransformable; use App\Shop\Shipping\ShippingInterface; use App\Shop\Addresses\Address; use App\Shop\Orders\Order; use Exception; use App\Http\Controllers\Controller; use Gloudemans\Shoppingcart\Facades\Cart; use Illuminate\Http\Request; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use PayPal\Exception\PayPalConnectionException; use Illuminate\Support\Facades\DB; use App\Shop\Products\Product; use Ramsey\Uuid\Uuid; use App\Shop\ProductAttributes\ProductAttribute; use App\Shop\Order\OrderProductPrices; use App\Shop\OrderProducts\OrderProduct; class CheckoutController extends Controller { use ProductTransformable; /** * @var CartRepositoryInterface */ private $cartRepo; /** * @var CourierRepositoryInterface */ private $courierRepo; /** * @var AddressRepositoryInterface */ private $addressRepo; /** * @var CustomerRepositoryInterface */ private $customerRepo; /** * @var ProductRepositoryInterface */ private $productRepo; /** * @var OrderRepositoryInterface */ private $orderRepo; /** * @var PayPalExpressCheckoutRepository */ private $payPal; /** * @var ShippingInterface */ private $shippingRepo; public function __construct( CartRepositoryInterface $cartRepository, CourierRepositoryInterface $courierRepository, AddressRepositoryInterface $addressRepository, CustomerRepositoryInterface $customerRepository, ProductRepositoryInterface $productRepository, OrderRepositoryInterface $orderRepository, ShippingInterface $shipping ) { $this->cartRepo = $cartRepository; $this->courierRepo = $courierRepository; $this->addressRepo = $addressRepository; $this->customerRepo = $customerRepository; $this->productRepo = $productRepository; $this->orderRepo = $orderRepository; $this->payPal = new PayPalExpressCheckoutRepository; $this->shippingRepo = $shipping; $this->elavonUrl = config('constants.evalon_url'); } /** * Display a listing of the resource. * * @param Request $request * * @return \Illuminate\Http\Response */ public function index(Request $request, $orderId=null) { $elavon_user_name = config('elavon.key'); $elavon_user_password = config('elavon.secret'); $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password); $vendor_name = config('elavon.vendorName'); $ch = curl_init(); $header = array(); $header[] = 'Content-type: application/json'; $header[] = 'Authorization: Basic '.$base_inc; $payload = json_encode( array( "vendorName"=> $vendor_name ) ); curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/merchant-session-keys"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER,$header); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); //curl_setopt($ch, CURLOPT_POSTFIELDS,"vendorName=Juvotest"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $server_output = curl_exec($ch); $out = json_decode($server_output); $merchantSessionKey = $out->merchantSessionKey; // If the order id is null then process it in usual way (this is an customer order) if( is_null( $orderId ) ) { $products = $this->cartRepo->getCartItems(); $customer = $request->user(); $rates = null; $shipment_object_id = null; if (env('ACTIVATE_SHIPPING') == 1) { $shipment = $this->createShippingProcess($customer, $products); if (!is_null($shipment)) { $shipment_object_id = $shipment->object_id; $rates = $shipment->rates; } } // Get payment gateways $paymentGateways = collect(explode(',', config('payees.name')))->transform(function ($name) { return config($name); })->all(); // $billingAddress = $customer->addresses()->first(); $billingAddress = $customer->addresses()->where(['billing_type_address' => 1])->first(); $total = $this->cartRepo->getTotal(2); $tax = $this->cartRepo->getTax(); // Get the discount coupon code if available $appliedCouponCode = $request->get('applied_coupon_code', ''); $discountCoupon = 'NA'; $discountType = ''; $discountValue = ''; $discountAmount = 0; if( $appliedCouponCode != '' ) { $discountCouponDetails = DB::table('discount_coupons')->where(['coupon_code' => $appliedCouponCode])->first(); if( $discountCouponDetails ) { if( $discountCouponDetails->coupon_type == '1' ) // Percentage { $discountAmount = number_format(( ( ( $total + $tax ) * $discountCouponDetails->discount_value ) / 100 ), 2); } else { $discountAmount = number_format(($discountCouponDetails->discount_value), 2); } $discountCoupon = $appliedCouponCode; $discountType = $discountCouponDetails->coupon_type; $discountValue = $discountCouponDetails->discount_value; } } // Fetch delivery addresses $deliveryAddresses = Address::where('customer_id', $customer->id)->where('billing_type_address', 0)->orderBy('id', 'asc')->get(); return view('front.checkout', [ 'customer' => $customer, 'billingAddress' => $billingAddress, 'deliveryAddresses' => $deliveryAddresses, 'addresses' => $customer->addresses()->get(), 'products' => $this->cartRepo->getCartItems(), 'subtotal' => $this->cartRepo->getSubTotal(), 'tax' => $tax, // 'total' => $this->cartRepo->getTotal(2), 'total' => $total, 'payments' => $paymentGateways, 'cartItems' => $this->cartRepo->getCartItemsTransformed(), 'shipment_object_id' => $shipment_object_id, 'rates' => $rates, // For discount 'discountCoupon' => $discountCoupon, 'discountType' => $discountType, 'discountValue' => $discountValue, 'discountAmount' => $discountAmount, 'orderDetails' => null, 'merchantSessionKey'=>$merchantSessionKey ]); } else { $customer = $request->user(); // Fetch the order details $orderDetails = Order::find($orderId); // If order exist if( $orderDetails ) { if( $orderDetails->customer_id == $customer->id ) { // Get payment gateways $paymentGateways = collect(explode(',', config('payees.name')))->transform(function ($name) { return config($name); })->all(); // $billingAddress = $customer->addresses()->first(); $billingAddress = $customer->addresses()->where(['billing_type_address' => 1])->first(); $subtotal = $orderDetails->total_products; // $total = $this->cartRepo->getTotal(2); $total = $subtotal; // $tax = $this->cartRepo->getTax(); $tax = $orderDetails->tax; $discountCoupon = 'NA'; $discountType = ''; $discountValue = ''; $discountAmount = 0; if( !is_null( $orderDetails->discount_coupon_code ) && !is_null( $orderDetails->discount_coupon_type ) && !is_null( $orderDetails->discount_value ) && !is_null( $orderDetails->discount_amount ) ) { $discountCoupon = $orderDetails->discount_coupon_code; $discountType = $orderDetails->discount_coupon_type; $discountValue = $orderDetails->discount_value; $discountAmount = $orderDetails->discount_amount; } // Fetch delivery addresses $deliveryAddresses = Address::where('customer_id', $customer->id)->where('billing_type_address', 0)->orderBy('id', 'asc')->get(); $rates = null; $shipment_object_id = null; return view('front.checkout', [ 'customer' => $customer, 'billingAddress' => $billingAddress, 'deliveryAddresses' => $deliveryAddresses, 'addresses' => $customer->addresses()->get(), // 'products' => $this->cartRepo->getCartItems(), 'subtotal' => $subtotal, 'tax' => $tax, // 'total' => $this->cartRepo->getTotal(2), 'total' => $total, 'payments' => $paymentGateways, 'cartItems' => $this->cartRepo->getCartItemsTransformed(), 'shipment_object_id' => $shipment_object_id, 'rates' => $rates, // For discount 'discountCoupon' => $discountCoupon, 'discountType' => $discountType, 'discountValue' => $discountValue, 'discountAmount' => $discountAmount, 'orderDetails' => $orderDetails, 'merchantSessionKey' =>$merchantSessionKey ]); } else { return redirect('accounts?tab=profile')->with('error', 'You are not allowed to access this order.'); } } else { return redirect('accounts?tab=profile')->with('error', 'Invalid order id.'); } } } /** * Checkout the items * * @param CartCheckoutRequest $request * * @return \Illuminate\Http\RedirectResponse * @throws \App\Shop\Addresses\Exceptions\AddressNotFoundException * @throws \App\Shop\Customers\Exceptions\CustomerPaymentChargingErrorException * @codeCoverageIgnore */ public function store(CartCheckoutRequest $request) { $shippingFee = 0; switch ($request->input('payment')) { case 'paypal': return $this->payPal->process($shippingFee, $request); break; case 'stripe': $details = [ 'description' => 'Stripe payment', 'metadata' => $this->cartRepo->getCartItems()->all() ]; $customer = $this->customerRepo->findCustomerById(auth()->id()); $customerRepo = new CustomerRepository($customer); $customerRepo->charge($this->cartRepo->getTotal(2, $shippingFee), $details); break; default: } } /** * Execute the PayPal payment * * @param PayPalCheckoutExecutionRequest $request * @return \Illuminate\Http\RedirectResponse */ public function executePayPalPayment(PayPalCheckoutExecutionRequest $request) { try { $this->payPal->execute($request); $this->cartRepo->clearCart(); return redirect()->route('checkout.success'); } catch (PayPalConnectionException $e) { throw new PaypalRequestError($e->getData()); } catch (Exception $e) { throw new PaypalRequestError($e->getMessage()); } } /** * @param StripeExecutionRequest $request * @return \Stripe\Charge */ public function charge(Request $request) { // Fetch the order id $orderId = $request->get('order_id', ''); // If order id is blank that means it is a regular order if( $orderId == '' ) { try { $customer = $this->customerRepo->findCustomerById(auth()->id()); $elavon_user_name = config('elavon.key'); $elavon_user_password = config('elavon.secret'); $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password); $vendor_name = config('elavon.vendorName'); $elav_order_total = round($request->total_amount,2)*100; $ch = curl_init(); $header = array(); $header[] = 'Content-type: application/json'; $header[] = 'Authorization: Basic '.$base_inc; $payload = json_encode( array( "vendorName"=> $vendor_name ) ); $card_identifier = $request->input('card-identifier'); $ms = $request->input('merchent_key'); $address = Address::where('id', $request->billing_address)->first(); $payment_payload = json_encode( array( "transactionType"=> "Payment", "paymentMethod"=>array('card' => array("merchantSessionKey"=>$ms,"cardIdentifier"=>$card_identifier, "save"=> false )), "vendorTxCode"=>"Product-".rand(), "amount"=> $elav_order_total, "currency"=> "EUR", "description"=> "Product Order", "customerFirstName"=> $customer->fname, "customerLastName"=> $customer->lname, "customerEmail"=> $customer->email, "billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'), "entryMethod"=> "Ecommerce" )); curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/transactions"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER,$header); curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_payload); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $server_output_pay = curl_exec($ch); $serialized_result = json_decode($server_output_pay); if(!isset($serialized_result->transactionId)){ return redirect()->back()->with('error', 'Some error in creating order.'); } } catch (StripeChargingErrorException $e) { Log::info($e->getMessage()); // return redirect()->route('checkout.index')->with('error', 'There is a problem processing your request.'); } $products = $this->cartRepo->getCartItems(); $productCount = count($products); if ($productCount > 0) { $subtotal = 0; $vat = 0; foreach($products as $productDetails){ $subtotal += $productDetails->price; $vat += ( ( $productDetails->price * $productDetails->tax ) / 100 ); } $total = ( $subtotal + $vat ); $discountAmount = 0; $discountAmount = $request->input('discount_amount'); $grandTotal = $total - $discountAmount; // Get the address $customerAddress = DB::table('addresses')->where('id',$request->input('billing_address'))->first(); if ($customerAddress) { // Start transaction DB::beginTransaction(); $order = new Order; $order->courier_id = 1; $order->reference = Uuid::uuid4()->toString(); $order->customer_id = $customer; $order->address_id = $customerAddress->id; $order->order_status_id = 1; // awaiting payment $order->payment = 'Credit Card'; if ($discountAmount > 0) { $order->discounts = $discountAmount; $order->discount_coupon_code = $request->input('discount_coupon'); $order->discount_coupon_type = ''; $order->discount_value = $request->input('discount_value'); $order->discount_amount = $discountAmount; } $order->total_products = $subtotal; $order->tax = $vat; $order->total = $grandTotal; $order->tax_value = $vat; $order->total_paid = $grandTotal; $order->billing_address_id = $customerAddress->id; $order->delivery_address_id = $customerAddress->id; $order->oil_type_order = '0'; $order->created_by_admin = '1'; $order->transaction_id = isset($serialized_result->transactionId) ? $serialized_result->transactionId : ''; // Payment option $order->payment_option = 'Credit Card'; if ($order->save()) { $products = ProductAttribute::get(); if(count($products) > 0){ foreach($products as $order_product){ $orders_prod_insert = new OrderProductPrices; $orders_prod_insert->order_id = $order->id; $orders_prod_insert->product_id = $order_product->product_id; $orders_prod_insert->attribute_id = $order_product->id; $orders_prod_insert->price = $order_product->price; $orders_prod_insert->sale_price = $order_product->sale_price; $orders_prod_insert->save(); } } for($i=0; $i<$productCount; $i++) { $orderProducts = new OrderProduct; $orderProducts->order_id = $order->id; $orderProducts->product_id = $productDetails->id; $orderProducts->quantity = $productDetails->qty; $orderProducts->product_name = $productDetails->name; $orderProducts->product_sku = $productDetails->sku; $orderProducts->product_description = $productDetails->description; $orderProducts->product_price = $productDetails->price; $orderProducts->save(); } DB::commit(); Cart::destroy(); return redirect()->route('checkout.success')->with('message', 'Payment successful!'); //return redirect()->route('admin.orders.index')->with('message', 'Order created successfully.'); } else { DB::rollBack(); return redirect()->back()->with('error', 'Some error in creating order.'); } } else { return redirect()->back()->with('error', 'No billing address found for the select customer.'); } } } else // It is an order placed by admin on behalf of customer { try { $customer = $this->customerRepo->findCustomerById(auth()->id()); //$stripeRepo = new StripeRepository($customer); $orderDetails = Order::find($orderId); $elavon_user_name = config('elavon.key'); $elavon_user_password = config('elavon.secret'); $base_inc = base64_encode($elavon_user_name.':'.$elavon_user_password); $vendor_name = config('elavon.vendorName'); $elav_order_total = number_format($order_total,2); $ch = curl_init(); $header = array(); $header[] = 'Content-type: application/json'; $header[] = 'Authorization: Basic '.$base_inc; $payload = json_encode( array( "vendorName"=> $vendor_name ) ); $card_identifier = $request->input('card-identifier'); $ms = $request->input('merchent_key'); $address = Address::where('id', $request->billing_address)->first(); $payment_payload = json_encode( array( "transactionType"=> "Payment", "paymentMethod"=>array('card' => array("merchantSessionKey"=>$ms,"cardIdentifier"=>$card_identifier, "save"=> false )), "vendorTxCode"=>"Product-".rand(), "amount"=> (int)$elav_order_total, "currency"=> "EUR", "description"=> "Product Order", "customerFirstName"=> $customer->fname, "customerLastName"=> $customer->lname, "customerEmail"=> $customer->email, "billingAddress"=>array("address1"=>$address->address_1,"postalCode"=>$address->zip,"city"=> $address->town,"country"=> 'IE'), "entryMethod"=> "Ecommerce" )); curl_setopt($ch, CURLOPT_URL,$this->elavonUrl."/api/v1/transactions"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER,$header); curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_payload); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $server_output_pay = curl_exec($ch); $serialized_result = json_decode($server_output_pay); try{ if ($serialized_result->transactionType == 'Payment') { $orderDetails->order_status_id = 1; # on-delivery } else { $orderDetails->order_status_id = 3; # error } $orderDetails->transaction_id = $serialized_result->transactionId; $orderDetails->transaction_status = ($serialized_result->status) ? $serialized_result->status : null; $orderDetails->delivery_date = date("Y-m-d"); $orderDetails->save(); } catch(Exception $e) { \Log::info('Message: ' .$e->getMessage()); DB::rollBack(); return redirect()->back()->with('error', 'Some error in creating order.'); } if(!isset($serialized_result->transactionId)){ return redirect()->back()->with('error', 'Some error in creating order.'); } /*$customer = $this->customerRepo->findCustomerById(auth()->id()); $stripeRepo = new StripeRepository($customer); $orderDetails = Order::find($orderId); $stripeRepo->executeShopOrderPayment( $request->all(), $orderDetails->total );*/ // try { // \Mail::to($customer)->send(new SendOrderToCustomerMailable($orderDetails)); // } // catch(Exception $e) { // \Log::inf('Message: ' .$e->getMessage()); // } return redirect()->route('checkout.success')->with('message', 'Stripe payment successful!'); } catch (StripeChargingErrorException $e) { Log::info($e->getMessage()); return redirect()->route('checkout.index', [$orderDetails->id])->with('error', 'There is a problem processing your request.'); } } } /** * Cancel page * * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function cancel(Request $request) { return view('front.checkout-cancel', ['data' => $request->all()]); } /** * Success page * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function success() { // $messages = DB::table('messages')->first(); return view('front.checkout-success'); } /** * @param Customer $customer * @param Collection $products * * @return mixed */ private function createShippingProcess(Customer $customer, Collection $products) { $customerRepo = new CustomerRepository($customer); if ($customerRepo->findAddresses()->count() > 0 && $products->count() > 0) { $this->shippingRepo->setPickupAddress(); $deliveryAddress = $customerRepo->findAddresses()->first(); $this->shippingRepo->setDeliveryAddress($deliveryAddress); $this->shippingRepo->readyParcel($this->cartRepo->getCartItems()); return $this->shippingRepo->readyShipment(); } } /** * Display a listing of the resource. * * @param Request $request * * @return \Illuminate\Http\Response */ public function makePayment(Request $request, $orderId) { $customer = $request->user(); // Get payment gateways $paymentGateways = collect(explode(',', config('payees.name')))->transform(function ($name) { return config($name); })->all(); // $billingAddress = $customer->addresses()->first(); $billingAddress = $customer->addresses()->where(['billing_type_address' => 1])->first(); // Fetch the order details $orderDetails = Order::find($orderId); $subtotal = $orderDetails->total_products; // $total = $this->cartRepo->getTotal(2); $total = $subtotal; // $tax = $this->cartRepo->getTax(); $tax = $orderDetails->tax; $discountCoupon = 'NA'; $discountType = ''; $discountValue = ''; $discountAmount = 0; if( !is_null( $orderDetails->discount_coupon_code ) && !is_null( $orderDetails->discount_coupon_type ) && !is_null( $orderDetails->discount_value ) && !is_null( $orderDetails->discount_amount ) ) { $discountCoupon = $orderDetails->discount_coupon_code; $discountType = $orderDetails->discount_coupon_type; $discountValue = $orderDetails->discount_value; $discountAmount = $orderDetails->discount_amount; } // Fetch delivery addresses $deliveryAddresses = Address::where('customer_id', $customer->id)->where('billing_type_address', 0)->orderBy('id', 'asc')->get(); $rates = null; $shipment_object_id = null; return view('front.product-order-checkout', [ 'customer' => $customer, 'billingAddress' => $billingAddress, 'deliveryAddresses' => $deliveryAddresses, 'addresses' => $customer->addresses()->get(), 'subtotal' => $subtotal, 'tax' => $tax, 'total' => $total, 'payments' => $paymentGateways, 'shipment_object_id' => $shipment_object_id, 'rates' => $rates, 'orderDetails' => $orderDetails, // For discount 'discountCoupon' => $discountCoupon, 'discountType' => $discountType, 'discountValue' => $discountValue, 'discountAmount' => $discountAmount, ]); } }