No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Cart, checkout and orders in code

OpenCart Shopping Cart Library: How 3.0 and 4.1 Calculate the Cart

How the Cart library works in OpenCart 3.0 and 4.1: the cart table, guest cart lifetime, price calculation with options and discounts, taxes, and working with the cart from a module.

10 min read OC 3.0 OC 4.1

Cart in OpenCart is the system/library/cart/cart.php library, which the startup code registers as $this->cart. It stores cart items in the cart table of the database, not in the session, and on every request it rebuilds the products from that table: the current price with options and discounts, weight, stock, and reward points. All amounts the customer sees in the cart and at checkout start from the getProducts() method of this library.

Below is how it works in OpenCart 3.0 (the code is the same in 3.0.4.1 and 3.0.5.1) and in 4.1 (4.1.0.4), where the versions differ and what that means for modules. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

Where is the cart stored and how is it tied to the customer?

The object is created at catalog startup: in 3.0 in catalog/controller/startup/startup.php (new Cart\Cart($this->registry)), in 4.1 in catalog/controller/startup/application.php through $this->load->library('cart/cart', …). Before it, the registry already contains customer, session, tax, and weight, which the library takes in its constructor. How objects get into the registry is described in the article about Registry in OpenCart.

Each item is a row in the cart table. The library always looks for "its" rows by a combination of fields, and this combination is what distinguishes the versions.

WhatOpenCart 3.0OpenCart 4.1
Row owner keyapi_id + customer_id + session_idstore_id + customer_id + session_id
Subscriptionrecurring_idsubscription_plan_id
Optionsoption (JSON)option (JSON)
Field overridesnoneoverride (JSON)
Multistoreno store_id column, cart is shared across storesseparate cart for each store

In 3.0, the api_id field separates carts that the admin collects via the API when creating or editing an order from visitor carts. In 4.1 this field is not in the table, and override is used for the order editor.

How long does a guest's cart live, and what happens on login?

Both versions clean up old guest carts directly in the constructor, that is, on every storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → request, and this is where the versions differ most noticeably.

system/library/cart/cart.php · OpenCart 3.0.5.1 · lines 20–21

		// Remove all the expired carts with no customer ID
		$this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE (api_id > '0' OR customer_id = '0') AND date_added < DATE_SUB(NOW(), INTERVAL 1 HOUR)");

OpenCart 3.0: guest items are deleted one hour after they were added, not after the last activity. A customer who added a product, went to lunch, and came back will see an empty cart, even though the session is still alive. There is no limit for registered customers (customer_id > 0).

OpenCart 4.1: the threshold is taken from config_session_expire (in seconds; after installation it is 86400, that is, one day), and cleanup is limited to the current store. The value is set in System → Settings on the Server tab.

Server tab: session lifetime, on which the guest cart lifetime depends in 4.1
Server tab: session lifetime, on which the guest cart lifetime depends in 4.1 · OpenCart 4.1.0.4

Merging on login

When a customer is logged in, the constructor transfers the guest items of the current session to their cart. OpenCart 3.0 deletes each guest row and adds the product again via add(), so identical items merge with an increased quantity. OpenCart 4.1 runs two UPDATE queries: it changes session_id in the customer's existing rows and sets customer_id on the guest rows, updating date_added. Therefore in 4.1 the same product with the same options can end up in the cart as two rows. Keep this in mind if your module counts items by cart_id.

flowchart TD
  A["Request to catalog"] --> B["new Cart: clean up old guest rows"]
  B --> C{"Customer logged in?"}
  C -->|"Yes"| D["Move session guest rows to customer's cart"]
  C -->|"No"| E["Nothing"]
  D --> F["getProducts(): collect products from cart table"]
  E --> F
  F --> G["getSubTotal, getTaxes, getTotal, hasStock"]

How does getProducts() calculate the item price?

For each cart row, the library checks that the product exists in the current store, is enabled, and that date_available has already arrived. If not, or if the quantity is not greater than zero, the row is silently deleted via remove(). Next, for each option, price, points, and weight surcharges are calculated using the +/- prefixes from product_option_value. The order of applying discounts differs between versions.

