get() public method

Finds an existing order item.
public get ( Buyable $buyable, $customfilter = [] ) : OrderItem
$buyable Buyable
return OrderItem the item requested, or false
 /**
  * Check to see if the shopping cart only contains downloadable
  * products.
  *
  * @return Boolean
  */
 public function onlyDownloadable()
 {
     $cart = ShoppingCart::get();
     foreach ($cart->getItems() as $item) {
         if (!$item->FindStockItem() instanceof DownloadableProduct) {
             return false;
         }
     }
     return true;
 }
 public function index($request)
 {
     $this->extend('onBeforeIndex');
     $site = SiteConfig::current_site_config();
     $order = $this->getOrderData();
     $cart = ShoppingCart::get();
     // Setup the paypal gateway URL
     if (Director::isDev()) {
         $gateway_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
     } else {
         $gateway_url = "https://www.paypal.com/cgi-bin/webscr";
     }
     $callback_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, "callback", $this->payment_gateway->ID);
     $success_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete');
     $error_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error');
     $back_url = Controller::join_links(Director::absoluteBaseURL(), Checkout_Controller::config()->url_segment, "finish");
     $fields = new FieldList(HiddenField::create('business', null, $this->payment_gateway->BusinessID), HiddenField::create('item_name', null, $site->Title), HiddenField::create('cmd', null, "_cart"), HiddenField::create('paymentaction', null, "sale"), HiddenField::create('invoice', null, $order->OrderNumber), HiddenField::create('custom', null, $order->OrderNumber), HiddenField::create('upload', null, 1), HiddenField::create('discount_amount_cart', null, number_format($cart->DiscountAmount, 2)), HiddenField::create('currency_code', null, Checkout::config()->currency_code), HiddenField::create('first_name', null, $order->FirstName), HiddenField::create('last_name', null, $order->Surname), HiddenField::create('address1', null, $order->Address1), HiddenField::create('address2', null, $order->Address2), HiddenField::create('city', null, $order->City), HiddenField::create('zip', null, $order->PostCode), HiddenField::create('country', null, $order->Country), HiddenField::create('email', null, $order->Email), HiddenField::create('return', null, $success_url), HiddenField::create('notify_url', null, $callback_url), HiddenField::create('cancel_return', null, $error_url));
     if (!Checkout::config()->simple_checkout && !$cart->isCollection()) {
         // Shipping Details
         $fields->add(HiddenField::create('shipping_addressee_name', null, $order->DeliveryFirstnames . " " . $order->DeliverySurname));
         $fields->add(HiddenField::create('shipping_address1', null, $order->DeliveryAddress1));
         $fields->add(HiddenField::create('shipping_address2', null, $order->DeliveryAddress2));
         $fields->add(HiddenField::create('shipping_city', null, $order->DeliveryCity));
         $fields->add(HiddenField::create('shipping_zip', null, $order->DeliveryPostCode));
         $fields->add(HiddenField::create('shipping_country', null, $order->DeliveryCountry));
     }
     $i = 1;
     foreach ($cart->getItems() as $item) {
         $fields->add(HiddenField::create('item_name_' . $i, null, $item->Title));
         $fields->add(HiddenField::create('amount_' . $i, null, number_format($item->Price, 2)));
         $fields->add(HiddenField::create('quantity_' . $i, null, $item->Quantity));
         $i++;
     }
     if (!Checkout::config()->simple_checkout && !$cart->isCollection()) {
         // Add shipping as an extra product
         $fields->add(HiddenField::create('item_name_' . $i, null, $order->PostageType));
         $fields->add(HiddenField::create('amount_' . $i, null, number_format($cart->PostageCost, 2)));
         $fields->add(HiddenField::create('quantity_' . $i, null, "1"));
     }
     // Add tax (if needed) else just total
     if ($cart->TaxCost) {
         $fields->add(HiddenField::create('tax_cart', null, number_format($cart->TaxCost, 2)));
     }
     $actions = FieldList::create(LiteralField::create('BackButton', '<a href="' . $back_url . '" class="btn btn-red checkout-action-back">' . _t('Checkout.Back', 'Back') . '</a>'), FormAction::create('Submit', _t('Checkout.ConfirmPay', 'Confirm and Pay'))->addExtraClass('btn')->addExtraClass('btn-green'));
     $form = Form::create($this, 'Form', $fields, $actions)->addExtraClass('forms')->setFormMethod('POST')->setFormAction($gateway_url);
     $this->customise(array("Title" => _t('Checkout.Summary', "Summary"), "MetaTitle" => _t('Checkout.Summary', "Summary"), "Form" => $form, "Order" => $order));
     $this->extend('onAfterIndex');
     return $this->renderWith(array("PayPal", "Payment", "Checkout", "Page"));
 }
 /**
  * Process the callback data from the payment provider
  */
 public function callback($request)
 {
     if (Director::isDev()) {
         $secret_key = StripePayment::config()->test_secret_key;
         $publish_key = StripePayment::config()->test_publish_key;
     } else {
         $secret_key = StripePayment::config()->live_secret_key;
         $publish_key = StripePayment::config()->live_publish_key;
     }
     Stripe::setApiKey($secret_key);
     $site = SiteConfig::current_site_config();
     $order = $this->getOrderData();
     $cart = ShoppingCart::get();
     $this->extend('onBeforeCallback');
     $error_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error');
     $data = $this->request->postVars();
     $status = "error";
     // Get the credit card details submitted by the form
     $token = $data['stripeToken'];
     $order_no = Session::get("StripePayment.OrderNumber");
     $order = Estimate::get()->filter("OrderNumber", $order_no)->first();
     if ($order_no && $order) {
         // Create the charge on Stripe's servers - this will charge
         // the user's card
         try {
             $success_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', $order_no);
             $charge = StripeCharge::create(array("amount" => round($order->Total->Value * 100), "currency" => strtolower(Checkout::config()->currency_code), "source" => $token, "metadata" => array("Order" => $order_no)));
             $order->convertToOrder();
             $order->write();
             $order = Order::get()->byID($order->ID);
             $order->Status = "paid";
             $order->PaymentProvider = "Stripe";
             $order->PaymentNo = $charge->id;
             $order->write();
             return $this->redirect($success_url);
         } catch (Exception $e) {
             $order->Status = "failed";
             $order->write();
             return $this->redirect($error_url);
         }
     } else {
         return $this->redirect($error_url);
     }
 }
 public function index($request)
 {
     $this->extend('onBeforeIndex');
     // Setup payment gateway form
     $order = $this->getOrderData();
     $cart = ShoppingCart::get();
     // Setup the gateway URL
     if (Director::isDev()) {
         $gateway_url = "https://secure-test.worldpay.com/wcc/purchase";
     } else {
         $gateway_url = "https://secure.worldpay.com/wcc/purchase ";
     }
     $callback_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, "callback", $this->payment_gateway->ID);
     $back_url = Controller::join_links(Director::absoluteBaseURL(), Checkout_Controller::config()->url_segment, "finish");
     $fields = FieldList::create(HiddenField::create('instId', null, $this->payment_gateway->InstallID), HiddenField::create('cartId', null, $order->OrderNumber), HiddenField::create('MC_callback', null, $callback_url), HiddenField::create('amount', null, number_format($cart->TotalCost, 2)), HiddenField::create('currency', null, Checkout::config()->currency_code), HiddenField::create('name', null, $order->FirstName . " " . $order->Surname), HiddenField::create('address1', null, $order->Address1), HiddenField::create('address2', null, $order->Address2), HiddenField::create('town', null, $order->City), HiddenField::create('region', null, $order->Country), HiddenField::create('postcode', null, $order->PostCode), HiddenField::create('country', null, $order->Country), HiddenField::create('email', null, $order->Email), HiddenField::create('tel', null, $order->PhoneNumber));
     // Create a string of items ordered (to manage the order via WorldPay)
     $desc_string = "";
     foreach ($cart->getItems() as $item) {
         $desc_string .= $item->Title . ' x ' . $item->Quantity . ', ';
     }
     if (!Checkout::config()->simple_checkout && !$cart->isCollection()) {
         // Add postage type to description
         $desc_string .= _t("Checkout.Postage", "Postage") . ': ' . $order->PostageType . '; ';
         // Add postage address to description
         $desc_string .= _t("Checkout.PostTo", "Post to") . ': ';
         $desc_string .= $order->DeliveryFirstnames . " " . $order->DeliverySurname . ', ';
         $desc_string .= $order->DeliveryAddress1 . ', ';
         $desc_string .= $order->DeliveryAddress2 ? $order->DeliveryAddress2 . ', ' : '';
         $desc_string .= $order->DeliveryCity . ', ';
         $desc_string .= $order->DeliveryCountry ? $order->DeliveryCountry . ', ' : '';
         $desc_string .= $order->DeliveryPostCode . ', ';
         $desc_string .= $order->DeliveryCountry;
     }
     $fields->add(HiddenField::create('desc', null, $desc_string));
     if (Director::isDev()) {
         $fields->add(HiddenField::create('testMode', null, '100'));
     }
     $actions = FieldList::create(LiteralField::create('BackButton', '<a href="' . $back_url . '" class="btn btn-red checkout-action-back">' . _t('Checkout.Back', 'Back') . '</a>'), FormAction::create('Submit', _t('Checkout.ConfirmPay', 'Confirm and Pay'))->addExtraClass('btn')->addExtraClass('btn-green'));
     $form = Form::create($this, 'Form', $fields, $actions)->addExtraClass('forms')->setFormMethod('POST')->setFormAction($gateway_url);
     $this->customise(array("Title" => _t('Checkout.Summary', "Summary"), "MetaTitle" => _t('Checkout.Summary', "Summary"), "Form" => $form, "Order" => $order));
     $this->extend("onAfterIndex");
     return $this->renderWith(array("Worldpay", "Payment", "Checkout", "Page"));
 }
 public function index($request)
 {
     $this->extend('onBeforeIndex');
     // Setup payment gateway form
     $site = SiteConfig::current_site_config();
     $order = $this->getOrderData();
     $cart = ShoppingCart::get();
     $pw = $this->payment_gateway->SHA;
     $sha_data = "";
     // Setup the gateway URL
     if (Director::isDev()) {
         $gateway_url = "https://mdepayments.epdq.co.uk/ncol/test/orderstandard.asp";
     } else {
         $gateway_url = "https://payments.epdq.co.uk/ncol/prod/orderstandard.asp";
     }
     $success_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete');
     $error_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error');
     $back_url = Controller::join_links(Director::absoluteBaseURL(), Checkout_Controller::config()->url_segment, "finish");
     $template_url = Controller::join_links(Director::absoluteBaseURL(), "BarclaycardEpdqDynamicTemplate");
     // Get an array of details, so we can generate a hash and convert
     // to hidden fields
     $data = array("PSPID" => $this->payment_gateway->PSPID, "ORDERID" => $order->OrderNumber, "AMOUNT" => round($cart->TotalCost * 100), "CURRENCY" => Checkout::config()->currency_code, "LANGUAGE" => i18n::get_locale(), "CN" => $order->FirstName . " " . $order->Surname, "EMAIL" => $order->Email, "OWNERADDRESS" => $order->Address1, "OWNERTOWN" => $order->City, "OWNERZIP" => $order->PostCode, "OWNERCTY" => $order->Country, "TITLE" => $site->Title, "BGCOLOR" => $this->payment_gateway->Background, "TXTCOLOR" => $this->payment_gateway->Text, "TBLBGCOLOR" => $this->payment_gateway->TableBackground, "TBLTXTCOLOR" => $this->payment_gateway->TableText, "BUTTONBGCOLOR" => $this->payment_gateway->ButtonBackground, "BUTTONTXTCOLOR" => $this->payment_gateway->ButtonText, "ACCEPTURL" => $success_url, "DECLINEURL" => $error_url, "EXCEPTIONURL" => $error_url, "CANCELURL" => $error_url, "TP" => $template_url);
     // Account for the fact the phone number might not be set
     if ($order->PhoneNumber) {
         $data["OWNERTELNO"] = $order->PhoneNumber;
     }
     $fields = FieldList::create();
     ksort($data);
     // Generate our SHA Key and add fields
     foreach ($data as $k => $v) {
         $fields->push(HiddenField::create($k, null, $v));
         $sha_data .= sprintf("%s=%s%s", $k, $v, $pw);
     }
     $hashed_data = strtoupper(hash("sha1", $sha_data));
     // Finally add out hashed data
     $fields->push(HiddenField::create("SHASign", null, $hashed_data));
     $actions = FieldList::create(LiteralField::create('BackButton', '<a href="' . $back_url . '" class="btn btn-red checkout-action-back">' . _t('Checkout.Back', 'Back') . '</a>'), FormAction::create('Submit', _t('Checkout.ConfirmPay', 'Confirm and Pay'))->addExtraClass('btn')->addExtraClass('btn-green'));
     $form = Form::create($this, 'Form', $fields, $actions)->addExtraClass('forms')->setFormMethod('POST')->setFormAction($gateway_url);
     $this->customise(array("Title" => _t('Checkout.Summary', "Summary"), "MetaTitle" => _t('Checkout.Summary', "Summary"), "Form" => $form, "Order" => $order));
     $this->extend("onAfterIndex");
     return $this->renderWith(array("BarclaysEpqd", "Payment", "Checkout", "Page"));
 }
 public function __construct($controller, $name = "BillingDetailsForm")
 {
     $personal_fields = CompositeField::create(HeaderField::create('PersonalHeader', _t('Checkout.PersonalDetails', 'Personal Details'), 3), TextField::create('FirstName', _t('Checkout.FirstName', 'First Name(s)')), TextField::create('Surname', _t('Checkout.Surname', 'Surname')), TextField::create("Company", _t('Checkout.Company', "Company"))->setRightTitle(_t("Checkout.Optional", "Optional")), EmailField::create('Email', _t('Checkout.Email', 'Email')), TextField::create('PhoneNumber', _t('Checkout.Phone', 'Phone Number')))->setName("PersonalFields")->addExtraClass('unit')->addExtraClass('size1of2')->addExtraClass('unit-50');
     $address_fields = CompositeField::create(HeaderField::create('AddressHeader', _t('Checkout.Address', 'Address'), 3), TextField::create('Address1', _t('Checkout.Address1', 'Address Line 1')), TextField::create('Address2', _t('Checkout.Address2', 'Address Line 2'))->setRightTitle(_t("Checkout.Optional", "Optional")), TextField::create('City', _t('Checkout.City', 'City')), TextField::create('PostCode', _t('Checkout.PostCode', 'Post Code')), CountryDropdownField::create('Country', _t('Checkout.Country', 'Country'), null, 'GB'))->setName("AddressFields")->addExtraClass('unit')->addExtraClass('size1of2')->addExtraClass('unit-50');
     $fields = FieldList::create(CompositeField::create($personal_fields, $address_fields)->setName("BillingFields")->addExtraClass('line')->addExtraClass('units-row'));
     // Add a save address for later checkbox if a user is logged in
     if (Member::currentUserID()) {
         $fields->add(CompositeField::create(CheckboxField::create("SaveAddress", _t('Checkout.SaveAddress', 'Save this address for later')))->setName("SaveAddressHolder")->addExtraClass('line')->addExtraClass('units-row'));
     }
     $back_url = Controller::join_links(BASE_URL, ShoppingCart::config()->url_segment);
     $actions = FieldList::create(LiteralField::create('BackButton', '<a href="' . $back_url . '" class="btn btn-red checkout-action-back">' . _t('Checkout.Back', 'Back') . '</a>'));
     if (ShoppingCart::get()->isCollection()) {
         $actions->add(FormAction::create('doSetDelivery', _t('Checkout.UseTheseDetails', 'Use these details'))->addExtraClass('btn')->addExtraClass('btn-green')->addExtraClass('checkout-action-next'));
     } else {
         $actions->add(FormAction::create('doSetDelivery', _t('Checkout.SetDeliveryAddress', 'Deliver to another address'))->addExtraClass('btn')->addExtraClass('checkout-action-next'));
         $actions->add(FormAction::create('doContinue', _t('Checkout.DeliverThisAddress', 'Deliver to this address'))->addExtraClass('btn')->addExtraClass('checkout-action-next')->addExtraClass('btn-green'));
     }
     $validator = new RequiredFields('FirstName', 'Surname', 'Address1', 'City', 'PostCode', 'Country', 'Email', 'PhoneNumber');
     parent::__construct($controller, $name, $fields, $actions, $validator);
 }
 public function index($request)
 {
     $this->extend("onBeforeIndex");
     $site = SiteConfig::current_site_config();
     $order = $this->getOrderData();
     $cart = ShoppingCart::get();
     $key = $this->payment_gateway->ConfigKey;
     $merchant_id = Director::isDev() ? "TEST" : $this->payment_gateway->MerchantID;
     $callback_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, "callback", $this->payment_gateway->ID);
     $return_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete');
     $back_url = Controller::join_links(Director::absoluteBaseURL(), Checkout_Controller::config()->url_segment, "finish");
     $payment_details = array('username' => $this->payment_gateway->Username, 'password' => $this->payment_gateway->Password, 'biller_code' => $this->payment_gateway->BillerCode, 'merchant_id' => $merchant_id, 'receipt_address' => $order->Email, 'payment_amount' => number_format($cart->TotalCost, 2), 'payment_reference' => $order->OrderNumber, 'payment_reference_minimum_length' => 10, 'payment_reference_maximum_length' => 20, 'payment_reference_text' => _t("PayWay.PaymentReferenceText", "Order Number"), 'return_link_url' => $return_url, 'reply_link_url' => $callback_url, 'reply_link_email' => $this->payment_gateway->PaymentReplyEmail, 'reply_link_post_type' => 'extended');
     foreach ($cart->getItems() as $item) {
         $payment_details[$item->Title] = $item->Quantity . ',' . number_format($item->Price, 2);
     }
     if (!Checkout::config()->simple_checkout) {
         $payment_details[$order->PostageType] = number_format($cart->PostageCost, 2);
     }
     // Add tax (if needed) else just total
     if ($cart->TaxCost) {
         $payment_details[_t("PayWay.Tax", 'Tax')] = number_format($cart->TaxCost, 2);
     }
     // If we cannot get payway's token, generate a friendly error
     try {
         $token = $this->get_token($payment_details);
     } catch (Exception $e) {
         error_log("Exception caught: " . $e->getMessage());
         $content = "<p>";
         $content = _t("PayWay.UnableToPayContent", "Please return to the previous page and try again");
         $content = "</p>";
         $content = '<p><a href="' . $back_url . '" class="btn">Back</a></p>';
         $this->customise(array("Title" => _t("PayWay.UnableToPay", "Unable to take payment"), "MetaTitle" => _t("PayWay.UnableToPay", "Unable to take payment"), "Content" => $content));
         return $this->renderWith(array("Page"));
     }
     $hand_off_url = Controller::join_links($this->config()->gateway_url, "MakePayment");
     $hand_off_url .= "?biller_code=" . $this->payment_gateway->BillerCode;
     $hand_off_url .= "&token=" . urlencode($token);
     $this->extend('onAfterIndex');
     return $this->redirect($hand_off_url);
 }
 public function index($request)
 {
     $this->extend('onBeforeIndex');
     $site = SiteConfig::current_site_config();
     $order = $this->getOrderData();
     $cart = ShoppingCart::get();
     $key = $this->payment_gateway->ConfigKey;
     $sofort = new SofortMultipayPayment($key);
     $sofort->setAmount(number_format($cart->TotalCost, 2));
     $sofort->setCurrencyCode(Checkout::config()->currency_code);
     $callback_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, "callback", $this->payment_gateway->ID);
     $success_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', $order->OrderNumber);
     $error_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error');
     $back_url = Controller::join_links(Director::absoluteBaseURL(), Checkout_Controller::config()->url_segment, "finish");
     $sofort->setSuccessUrl($success_url, true);
     $sofort->setAbortUrl($error_url);
     $sofort->setNotificationUrl($callback_url);
     $desc_string = "";
     foreach ($cart->getItems() as $item) {
         $desc_string .= $item->Title . ' x ' . $item->Quantity . ', ';
     }
     $sofort->setReason($desc_string);
     $sofort->sendRequest();
     $fields = new FieldList();
     $i = 1;
     $actions = FieldList::create(LiteralField::create('BackButton', '<a href="' . $back_url . '" class="btn btn-red checkout-action-back">' . _t('Checkout.Back', 'Back') . '</a>'));
     $form = Form::create($this, 'Form', $fields, $actions)->addExtraClass('forms')->setFormMethod('GET');
     if ($sofort->getPaymentUrl()) {
         $actions->add(FormAction::create('Submit', _t('Checkout.ConfirmPay', 'Confirm and Pay'))->addExtraClass('btn')->addExtraClass('btn-green'));
         $form->setFormAction($sofort->getPaymentUrl());
         // Set the Payment No to our order data (accessable by
         // onAfterIndex)
         $order->PaymentID = $sofort->getTransactionId();
     } else {
         $actions->add(LiteralField::create('BackButton', '<strong class="error">' . _t('Sofort.TransactionError', 'Error with transaction') . '</strong>'));
     }
     $this->customise(array("Title" => _t('Checkout.Summary', "Summary"), "MetaTitle" => _t('Checkout.Summary', "Summary"), "Form" => $form, "Order" => $order));
     $this->extend("onAfterIndex");
     return $this->renderWith(array("Sofort", "Payment", "Checkout", "Page"));
 }
 public function doAddItemToCart($data, $form)
 {
     $classname = $data["ClassName"];
     $id = $data["ID"];
     $customisations = array();
     $cart = ShoppingCart::get();
     if ($object = $classname::get()->byID($id)) {
         $price = $object->Price;
         foreach ($data as $key => $value) {
             if (!(strpos($key, 'customise') === false) && $value) {
                 $custom_data = explode("_", $key);
                 if ($custom_item = ProductCustomisation::get()->byID($custom_data[1])) {
                     $modify_price = 0;
                     // Check if the current selected option has a price modification
                     if ($custom_item->Options()->exists()) {
                         $option = $custom_item->Options()->filter("Title", $value)->first();
                     }
                     $customisations[] = array("Title" => $custom_item->Title, "Value" => $value, "Price" => $option->ModifyPrice);
                 }
             }
         }
         if ($object->TaxRateID && $object->TaxRate()->Amount) {
             $tax_rate = $object->TaxRate()->Amount;
         } else {
             $tax_rate = 0;
         }
         $item_to_add = array("Key" => (int) $data['ID'] . ':' . base64_encode(json_encode($customisations)), "Title" => $object->Title, "Content" => $object->Content, "BasePrice" => $price, "TaxRate" => $tax_rate, "CustomisationArray" => $customisations, "Image" => $object->Images()->first(), "StockID" => $object->StockID, "ID" => $object->ID, "ClassName" => $object->ClassName);
         $cart->add($item_to_add, $data['Quantity']);
         $cart->save();
         $message = _t('Checkout.AddedItemToCart', 'Added item to your shopping cart');
         $message .= ' <a href="' . $cart->Link() . '">';
         $message .= _t('Checkout.ViewCart', 'View cart');
         $message .= '</a>';
         $this->setSessionMessage("success", $message);
     } else {
         $this->owner->setSessionMessage("bad", _t("Checkout.ThereWasAnError", "There was an error"));
     }
     return $this->redirectBack();
 }
 public function doAddItemToCart($data, $form)
 {
     $classname = $data["ClassName"];
     $id = $data["ID"];
     $cart = ShoppingCart::get();
     $object = $classname::get()->byID($id);
     $parent = $object->ProductGroup();
     if ($object && $parent) {
         if ($parent->TaxRateID && $parent->TaxRate()->Amount) {
             $tax_rate = $parent->TaxRate()->Amount;
         } else {
             $tax_rate = 0;
         }
         $price = (int) $object->Price ? $object->Price : $parent->Price;
         $image = $object->Images()->exists() ? $object->SortedImages()->first() : $parent->SortedImages()->first();
         $weight = $object->Weight ? $object->Weight : $parent->Weight;
         $item_to_add = array("Key" => $object->ID, "Title" => $parent->Title . " - " . $object->Title, "Content" => $object->Content, "BasePrice" => $price, "TaxRate" => $tax_rate, "Image" => $image, "StockID" => $object->StockID, "ID" => $object->ID, "Weight" => $weight, "ClassName" => $object->ClassName);
         // Try and add item to cart, return any exceptions raised
         // as a message
         try {
             $cart->add($item_to_add, $data['Quantity']);
             $cart->save();
             $message = _t('GroupedProduct.AddedItemToCart', 'Added item to your shopping cart');
             $message .= ' <a href="' . $cart->Link() . '">';
             $message .= _t('GroupedProduct.ViewCartNow', 'View cart now');
             $message .= '</a>';
             $this->owner->setSessionMessage("success", $message);
         } catch (ValidationException $e) {
             $this->owner->setSessionMessage("bad", $e->getMessage());
         } catch (Exception $e) {
             $this->owner->setSessionMessage("bad", $e->getMessage());
         }
     } else {
         $this->setSessionMessage("bad", _t("GroupedProduct.ThereWasAnError", "There was an error"));
     }
     return $this->redirectBack();
 }
 public function complete()
 {
     $site = SiteConfig::current_site_config();
     $id = $this->request->param('ID');
     if ($id == "error") {
         $return = $this->error_data();
     } else {
         $return = $this->success_data();
     }
     $this->customise($return);
     // Extend our completion process, to allow for custom completion
     // templates
     $this->extend("onBeforeComplete");
     // Clear our session data
     if (isset($_SESSION)) {
         ShoppingCart::get()->clear();
         unset($_SESSION['Checkout.PostageID']);
         unset($_SESSION['Checkout.PaymentMethod']);
     }
     return $this->renderWith(array("Payment_complete_" . $this->payment_handler, "Payment_complete", "Checkout", "Page"));
 }
 public function complete()
 {
     $site = SiteConfig::current_site_config();
     $order = $this->getOrder();
     $id = $this->request->param('ID');
     if ($id == "error") {
         $return = $this->error_data();
     } else {
         $return = $this->success_data();
     }
     if ($order) {
         $return['CommerceOrderSuccess'] = true;
         $return['Order'] = $order;
     } else {
         $return['CommerceOrderSuccess'] = false;
         $return['Order'] = false;
     }
     // Clear our session data
     if (isset($_SESSION)) {
         ShoppingCart::get()->clear();
         unset($_SESSION['Commerce.Order']);
         unset($_SESSION['Commerce.PostageID']);
         unset($_SESSION['Commerce.PaymentMethod']);
     }
     return $this->customise($return)->renderWith(array("Payment_Response", 'Page'));
 }
 public function doAddItemToCart($data, $form)
 {
     $classname = $data["ClassName"];
     $id = $data["ID"];
     $customisations = array();
     $cart = ShoppingCart::get();
     if ($object = $classname::get()->byID($id)) {
         $price = $object->Price;
         foreach ($data as $key => $value) {
             if (!(strpos($key, 'customise') === false) && $value) {
                 $custom_data = explode("_", $key);
                 if ($custom_item = ProductCustomisation::get()->byID($custom_data[1])) {
                     $modify_price = 0;
                     // Deal with checkbox set fields to ensure data is a string
                     if (is_array($value)) {
                         $custom_value = implode(",", $value);
                     } else {
                         $custom_value = $value;
                     }
                     // Check if the current selected option has a price modification
                     if ($custom_item->Options()->exists()) {
                         $options = $custom_item->Options()->filter("Title", $value);
                         // If dealing with multiple results collect them, or return a single value
                         if ($options->exists() && $options->count() > 1) {
                             $custom_value = "";
                             foreach ($options as $option) {
                                 $modify_price = $modify_price + $option->ModifyPrice;
                                 $custom_value .= $option->Title;
                             }
                         } elseif ($options->exists()) {
                             $option = $options->first();
                             $modify_price = $option->ModifyPrice;
                         }
                     }
                     $customisations[] = array("Title" => $custom_item->Title, "Value" => $custom_value, "Price" => $modify_price);
                 }
             }
         }
         if ($object->TaxRateID && $object->TaxRate()->Amount) {
             $tax_rate = $object->TaxRate()->Amount;
         } else {
             $tax_rate = 0;
         }
         $item_to_add = array("Key" => (int) $data['ID'] . ':' . base64_encode(json_encode($customisations)), "Title" => $object->Title, "Content" => $object->Content, "BasePrice" => $price, "TaxRate" => $tax_rate, "CustomisationArray" => $customisations, "Image" => $object->Images()->first(), "StockID" => $object->StockID, "ID" => $object->ID, "ClassName" => $object->ClassName);
         // Try and add item to cart, return any exceptions raised
         // as a message
         try {
             $cart->add($item_to_add, $data['Quantity']);
             $cart->save();
             $message = _t('Commerce.AddedItemToCart', 'Added item to your shopping cart');
             $message .= ' <a href="' . $cart->Link() . '">';
             $message .= _t('Commerce.ViewCartNow', 'View cart now');
             $message .= '</a>';
             $this->setSessionMessage("success", $message);
         } catch (ValidationException $e) {
             $this->setSessionMessage("bad", $e->getMessage());
         } catch (Exception $e) {
             $this->setSessionMessage("bad", $e->getMessage());
         }
     } else {
         $this->setSessionMessage("bad", _t("Checkout.ThereWasAnError", "There was an error"));
     }
     return $this->redirectBack();
 }
 /**
  * Use to catch the users delivery details, if different to their billing
  * details
  *
  * @var array
  */
 public function delivery()
 {
     // If we are using simple checkout, skip
     if (Checkout::config()->simple_checkout) {
         return $this->redirect($this->Link('finish'));
     }
     // If customer is collecting, skip
     if (ShoppingCart::get()->isCollection()) {
         return $this->redirect($this->Link('finish'));
     }
     // Check permissions for guest checkout
     if (!Member::currentUserID() && !Checkout::config()->guest_checkout) {
         return $this->redirect($this->Link('index'));
     }
     $this->customise(array('Title' => _t('Checkout.DeliveryDetails', "Delivery Details"), 'Form' => $this->DeliveryForm()));
     $this->extend("onBeforeDelivery");
     return $this->renderWith(array('Checkout_delivery', 'Checkout', 'Page'));
 }
 /**
  * Find the total discount amount for this line item
  * 
  * @return Float
  */
 public function getDiscount()
 {
     $amount = 0;
     $cart = ShoppingCart::get();
     $items = $cart->TotalItems;
     $discount = $cart->getDiscount();
     if ($this->BasePrice && $discount && $discount->Amount) {
         if ($discount->Type == "Fixed") {
             $amount = $discount->Amount / $items * $this->Quantity;
         } elseif ($discount->Type == "Percentage") {
             $amount = $this->Price / 100 * $discount->Amount * $this->Quantity;
         }
     }
     return $amount;
 }
 public function __construct($controller, $name = "PostagePaymentForm")
 {
     if (!Checkout::config()->simple_checkout && !ShoppingCart::get()->isCollection()) {
         // Get delivery data and postage areas from session
         $delivery_data = Session::get("Checkout.DeliveryDetailsForm.data");
         $country = $delivery_data['DeliveryCountry'];
         $postcode = $delivery_data['DeliveryPostCode'];
         $cart = ShoppingCart::get();
         $postage_areas = new ShippingCalculator($postcode, $country);
         $postage_areas->setCost($cart->SubTotalCost)->setWeight($cart->TotalWeight)->setItems($cart->TotalItems);
         $postage_areas = $postage_areas->getPostageAreas();
         // Loop through all postage areas and generate a new list
         $postage_array = array();
         foreach ($postage_areas as $area) {
             $area_currency = new Currency("Cost");
             $area_currency->setValue($area->Cost);
             $postage_array[$area->ID] = $area->Title . " (" . $area_currency->Nice() . ")";
         }
         if (Session::get('Checkout.PostageID')) {
             $postage_id = Session::get('Checkout.PostageID');
         } elseif ($postage_areas->exists()) {
             $postage_id = $postage_areas->first()->ID;
         } else {
             $postage_id = 0;
         }
         if (count($postage_array)) {
             $select_postage_field = OptionsetField::create("PostageID", _t('Checkout.PostageSelection', 'Please select your preferred postage'), $postage_array)->setValue($postage_id);
         } else {
             $select_postage_field = ReadonlyField::create("NoPostage", "", _t('Checkout.NoPostageSelection', 'Unfortunately we cannot deliver to your address'))->addExtraClass("label")->addExtraClass("label-red");
         }
         // Setup postage fields
         $postage_field = CompositeField::create(HeaderField::create("PostageHeader", _t('Checkout.Postage', "Postage")), $select_postage_field)->setName("PostageFields")->addExtraClass("unit")->addExtraClass("size1of2")->addExtraClass("unit-50");
     } elseif (ShoppingCart::get()->isCollection()) {
         $postage_field = CompositeField::create(HeaderField::create("PostageHeader", _t('Checkout.CollectionOnly', "Collection Only")), ReadonlyField::create("CollectionText", "", _t("Checkout.ItemsReservedInstore", "Your items will be held instore until you collect them")))->setName("CollectionFields")->addExtraClass("unit")->addExtraClass("size1of2")->addExtraClass("unit-50");
     } else {
         $postage_field = null;
     }
     // Get available payment methods and setup payment
     $payment_methods = ArrayList::create();
     foreach (SiteConfig::current_site_config()->PaymentMethods() as $payment_method) {
         if ($payment_method->canView()) {
             $payment_methods->add($payment_method);
         }
     }
     // Deal with payment methods
     if ($payment_methods->exists()) {
         $payment_field = OptionsetField::create('PaymentMethodID', _t('Checkout.PaymentSelection', 'Please choose how you would like to pay'), $payment_methods->map('ID', 'Label'), $payment_methods->filter('Default', 1)->first()->ID);
     } else {
         $payment_field = ReadonlyField::create("PaymentMethodID", _t('Checkout.PaymentSelection', 'Please choose how you would like to pay'), _t('Checkout.NoPaymentMethods', 'You cannot pay at this time, if you feel there has been an error please contact us.'));
     }
     $payment_field = CompositeField::create(HeaderField::create('PaymentHeading', _t('Checkout.Payment', 'Payment'), 2), $payment_field)->setName("PaymentFields")->addExtraClass("unit")->addExtraClass("size1of2")->addExtraClass("unit-50");
     $fields = FieldList::create(CompositeField::create($postage_field, $payment_field)->setName("PostagePaymentFields")->addExtraClass("units-row")->addExtraClass("line"));
     $back_url = $controller->Link("billing");
     if ($payment_methods->exists()) {
         $actions = FieldList::create(LiteralField::create('BackButton', '<a href="' . $back_url . '" class="btn btn-red checkout-action-back">' . _t('Checkout.Back', 'Back') . '</a>'), FormAction::create('doContinue', _t('Checkout.PaymentDetails', 'Enter Payment Details'))->addExtraClass('btn')->addExtraClass('checkout-action-next')->addExtraClass('btn-green'));
     } else {
         $actions = FieldList::create();
     }
     $validator = RequiredFields::create(array("PostageID", "PaymentMethod"));
     parent::__construct($controller, $name, $fields, $actions, $validator);
 }
 /**
  * Get the current shoppingcart
  * 
  * @return ShoppingCart
  */
 public function getShoppingCart()
 {
     return ShoppingCart::get();
 }
 /**
  * Find relevent postage rates, based on supplied:
  * - Country
  * - Zip/postal code
  * - Weight
  * - Cost
  * - Number of Items
  * 
  * This is returned as an ArrayList that can be looped through.
  *
  * @return ArrayList
  */
 public function getPostageAreas()
 {
     $return = ArrayList::create();
     $config = SiteConfig::current_site_config();
     $cart = ShoppingCart::get();
     $discount = $cart->getDiscount();
     $filter_zipcode = strtolower(substr($this->zipcode, 0, 2));
     if ($this->include_wildcards) {
         $filter = array("Country:PartialMatch" => array($this->country_code, "*"), "ZipCode:PartialMatch" => array($filter_zipcode, "*"));
     } else {
         $filter = array("Country:PartialMatch" => $this->country_code, "ZipCode:PartialMatch" => $filter_zipcode);
     }
     // Find any postage areas that match our filter
     $postage_areas = $config->PostageAreas()->filter($filter);
     // Check if any discounts are set with free postage
     // This is a little hacky at the moment, need to find a nicer
     // way to add free shipping.
     if ($discount && $discount->Type == "Free Shipping" && (strpos($discount->Country, $this->country_code) !== false || $discount->Country == "*")) {
         $postage = Checkout::CreateFreePostageObject();
         $return->add($postage);
     }
     // Make sure we don't effect any associations
     foreach ($postage_areas as $item) {
         $return->add($item);
     }
     // Before doing anything else, remove any wildcards (if needed)
     $exact_country = false;
     // Find any countries that are exactly matched
     foreach ($return as $location) {
         if ($location->Country != "*") {
             $exact_country = true;
         }
     }
     // If exactly matched, remove any wildcards
     foreach ($return as $location) {
         if ($exact_country && $location->Country == "*" && $location->ID != -1) {
             $return->remove($location);
         }
     }
     // Now we have a list of locations, start checking for additional
     // rules an remove if not applicable.
     $total_cost = $this->cost;
     $total_weight = $this->weight;
     $total_items = $this->items;
     $max_cost = 0;
     $max_weight = 0;
     $max_items = 0;
     // First loop through and find items that are invalid
     foreach ($return as $location) {
         if ($location->Calculation == "Price" && $total_cost < $location->Unit) {
             $return->remove($location);
         }
         if ($location->Calculation == "Weight" && $total_weight < $location->Unit) {
             $return->remove($location);
         }
         if ($location->Calculation == "Items" && $total_items < $location->Unit) {
             $return->remove($location);
         }
     }
     // Now find max values based on units
     foreach ($return as $location) {
         if ($location->Calculation == "Price" && $location->Unit > $max_cost) {
             $max_cost = $location->Unit;
         }
         if ($location->Calculation == "Weight" && $location->Unit > $max_weight) {
             $max_weight = $location->Unit;
         }
         if ($location->Calculation == "Items" && $location->Unit > $max_items) {
             $max_items = $location->Unit;
         }
     }
     // Now loop through again and calculate which brackets each
     // Location fits in
     foreach ($return as $location) {
         if ($location->Calculation == "Price" && $location->Unit < $max_cost) {
             $return->remove($location);
         }
         if ($location->Calculation == "Weight" && $location->Unit < $max_weight) {
             $return->remove($location);
         }
         if ($location->Calculation == "Items" && $location->Unit < $max_items) {
             $return->remove($location);
         }
     }
     return $return;
 }