File: D:/HostingSpaces/SBogers10/topswtw.komma.pro/app/controllers/CheckoutController.php
<?php
use KommaApp\Shop\Checkout\CheckoutSession\CheckoutSession;
use KommaApp\Shop\Checkout\Payment\PaymentService;
use KommaApp\Shop\Checkout\Shipping\ShippingService;
use KommaApp\Shop\Countries\CountryService;
use KommaApp\Shop\Customers\CustomerService;
use KommaApp\Shop\FormValidation\CheckoutForm;
use KommaApp\Shop\Mailers\CustomerMailer;
use KommaApp\Shop\Modules\Modules;
use KommaApp\Shop\Orders\Order;
use KommaApp\Shop\Orders\OrderService;
use KommaApp\Shop\Pages\PageService;
use Illuminate\Validation\Factory as Validator;
class CheckoutController extends BaseController
{
/**
* @var OrderService
*/
protected $orderService;
/**
* @var ShippingService
*/
protected $shippingService;
/**
* @var CheckoutSession
*/
protected $checkoutSession;
/**
* @var PaymentService
*/
private $paymentService;
/**
* @var PageService
*/
private $pageService;
/**
* @var CustomerService
*/
private $customerService;
/**
* @var CountryService
*/
private $countryService;
/**
* @var CustomerMailer;
*/
private $customerMailer;
/**
* @var CheckoutForm
*/
private $checkoutForm;
private $validator;
/**
* @param CheckoutSession $checkoutSession
* @param OrderService $orderService
* @param PaymentService $paymentService
* @param PageService $pageService
* @param CustomerService $customerService
* @param CountryService $countryService
* @param CheckoutForm $checkoutForm
*/
function __construct(
CheckoutSession $checkoutSession,
ShippingService $shippingService,
OrderService $orderService,
PaymentService $paymentService,
PageService $pageService,
CustomerService $customerService,
CountryService $countryService,
Validator $validator,
CustomerMailer $customerMailer,
CheckoutForm $checkoutForm
)
{
$this->checkoutSession = $checkoutSession;
$this->orderService = $orderService;
$this->shippingService = $shippingService;
$this->paymentService = $paymentService;
$this->pageService = $pageService;
$this->customerService = $customerService;
$this->countryService = $countryService;
$this->validator = $validator;
$this->customerMailer = $customerMailer;
$this->checkoutForm = $checkoutForm;
}
/*
|--------------------------------------------------------------------------
| Checkout Login
|--------------------------------------------------------------------------
|
*/
public function showLoginPage()
{
// Set coupon code in session
if (\Request::get('coupon-code')) $this->checkoutSession->cart()->setCouponCode(\Request::get('coupon-code'));
// Check if we are allowed to visit this page
if (!$this->pageAllowed('checkoutLogin')) {
return \Redirect::to(\Shop::getPageService()->page('cart')->route);
}
// Check customer is logged in, continue tot checkout data
if (\Auth::customer()->check()) {
return \Redirect::to(\Shop::getPageService()->page('checkoutData')->route);
}
// Show login page
return View::make( viewPrefix() . 'checkout.login');
}
/*
|--------------------------------------------------------------------------
| Checkout
|--------------------------------------------------------------------------
|
*/
/**
* Show order page, the page after the cart
* This page is called on winkelwagen/bestelgegevens (nl)
* @return View
*/
public function show()
{
//Redirect to paymentLink for order if the current order is not yet payed
if($this->checkoutSession->orderId()) {
$order = Order::find($this->checkoutSession->orderId());
if($order) {
$pageRoute = \Shop::getPageService()->getPageByShopAndLang('pendingPayment', \Shop::getShop()->id, $order->language_id);
$paymentLink = $pageRoute.'/?token='.urlencode($order['order_token']);
return \Illuminate\Support\Facades\Redirect::to($paymentLink);
}
}
// Check default country Todo: liefst ergens anders plaatsen
$shopCountry = $this->countryService->shopCountry();
if (!\Session::get('checkout.customer.data.invoice-country'))
\Session::put('checkout.customer.data.invoice-country', \Shop::getDomainCountry());
if (!\Session::get('checkout.shipping.data.shipping-country'))
\Session::put('checkout.shipping.data.shipping-country', \Shop::getDomainCountry());
// Check if we are allowed to visit this page
if (!$this->pageAllowed('checkoutData')) {
return \Redirect::to(\Shop::getPageService()->page('cart')->route);
}
//Check if the payment method is set, already rounded up the order
/*
//Todo: dit met Stef bespreken, hoe we dit gaan opvangen.
if($order_id = $this->checkoutSession->orderId()){
//Redirect to the page were we can chose payment methods
//Collect the order token based on the order_id
if(!$order = Order::find($order_id)) return false;
return \Redirect::to(\Shop::getPageService()->page('pendingPayment')->route.'?token='.$order->order_token);
}
*/
return Response::view( viewPrefix() . 'checkout.checkout', [
'shop' => \Shop::get(),
'checkout' => $this->checkoutSession,
'paymentMethods' => $this->paymentService->getPaymentMethods(),
'countries' => $this->countryService->countriesForCheckout()
])->header('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
}
/**
* Process order
*
* @return string
*/
public function process()
{
// Get Shop id
$shopId = \Shop::getId();
// Setup shop languages
\Shop::getLanguageService()->bootFromUri($shopId);
// Store order in database, notify user for order
$input = Input::all();
if (isset($input['invoice-company-vat'])) {
$input['invoice-company-vat'] = strtoupper($input['invoice-company-vat']);
$input['invoice-company-vat'] = preg_replace("/[^A-Z0-9]/", "", $input['invoice-company-vat']);
}
// Save customer in a session
$this->checkoutSession->customer()->save();
$this->checkoutSession->payment()->save();
//Set the remark in the session
$this->checkoutSession->setRemarks($input['remarks']);
// Check shipping address
$input = $this->orderService->updateShippingAddress($input);
// Is the order valid
if (!$this->checkoutForm->isValid($input)) {
return \Redirect::back()
->withErrors($this->checkoutForm->errorMessages());
}
$store = $this->orderService->store($input);
//if the response is an redirect, return redirect
if (get_class($store) == 'Illuminate\Http\RedirectResponse') return $store;
// redirect to payment
return $this->orderService->redirectToPayment();
}
/*
|--------------------------------------------------------------------------
| Checkout success
|--------------------------------------------------------------------------
|
*/
/**
* @return mixed
*/
public function showThanksPage()
{
if (!($token = \Input::get('token')))
return \Redirect::to(\Shop::getPageService()->page('checkoutData')->route);
// $token = '$2y$10$m1qGsU/vLAnsiAi7fzHWuuZwml71JfDg/qDQEPegwTSjyx/rFT6oW';
/** @var Order $order */
$order = $this->orderService->getOrderByToken($token);
$order->load('products');
return View::make( viewPrefix() . 'checkout.thanks')->with([
'shop' => \Shop::get(),
'checkout' => $this->checkoutSession,
'order' => $order,
'customerService' => $this->customerService
]);
}
/**
* This method is called as an post function on the link account to order after payment
* nl url = nl/winkelwagen/wachten-op-betaling
*
*/
public function quickLinkAccount()
{
//No post, return to home
if (!\Request::isMethod('post')) return \Redirect::to('/', 302);
// Setup shop languages from URI
\Shop::getLanguageService()->bootFromUri(\Shop::getId());
//Vallidate the input, the password and confirmation are required and should be the same And min 6 characters
$validator = $this->validator->make(\Input::all(),
['password' => 'required|min:6',
'password_confirmation' => 'required|same:password',]
, [
'password.min' => \Lang::get('customer/create.error_password_min'),
'password_confirmation.same' => \Lang::Get('customer/create.error_password_confirmation'),
]
);
//Check of the validation fails
if ($validator->fails()) {
//It fails, redirecot to the form with validation errors
if (!\Request::header('referer')) \App::abort(404, 'Page not found');
return \Redirect::back()->withErrors($validator);
}
//Set The password and orderToken
//Set The password and orderToken
$password = \Input::get('password');
$orderToken = \Input::get('order_token');
// Link the account based on ther order
$result = $this->customerService->LinkAccountFromOrder($orderToken, $password);
//If this fails return with errors
if (isset($result['error'])) {
return \Redirect::back()->with(['errors_msg' => [$result['error']]]);
}
//All is well return to customer.activated
return \View::make( viewPrefix() . 'customers.activated');
}
/**
* This method is called after an order with an email that has an account
*
*/
public function linkAccount()
{
if (!\Request::isMethod('post')) return \Redirect::to('', 302);
$credentials = \Input::only('email', 'password');
$credentials['active'] = 1;
// Login with credentials
if (!\Auth::customer()->attempt($credentials)) {
return \Redirect::back()
->withErrors(['noUserFound' => 'no user found']);
}
// Get the order model and customer model
$order = Order::find(\Input::get('order_id'));
$customer = \Auth::customer()->get();
// Link order with order_id with the user that is logged in.
$order->customer()->associate($customer);
$order->save();
// Show linked message
return View::make( viewPrefix() . 'checkout.accountLinked', compact('order'));
}
/*
|--------------------------------------------------------------------------
| VAT
|--------------------------------------------------------------------------
|
*/
public function checkVat($vatId)
{
//Check if the invoice country code is in the request
if (!$invoice_country = Input::get('invoice_country')) {
//no inoice country ->not valid
return \Response::json(['valid' => 0]);
}
//extract the countrycode out of the VAT
$countryCode = substr($vatId, 0, 2);
//Check if the invoice country is the same as the VAT country
if ($invoice_country != $countryCode) {
//invoice country not like countrycode -> not valid
return \Response::json(['valid' => 0]);
}
//trim the data
$vatId = str_replace(array(' ', '.', '-', ',', ', '), '', trim($vatId));
//run the CheckVatNumber from the orderService
if (!$this->orderService->checkVatNumber($vatId)) {
return \Response::json(['valid' => 0]);
}
return \Response::json(['valid' => 1]);
}
/*
|--------------------------------------------------------------------------
| Page verification
|--------------------------------------------------------------------------
|
*/
/*
* Check if you can visit a page
*/
protected function pageAllowed($page)
{
// Conditions
$cartNotEmpty = ['checkoutLogin', 'checkoutData'];
// Check conditions
if (in_array($page, $cartNotEmpty)) {
if ($this->checkoutSession->cart()->totalQuantity() == 0) {
return false;
}
}
return true;
}
/*
|--------------------------------------------------------------------------
| Shipping Costs
|--------------------------------------------------------------------------
|
*/
public function getShippingCosts($countryCode = null)
{
if (!$countryCode)
return \Response::json(['error: No iso2 country code provided']);
if (!$country = $this->countryService->getCountryByIso2($countryCode))
return \Response::json(['error: can\'t find country with iso2:' . $countryCode]);
$price = $this->checkoutSession->cart()->totalPrice();
$coupon = $this->checkoutSession->cart()->getCouponCode();
if ($this->checkoutSession->cart()->hasNoShippingCosts($price, $coupon)) {
return \Response::json(['shippingCosts' => ["shop_id" => 1, 'country_id' => $country->id, "shipping_costs" => 0, "free_shipping" => NULL]]);
}
if (!$shippingCosts = $this->shippingService->getShippingCostsForCountryId($country->id))
return \Response::json(['error: can\'t find shipping costs for country with iso2:' . $countryCode]);
return \Response::json(['shippingCosts' => $shippingCosts->toArray()]);
}
}