OpenCart 3.0

  1. Base — product.price.
  2. If there is a row in product_discount for the customer's group with quantity not greater than the total quantity of this product in the cart, the price is replaced with its price.
  3. If there is an active special in product_special, the price is replaced once more, meaning the special beats the quantity discountA price that drops from a certain quantity onward: useful for wholesale. More in the glossary →.
  4. The sum of options is added to the result: 'price' => ($price + $option_price).

OpenCart 4.1

  1. Base — product.price + $option_price.
  2. If the row is tied to a subscription plan, the price becomes the plan price (or the trial price, if trial is enabled).
  3. One row is taken from product_discount (sorted by quantity DESC, priority ASC, price ASC) and applied according to the type field: F — fixed price plus options, P — percentage, S — amount subtraction.

system/library/cart/cart.php · OpenCart 4.1.0.4 · lines 232–243

					if ($product_discount_query->num_rows) {
						if ($product_discount_query->row['type'] == 'F') {
							// Fixed Price
							$price = $product_discount_query->row['price'] + $option_price;
						} elseif ($product_discount_query->row['type'] == 'P') {
							// Percentage
							$price -= ($price * ($product_discount_query->row['price'] / 100));
						} elseif ($product_discount_query->row['type'] == 'S') {
							// Subtract
							$price -= $product_discount_query->row['price'];
						}
					}

In 4.1 there is no separate product_special table: specials and quantity discounts are stored in product_discount, and the cart selects one row from them according to the sorting above. In addition, 4.1 supports variants: if a product has master_id, options are looked up on the master product, and values from variant marked in override are substituted automatically. How these tables are structured is described in the article about the product table and related tables.

Stock, minimum quantity, and keys that have changed

This is where modules ported from 3.0 to 4.1 most often break, because the item array keys have the same names but different meanings.

KeyOpenCart 3.0OpenCart 4.1
stockbool: whether there is enough stocknumber: product.quantity
stock_statusnonebool: whether there is enough stock
minimumminimum product quantitypresent among product fields
minimum_statusnonebool, plus the hasMinimum() method
recurring / subscriptionrecurring: array or falsesubscription: array (empty if there is no subscription)

A check of if (!$product['stock']) from a 3.0 module in 4.1 will only trigger when the stock is zero, not when it is insufficient for the ordered quantity. For 4.1, check stock_status or call hasStock().

There is also a difference in the product stock check itself. OpenCart 3.0 compares product.quantity with the quantity in one cart row, so two rows of the same product with different options, each for 3 units, will pass the check with a stock of 4. OpenCart 4.1 compares against the sum of all rows for this product ($product_total). Option valueA specific variant: "M," "L," "Red." More in the glossary → stock is checked per row in both versions.

What to do when stock is insufficient is determined by the config_stock_checkout and config_stock_warning settings on the Option tab: the checkout/cart controllerCode that receives a request and prepares data. More in the glossary → in both versions looks at hasStock() and these two checkboxes.

Option tab: the stock block determines whether checkout is allowed without availability
Option tab: the stock block determines whether checkout is allowed without availability · OpenCart 4.1.0.4

Aggregate methods and the cost of repeated calls

The library has a set of aggregating methods: getSubTotal(), getTaxes(), getTotal(), getWeight(), countProducts(), hasProducts(), hasStock(), hasShipping(), hasDownload(); in 3.0 also getRecurringProducts() and hasRecurringProducts(), and in 4.1 — getSubscriptions(), hasSubscription(), hasMinimum(), and has($cart_id). In 3.0, the methods getSubTotal(), getTaxes(), getTotal(), getWeight(), countProducts(), hasProducts(), hasStock(), and hasShipping() internally call getProducts().

OpenCart 3.0: getProducts() does not cache anything. Each aggregator call reads the cart table again and, for each item, makes queries for the product, options, discounts, specials, rewards, downloads, and subscriptions. A checkout page where the header, cart, and total modules together access the cart a dozen times easily generates hundreds of queries. A module on 3.0 should call getProducts() once and then work with the array.

OpenCart 4.1: the result is stored in the $this->data property, which the constructor fills immediately, and add(), update(), and clear() reset it. Repeated calls are free. But there is a consequence: if a module changed the cart table with direct SQL, the library will keep returning old data until the end of the request.

Taxes

