本文整理汇总了PHP中Cart::getProducts方法的典型用法代码示例。如果您正苦于以下问题:PHP Cart::getProducts方法的具体用法?PHP Cart::getProducts怎么用?PHP Cart::getProducts使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cart
的用法示例。
在下文中一共展示了Cart::getProducts方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getItemsFromCart
/**
* Returns cart items in a format useful for the
* API request
*
* Also adds discount as a cart item, since this is
* how Paypal expects to receive discounts
*
* @param Cart $cart
* @return array
*/
private function getItemsFromCart(Cart $cart)
{
$items = array();
foreach($cart->getProducts() as $product)
{
$item = new stdClass();
$item->name = $product->title;
$item->number = $product->sku;
$item->description = substr($product->short_description, 0, 127);
$item->amount = ShopDisplay::numberFormat($product->price);
$item->quantity = $product->quantity;
$items[] = $item;
}
if($cart->getDiscountAmount() > 0)
{
$item = new stdClass();
$item->name = 'Discount';
$item->description = $cart->getDiscountName();
$item->amount = -1 * $cart->getDiscountAmount();
$item->quantity = 1;
$items[] = $item;
}
return $items;
}
示例2: initContent
public function initContent()
{
parent::initContent();
$params = KwixoURLCallFrontController::ManageUrlCall();
$payment_ok = $params['payment_status'];
$errors = $params['errors'];
$id_order = $params['id_order'];
if ($id_order != false) {
$order = new Order($id_order);
$cart = new Cart($order->id_cart);
$products = $cart->getProducts();
$amount = $order->total_paid_tax_incl;
$total_shipping = $order->total_shipping;
} else {
$products = false;
$amount = false;
$total_shipping = false;
}
$link = new Link();
$this->context->smarty->assign('payment_ok', $payment_ok);
$this->context->smarty->assign('errors', $errors);
$this->context->smarty->assign('amount', $amount);
$this->context->smarty->assign('total_shipping', $total_shipping);
$this->context->smarty->assign('products', $products);
$this->context->smarty->assign('path_order', $link->getPageLink('order', true));
$this->context->smarty->assign('path_history', $link->getPageLink('history', true));
$this->context->smarty->assign('path_contact', $link->getPageLink('contact', true));
$this->setTemplate('urlcall.tpl');
}
示例3: showCartAction
/**
* @param Request $request
* @return string
* @throws Exception
*/
public function showCartAction(Request $request)
{
$cart = new Cart();
$productsId = $cart->getProducts();
$args = array('productsId' => $productsId);
return $this->render('cart', $args);
}
示例4: updateProductsTax
public static function updateProductsTax(AvalaraTax $avalaraModule, Cart $cart, $id_address, $region, $taxable = true)
{
$p = array();
foreach ($cart->getProducts() as $product) {
$avalaraProducts = array('id_product' => (int) $product['id_product'], 'name' => $product['name'], 'description_short' => $product['description_short'], 'quantity' => 1, 'total' => (double) 1000000, 'tax_code' => $taxable ? $avalaraModule->getProductTaxCode((int) $product['id_product']) : 'NT');
$p[] = $avalaraProducts;
// Call Avalara
$getTaxResult = $avalaraModule->getTax(array($avalaraProducts), array('type' => 'SalesOrder', 'DocCode' => 1, 'taxable' => $taxable));
// Store the taxrate in cache
// If taxrate exists (but it's outdated), then update, else insert (REPLACE INTO)
if (isset($getTaxResult['TotalTax']) && isset($getTaxResult['TotalAmount'])) {
$total_tax = $getTaxResult['TotalTax'];
$total_amount = $getTaxResult['TotalAmount'];
if ($total_amount == 0) {
$db_rate = 0;
} else {
$db_rate = (double) ($total_tax * 100 / $total_amount);
}
Db::getInstance()->Execute('REPLACE INTO `' . _DB_PREFIX_ . 'avalara_product_cache` (`id_product`, `tax_rate`, `region`, `update_date`, `id_address`)
VALUES (' . (int) $product['id_product'] . ', ' . $db_rate . ',
\'' . ($region ? pSQL($region) : '') . '\', \'' . date('Y-m-d H:i:s') . '\', ' . (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')} . ')');
}
}
return $p;
}
示例5: actionIndex
/**
* Action для главной страницы
*/
public function actionIndex()
{
// Список категорий для левого меню
$categories = Category::getCategoriesList();
// Список последних товаров
$latestProducts = Product::getLatestProducts(6);
// Список товаров для слайдера
$sliderProducts = Product::getRecommendedProducts();
// Показывыем в корзине информацию о добавленных товарах
$productsInCart = Cart::getProducts();
if ($productsInCart) {
// Если в корзине есть товары, получаем полную информацию о товарах для списка
// Получаем массив только с идентификаторами товаров
$productsIds = array_keys($productsInCart);
// Получаем массив с полной информацией о необходимых товарах
$products = Product::getProdustsByIds($productsIds);
// Получаем общую стоимость товаров
$totalPrice = Cart::getTotalPrice($products);
}
// Получаем идентификатор пользователя из сессии
$userId = $_SESSION['user'];
// Получаем информацию о пользователе из БД
$user = User::getUserById($userId);
// Подключаем вид
require_once ROOT . '/views/site/index.php';
return true;
}
示例6: actionCheckout
/**
* Action для страницы "Оформление покупки"
*/
public function actionCheckout()
{
$productsInCart = Cart::getProducts();
if ($productsInCart == false) {
header("Location: /");
}
$categories = Category::getCategoriesList();
// Находим общую стоимость
$productsIds = array_keys($productsInCart);
$products = Product::getProdustsByIds($productsIds);
$totalPrice = Cart::getTotalPrice($products);
// Количество товаров
$totalQuantity = Cart::countItems();
$userName = false;
$userPhone = false;
$userComment = false;
$result = false;
if (!User::isGuest()) {
// Если пользователь не гость
// Получаем информацию о пользователе из БД
$userId = User::checkLogged();
$user = User::getUserById($userId);
$userName = $user['name'];
} else {
// Если гость, поля формы останутся пустыми
$userId = false;
}
if (isset($_POST['submit'])) {
$userName = $_POST['userName'];
$userPhone = $_POST['userPhone'];
$userComment = $_POST['userComment'];
// Флаг ошибок
$errors = false;
if (!User::checkName($userName)) {
$errors[] = 'Неправильное имя';
}
if (!User::checkPhone($userPhone)) {
$errors[] = 'Неправильный телефон';
}
if ($errors == false) {
// Если ошибок нет
// Сохраняем заказ в базе данных
$result = Order::save($userName, $userPhone, $userComment, $userId, $productsInCart);
if ($result) {
// Если заказ успешно сохранен
// Оповещаем администратора о новом заказе по почте
$adminEmail = 'vlade1985@gmail.com';
$message = '<a href="localhost/admin/orders">Список заказов</a>';
$subject = 'Новый заказ!';
mail($adminEmail, $subject, $message);
// Очищаем корзину
Cart::clear();
}
}
}
// Подключаем вид
require_once ROOT . '/views/cart/checkout.php';
return true;
}
示例7: createUserInterface
/**
* @see ApplicationView::createUserInterface()
*/
protected function createUserInterface()
{
parent::createUserInterface();
$this->addStyle('/css/cart.css');
$resourceBundle = Application::getInstance()->getBundle();
$products = $this->cart->getProducts();
if (count($products) == 0) {
$this->contentPanel->addChild(new Heading(2))->addChild(new Text($resourceBundle->getString('CART_NO_PRODUCT')));
} else {
$this->contentPanel->addChild(new CartList())->setProductList($products);
$totalParagraph = $this->contentPanel->addChild(new Paragraph())->addStyle('cart-total');
//Total do carrinho
$totalParagraph->addChild(new Strong())->addChild(new Text($resourceBundle->getString('CART_TOTAL')));
$totalParagraph->addChild(new Span())->addChild(new Text(money_format($resourceBundle->getString('MONEY_FORMAT'), $this->cart->getTotal())));
//Botão de checkout
$totalParagraph->addChild(new Anchor('/?c=cart&a=checkout'))->addStyle('checkout')->addChild(new Text($resourceBundle->getString('CART_CHECKOUT')));
}
}
示例8: sendCampaign
public function sendCampaign()
{
// get abandoned cart :
$sql = "SELECT * FROM (\n\t\tSELECT\n\t\tCONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) `customer`, a.id_cart total, ca.name carrier, c.id_customer, a.id_cart, a.date_upd,a.date_add,\n\t\t\t\tIF (IFNULL(o.id_order, 'Non ordered') = 'Non ordered', IF(TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', a.`date_add`)) > 86400, 'Abandoned cart', 'Non ordered'), o.id_order) id_order, IF(o.id_order, 1, 0) badge_success, IF(o.id_order, 0, 1) badge_danger, IF(co.id_guest, 1, 0) id_guest\n\t\tFROM `" . _DB_PREFIX_ . "cart` a \n\t\t\t\tJOIN `" . _DB_PREFIX_ . "customer` c ON (c.id_customer = a.id_customer)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "currency` cu ON (cu.id_currency = a.id_currency)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "carrier` ca ON (ca.id_carrier = a.id_carrier)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "orders` o ON (o.id_cart = a.id_cart)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "connections` co ON (a.id_guest = co.id_guest AND TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', co.`date_add`)) < 1800)\n\t\t) AS toto WHERE id_order='Abandoned cart'";
$currency = Context::getContext()->currency->sign;
$defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$abandoned_carts = Db::getInstance()->ExecuteS($sql);
// get all available campaigns
$sqlCampaigns = 'SELECT * FROM `' . _DB_PREFIX_ . 'campaign` WHERE active=1';
$allCampaigns = Db::getInstance()->ExecuteS($sqlCampaigns);
// loop on all abandoned carts
foreach ($abandoned_carts as $abncart) {
// loop on all available campaigns
foreach ($allCampaigns as $camp) {
$cartIsOnCampaign = $this->checkIfCartIsOnCampaign($abncart['date_add'], $camp['execution_time_day'], $camp['execution_time_hour']);
if ($cartIsOnCampaign) {
$id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
$customer = new Customer($abncart['id_customer']);
$cR = new CartRule($camp['id_voucher'], $id_lang);
$cart = new Cart($abncart['id_cart']);
$products = $cart->getProducts();
$campM = new Campaign($camp['id_campaign']);
if (!empty($products)) {
$cart_content = $campM->getCartContentHeader();
} else {
$cart_content = '';
}
foreach ($products as $prod) {
$p = new Product($prod['id_product'], true, $id_lang);
$price_no_tax = Product::getPriceStatic($p->id, false, null, 2, null, false, true, 1, false, null, $abncart['id_cart'], null, $null, true, true, null, false, false);
$total_no_tax = $prod['cart_quantity'] * $price_no_tax;
$images = Image::getImages((int) $id_lang, (int) $p->id);
$link = new Link();
$cart_content .= '<tr >
<td align="center" ><img src="' . $link->getImageLink($p->link_rewrite, $images[0]['id_image']) . '" width="80"/></td>
<td align="center" ><a href="' . $link->getProductLink($p) . '"/>' . $p->name . '</a></td>
<td align="center" >' . Tools::displayprice($price_no_tax) . '</td>
<td align="center" >' . $prod['cart_quantity'] . '</td>
<td align="center" >' . Tools::displayprice($total_no_tax) . '</td>
</tr>';
}
$tpl_vars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{coupon_name}' => $cR->name, '{coupon_code}' => $cR->code, '{cart_content}' => $cart_content, '{coupon_value}' => $camp['voucher_amount_type'] == 'percent' ? $cR->reduction_percent . '%' : $currency . $cR->reduction_amount, '{coupon_valid_to}' => date('d/m/Y', strtotime($cR->date_to)), '{campaign_name}' => $camp['name']);
$path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/';
// send email to customer :
Mail::Send($id_lang, $campM->getFileName(), $camp['name'], $tpl_vars, $customer->email, null, null, null, null, null, $path, false, Context::getContext()->shop->id);
// Email to admin :
Mail::Send($id_lang, $campM->getFileName(), Mail::l(sprintf('Email sent to %s %s for campaign %s', $customer->lastname, $customer->firstname, $camp['name'])), $tpl_vars, Configuration::get('PS_SHOP_EMAIL'), null, null, null, null, null, $path, false, Context::getContext()->shop->id);
// echo 'ID ' . $abncart['id_cart'];
}
}
}
}
示例9: actionIndex
public function actionIndex()
{
$catObj = new Category();
$categories = $catObj->getCategoriesList();
$productsInCart = Cart::getProducts() ? Cart::getProducts() : false;
if ($productsInCart) {
$productIds = array_keys($productsInCart);
$products = Product::getProductsByIds($productIds);
$totalPrice = Cart::getTotalPrice($products);
}
require_once ROOT . '/views/cart/index.php';
return true;
}
示例10: LoginedAction
private function LoginedAction()
{
global $cookie, $smarty;
if (!isset($cookie->id_cart)) {
die('Shpping cart is empty!');
}
$cart = new Cart((int) $cookie->id_cart);
$user = new User((int) $cart->id_user);
$addresses = $user->getAddresses();
$carriers = Carrier::loadData();
$payments = PaymentModule::getHookPayment();
$smarty->assign(array('cart' => $cart, 'addresses' => $addresses, 'carriers' => $carriers, 'payments' => $payments, 'products' => $cart->getProducts(), 'discount' => $cart->discount, 'total' => $cart->getProductTotal()));
}
示例11: calculateShipping
/**
* Calculates shipping rates
*
* @param Cart $cart SHipping cart for which to calculate shipping
* @param null $service
* @internal param \Address $shipping_address Address to which products should be shipped
* @return int|mixed
*/
public function calculateShipping(Cart $cart, $service = NULL)
{
if($this->type == 'per_item')
{
$products = $cart->getProducts();
$total_quantity = 0;
foreach($products as $product)
$total_quantity += $product->quantity;
return $total_quantity * $this->price;
}
return $this->price;
}
示例12: actionCheckout
/**
* @return bool
* Метод для оформления заказа
*/
public function actionCheckout()
{
$productsInCart = Cart::getProducts();
if ($productsInCart == false) {
//Если корзина пустая,пользователь перенаправляется на главную
header("Location: /");
}
$categories = Category::getCategoriesList();
$productsIds = array_keys($productsInCart);
$products = Product::getProductsByIds($productsIds);
$totalPrice = Cart::getTotalPrice($products);
$totalItems = Cart::countItems();
//общее кол-во товаров
$userName = '';
$userPhone = '';
$userMessage = '';
$res = false;
//флаг успешного оформления заказа
$fail = '';
if (!User::isGuest()) {
$userId = User::isLogged();
//если пользователь не гость,получаем инфу о нем из БД
$user = User::getUserById($userId);
$userName = $user['name'];
} else {
$userId = false;
}
if (isset($_POST['submit'])) {
//Если форма отправлена,получаем данные для полей
$userName = $_POST['userName'];
$userPhone = $_POST['userPhone'];
$userMessage = $_POST['userMessage'];
if (!User::isValidNamePhone($userName, $userPhone)) {
$fail = 'Номер должен быть больше 9 символов/имя не может быть пустым';
}
//Если все ок,записываем заказ в БД
if ($fail == false) {
$res = Order::save($userName, $userPhone, $userId, $userMessage, $productsInCart);
if ($res) {
Cart::clearCart();
}
}
}
$args = array('categories' => $categories, 'productsInCart' => $productsInCart, 'productsIds' => $productsIds, 'products' => $products, 'totalPrice' => $totalPrice, 'totalItems' => $totalItems, 'fail' => $fail, 'res' => $res, 'userName' => $userName, 'userPhone' => $userPhone, 'userMessage' => $userMessage);
return self::render('checkout', $args);
}
示例13: confirmOrder
public function confirmOrder($custom)
{
$cart = new Cart((int) $custom['id_cart']);
$cart_details = $cart->getSummaryDetails(null, true);
$cart_hash = sha1(serialize($cart->nbProducts()));
$this->context->cart = $cart;
$address = new Address((int) $cart->id_address_invoice);
$this->context->country = new Country((int) $address->id_country);
$this->context->customer = new Customer((int) $cart->id_customer);
$this->context->language = new Language((int) $cart->id_lang);
$this->context->currency = new Currency((int) $cart->id_currency);
if (isset($cart->id_shop)) {
$this->context->shop = new Shop($cart->id_shop);
}
$this->createLog($cart->getProducts(true));
$mc_gross = Tools::getValue('mc_gross');
$total_price = Tools::ps_round($cart_details['total_price'], 2);
$message = null;
$result = $this->verify();
if (strcmp($result, VERIFIED) == 0) {
if ($mc_gross != $total_price) {
$payment = (int) Configuration::get('PS_OS_ERROR');
$message = $this->l('Price payed on paypal is not the same that on PrestaShop.') . '<br />';
} elseif ($custom['hash'] != $cart_hash) {
$payment = (int) Configuration::get('PS_OS_ERROR');
$message = $this->l('Cart changed, please retry.') . '<br />';
} else {
$payment = (int) Configuration::get('PS_OS_WS_PAYMENT');
$message = $this->l('Payment accepted.') . '<br />';
}
$customer = new Customer((int) $cart->id_customer);
$id_order = (int) Order::getOrderByCartId((int) $cart->id);
$transaction = array('currency' => pSQL(Tools::getValue(CURRENCY)), 'id_invoice' => pSQL(Tools::getValue(ID_INVOICE)), 'id_transaction' => pSQL(Tools::getValue(ID_TRANSACTION)), 'payment_date' => pSQL(Tools::getValue(PAYMENT_DATE)), 'shipping' => (double) Tools::getValue(SHIPPING), 'total_paid' => (double) Tools::getValue(TOTAL_PAID));
$this->validateOrder($cart->id, $payment, $total_price, $this->displayName, $message, $transaction, $cart->id_currency, false, $customer->secure_key);
$history = new OrderHistory();
$history->id_order = (int) $id_order;
$history->changeIdOrderState((int) $payment, (int) $id_order);
$history->addWithemail();
$history->add();
}
}
示例14: initContent
public function initContent()
{
parent::initContent();
$currency = new Currency((int) $this->context->cart->id_currency);
$paylater = new Paylater();
$id_module = $paylater->id;
if (Tools::getValue('c')) {
$cart = new Cart((int) Tools::getValue('c'));
$order_id = Order::getOrderByCartId((int) $cart->id);
$order = new Order($order_id);
$cart_products = $cart->getProducts();
$items = array();
foreach ($cart_products as $p) {
$items[] = array('id' => $p['id_product'], 'name' => $p['name'], 'sku' => $p['reference'], 'category' => $p['category'], 'price' => $p['price'], 'quantity' => $p['quantity']);
}
$analitics = Configuration::get('PAYLATER_ANALYTICS');
$this->context->smarty->assign(array('total' => $order->total_paid, 'currency' => $currency, 'currency_iso' => $currency->iso_code, 'id_module' => $id_module, 'id_cart' => $cart, 'order_id' => $order_id, 'shop_name' => Configuration::get('PS_SHOP_NAME'), 'shipping' => $order->total_shipping_tax_excl, 'total_w_tax' => $order->total_paid_tax_excl, 'tax' => $order->total_paid_tax_incl - $order->total_paid_tax_excl, 'items' => $items, 'analitics' => $analitics));
return $this->setTemplate('confirmation.tpl');
} else {
return $this->setTemplate('error.tpl');
}
}
示例15: hookDisplayPayment
public function hookDisplayPayment($params)
{
include_once _PS_MODULE_DIR_ . '/bluepay/bluepay_customers.php';
$cart = new Cart($this->context->cart->id);
$cart_contents = '';
foreach ($cart->getProducts() as $product) {
foreach ($product as $key => $value) {
if ($key == 'cart_quantity') {
$cart_contents .= $value . ' ';
}
if ($key == 'name') {
$cart_contents .= $value . '|';
}
}
}
$address = new Address((int) $cart->id_address_invoice);
$state = new State($address->id_state);
$cards = array();
$cards['visa'] = Configuration::get('BP_CARD_TYPES_VISA') == 'on';
$cards['mastercard'] = Configuration::get('BP_CARD_TYPES_MC') == 'on';
$cards['discover'] = Configuration::get('BP_CARD_TYPES_DISC') == 'on';
$cards['amex'] = Configuration::get('BP_CARD_TYPES_AMEX') == 'on';
$expiration_month = array();
for ($i = 1; $i < 13; $i++) {
$expiration_month[$i] = str_pad($i, 2, '0', STR_PAD_LEFT);
}
$expiration_year = array();
for ($i = 13; $i < 25; $i++) {
$expiration_year[$i] = $i;
}
$this->context->smarty->assign(array('payment_type' => Configuration::get('BP_PAYMENT_TYPE'), 'display_logo' => Configuration::get('BP_DISPLAY_LOGO'), 'secret_key' => Configuration::get('BP_SECRET_KEY'), 'account_id' => Configuration::get('BP_ACCOUNT_ID'), 'transaction_type' => Configuration::get('BP_TRANSACTION_TYPE'), 'payment_type' => Configuration::get('BP_PAYMENT_TYPE'), 'mode' => Configuration::get('BP_TRANSACTION_MODE'), 'customer' => $params['cookie']->customer_firstname . ' ' . $params['cookie']->customer_lastname, 'customer_address' => Tools::safeOutput($address->address1 . ' ' . $address->address2), 'customer_city' => Tools::safeOutput($address->city), 'customer_state' => $state->name, 'customer_zip' => Tools::safeOutput($address->postcode), 'customer_email' => $this->context->cookie->email, 'customer_country' => $address->country, 'invoice_id' => (int) $params['cart']->id, 'cards' => $cards, 'this_path' => $this->_path, 'cart' => $cart_contents, 'require_cvv2' => Configuration::get('BP_REQUIRE_CVV2'), 'allow_stored_payments' => Configuration::get('BP_ALLOW_STORED_PAYMENTS'), 'use_iframe' => Configuration::get('BP_CHECKOUT_IFRAME'), 'has_saved_payment_information' => BluePayCustomer::customerHasStoredPayment($params['cookie']->id_customer), 'has_saved_cc_payment_information' => BluePayCustomer::customerHasStoredCCPayment($params['cookie']->id_customer), 'saved_payment_information' => BluePayCustomer::getCustomerById($params['cookie']->id_customer), 'card_expiration_mm' => $expiration_month, 'card_expiration_yy' => $expiration_year, 'ach_account_types' => array('C' => 'Checking', 'S' => 'Savings')));
if (Configuration::get('BP_CHECKOUT_IFRAME') == 'No') {
return $this->display(__FILE__, 'views/templates/hook/payment.tpl');
}
return $this->display(__FILE__, 'views/templates/hook/payment_iframe.tpl');
}