getTaxes() groups amounts by tax_rate_id. OpenCart 3.0 multiplies the amount of each rate by the quantity. OpenCart 4.1 multiplies only percentage rates (type = 'P') by the quantity, and counts a fixed rate once per cart row. Therefore the same cart with a fixed tax can give different amounts in 3.0 and 4.1. For more on how these values get into order totals, see the section on order totals and the article about the order and order_total tables.

How to work with the cart from a module

The public methods for changing the cart are the same in meaning, but in 4.1 they are typed and have additional parameters.

ActionOpenCart 3.0OpenCart 4.1
Addadd($product_id, $quantity = 1, $option = array(), $recurring_id = 0)add(int $product_id, int $quantity = 1, array $option = [], int $subscription_plan_id = 0, array $override = [])
Change quantityupdate($cart_id, $quantity)update(int $cart_id, int $quantity)
Removeremove($cart_id)remove(int $cart_id)
Clearclear()clear()

Example: add a product with an option from a module controller

$product_id = (int)($this->request->post['product_id'] ?? 0);
$quantity   = max(1, (int)($this->request->post['quantity'] ?? 1));

// product_option_id => product_option_value_id; ключі приводимо до int і сортуємо
$option = [];

foreach ((array)($this->request->post['option'] ?? []) as $key => $value) {
	$option[(int)$key] = is_array($value) ? array_map('intval', $value) : $value;
}

ksort($option);

$this->cart->add($product_id, $quantity, $option);

$json['total'] = $this->cart->countProducts();

Note ksort(). The add() method looks for an existing row by an exact match of json_encode($option): the same set of options passed in a different order, or with string values instead of numbers, produces different JSON and creates a new row instead of increasing the quantity. Normalize the options array the same way everywhere the module adds a product. The library does not check required options: in the core this is done by the controller (checkout/cart/add in 3.0, checkout/cart.add in 4.1), and the module must repeat that check itself. Format the response for the AJAX "Buy" button according to the rules from the article AJAX in OpenCart.

How to change the calculation

The library has no hook methods for prices. OpenCart 4.1: library/* events exist, but for the cart library it is simpler and more reliable to change the result where it is used: via model/*/after or controller/*/after, or through the override field of the cart row, whose values overwrite the item keys in getProducts(). OpenCart 3.0: there are no events for libraries, so the formula itself can only be changed through OCMOD on system/library/cart/cart.php. Which option to choose for a specific task is covered in the article Events or OCMOD. For discounts and surcharges, it is usually better to write an order total module than to edit the cart.

Summary

  • The cart is stored in the cart table; a row belongs to the combination of customer_id + session_id plus api_id in 3.0 or store_id in 4.1.
  • A guest cart in 3.0 lives for one hour from when an item is added; in 4.1 it lives for config_session_expire seconds. On login, 3.0 merges items via add(), while 4.1 simply reassigns rows.
  • The item price is without tax. 3.0: base → discount → special → plus options. 4.1: base plus options → subscription → one row of product_discount with type F/P/S.
  • In 4.1 stock is a number, and the availability flag is stock_status; stock is compared against the sum of all product rows.
  • 3.0 recalculates the cart on every aggregator call; 4.1 caches the result within the request.
  • Normalize options before add(), otherwise the same product will end up in the cart as several rows.

Next, it is worth understanding how totals and orders are assembled from these items: the storage structure is described in the article about the order table, and all materials of this section are collected on the page Cart, checkout, and orders in code.

FAQ

Why does an item disappear from the cart without any action by the customer?
The library removes an item if the product is disabled, not yet available by date, not assigned to the current store, or has a quantity of zero. In 3.0, guest items are also removed one hour after being added.
Can a guest cart be kept longer than an hour in OpenCart 3.0?
Only by changing the DELETE condition in the library constructor via OCMOD, because the interval is set directly in the SQL there. Check how this will affect the size of the cart table, and add your own cleanup of old rows.
How do I get a specific customer's cart in the admin?
The Cart library only works with the current catalog visitor. In the admin, read the cart table directly by customer_id, and remember that prices there are not calculated: you need to calculate them using the same rules.
Why doesn't the header cart count update after a module adds a product?
The header cart block is rendered on the server or updated by a separate AJAX request. After adding the product, return the new quantity and total in JSON and update the block on the page, or reload it via the common/cart route.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.