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

Order total OpenCart: how subtotal, shipping, coupons and taxes add up

How OpenCart order total modules work in 3.0 and 4.1: getTotal chain, sort order, coupons, taxes, and writing your own total module.

10 min read OC 3.0 OC 4.1

Order total in OpenCart is a chain of total modules, each of which adds its own row to the cart and order totalsLines at the bottom: total, shipping, discount, coupon. Managed in "Extensions → Extensions": in the list of types, select "Order Totals." More in the glossary →: subtotal, shipping, coupon, reward points, taxes, and the final total. The core calls their getTotal() methods in sort order, passing three variables by reference: the array of rows, the array of taxes, and the current total. This means each next module sees the results of the previous ones. The final total total is written to order.total, and all rows go into the order_total table.

Below is how this works in OpenCart 3.0 (3.0.4.1 and 3.0.5.1) and 4.1 (4.1.0.4), where modules break on execution order and how to write a custom total. The examples are for OpenCart 4.1. In 4.0.x, model triggers and event handling differ.

Where do the total modules live and what types are there?

Total is one of the extension types, alongside payment, shipping, and modules (for extension types in general, see the article OpenCart module types). In the admin they are located under ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → → Extensions, filtered by Order Totals. Each has a status and a sort order, which are stored in the setting table with the keys total_{code}_status and total_{code}_sort_order.

Extensions → Order Totals: status and sort order of each module
Extensions → Order Totals: status and sort order of each module · OpenCart 4.1.0.4
WhatOpenCart 3.0OpenCart 4.1
Catalog modelcatalog/model/extension/total/{code}.php, class ModelExtensionTotal{Code}extension/{ext}/catalog/model/total/{code}.php, class Opencart\Catalog\Model\Extension\{Ext}\Total\{Code}
SignaturegetTotal($total), where $total is an array with references totals, taxes, totalgetTotal(array &$totals, array &$taxes, float &$total): void
Who assembles the chaincontrollers, e.g. checkout/confirm and checkout/cartcore 4.1 (catalog) calls getTotal() of each module
Core modulessub_total, reward, shipping, coupon, tax, credit, voucher, total, handling, low_order_fee, etc.sub_total, reward, shipping, coupon, tax, credit, total, handling, low_order_fee

In 4.1, the core order total modules do not include voucher, and sub_total counts only cart->getSubTotal(). In 3.0, sub_total also adds gift certificates from the session to the subtotal of products.

How does the core go through the getTotal chain?

The algorithm is the same in both branches:

  1. An empty array $totals, a sum $total = 0, and an array $taxes are created, immediately filled with the product taxes from $this->cart->getTaxes() (key tax_rate_id).
  2. From the list of installed total-type extensions, those with total_{code}_status enabled are taken and sorted by total_{code}_sort_order.
  3. For each one, getTotal() is called. The module can add a row to $totals, change $total, and change $taxes.
  4. After the pass, the $totals array is sorted once more by the sort_order field of the rows themselves. This is the order in which the customer sees them.

Why in 3.0 the parameter has no &: models are called through a proxy with __call, which does not pass arguments by reference. So the 3.0 controllerCode that receives a request and prepares data. More in the glossary → puts references to the variables ('totals' => &$totals, etc.) into an array and passes the array itself. Changes to the elements inside the model reach the controller's variables. In 4.1, the core receives a closure from the proxy and calls it directly, ($this->model_…->getTotal)($totals, $taxes, $total), so references work normally.

flowchart TD
  A["taxes = cart->getTaxes(), total = 0"] --> B["sub_total: + product sum"]
  B --> C["reward: − points"]
  C --> D["shipping: + delivery, + delivery tax in taxes"]
  D --> E["coupon: − discount, − part of taxes"]
  E --> F["tax: rows from taxes, + to total"]
  F --> G["credit: − customer balance"]
  G --> H["total: final row"]

The order in the diagram reflects the sort_order values after installation in both branches: sub_total 1, reward 2, shipping 3, coupon 4, tax 5, credit 7, total 9 (in 3.0 also voucher 8).

Why does the sort order break taxes and coupons?

Modules don't calculate anything "from scratch": each sees only what the previous ones have done. This creates several strict dependencies.

  • tax must come after everything that changes $taxes. The tax module simply converts each non-zero element of $taxes into a row and adds it to the total. Shipping adds to $taxes the tax on its cost, and the coupon subtracts the tax from the discount. If you place tax before shipping or coupon, these changes will not reach the total.
  • total must be last. It calculates nothing and only records the current value of $total. Anything that comes after it will change the order total but not the "Total" row. OpenCart 3.0 clamps a negative result to zero (max(0, $total['total'])), while OpenCart 4.1 writes $total as is.
  • A coupon limits the discount to the current total. If the discount is greater than the already accumulated $total, it is reduced to it. So a coupon placed before shipping cannot make shipping free with a fixed discount, because it will have nothing to subtract from.

How does a coupon calculate the discount and tax?

The coupon module is the most complex of the standard ones, and it clearly shows how a total has to work with taxes.

  1. The coupon is taken from $this->session->data['coupon'] and checked for dates, minimum amount, usage limits, and binding to products or categories.
  2. If the coupon is tied to products, the base for the discount is the sum of only those items; otherwise, it is cart->getSubTotal().
  3. For type F (fixed amount), the discount is capped at the base and distributed across items in proportion to their sums; for P, it is a percentage of each item's sum.
  4. For each item with a tax classA rule for calculating tax on a product. Many Ukrainian stores do not show VAT separately. More in the glossary → from $taxes, only the percentage tax rates are subtracted from the discount; the coupon does not touch fixed taxes.
  5. If the coupon gives free shipping, the cost of the selected shipping is added to the discount, and its percentage tax is subtracted from $taxes.
  6. The row is added with a negative value, and $total is reduced by the discount.

An important detail that later causes trouble when confirming an order: the row name is built from the language key text_coupon (in the English file Coupon (%s)), and the coupon's confirm() method extracts the coupon code from the row name, namely the text between the first ( and the last ). If you remove the brackets in a translation, the coupon usage history will not be recorded, and the uses_total/uses_customer limits will stop working. Check this when you edit the module's language files. The rules for working with them are in the article about OpenCart language files.

How are totals stored and confirmed in the order?

When an order is created, the $totals array goes into $order_data['totals'], and the final total goes into $order_data['total']. The checkout/order model writes each row to the order_total table.

catalog/model/checkout/order.php · OpenCart 4.1.0.4 · lines 104–109

		// Totals
		if (!empty($data['totals'])) {
			foreach ($data['totals'] as $total) {
				$this->model_checkout_order->addTotal($order_id, $total);
			}
		}

The order_total columns are: order_id, code, title, value, sort_order; in 4.1, extension was added, by which the core later finds the module's model. Therefore in 4.1, the row added by your module must contain the key 'extension' with your extension's code, otherwise the model will not be found when the status changes. The structure of the order tables is described in the article about order, order_total and order_history.

confirm and unconfirm

When an order first moves into a status from the "processing" or "complete" groups (config_processing_status, config_complete_status), the core goes through the order_total rows and calls the confirm method of each module that has one. This is how the coupon records its usage history, reward points are deducted, and the customer's balance is reduced.

catalog/model/checkout/order.php · OpenCart 3.0.5.1 · lines 306–318

				foreach ($order_totals as $order_total) {
					$this->load->model('extension/total/' . $order_total['code']);

					if (property_exists($this->{'model_extension_total_' . $order_total['code']}, 'confirm')) {
						// Confirm coupon, vouchers and reward points
						$fraud_status_id = $this->{'model_extension_total_' . $order_total['code']}->confirm($order_info, $order_total);

						// If the balance on the coupon, vouchers and reward points is not enough to cover the transaction or has already been used then the fraud order status is returned.
						if ($fraud_status_id) {
							$order_status_id = $fraud_status_id;
						}
					}
				}

If confirm() returns a non-zero status id, the order receives that status. This is how the core sets a fraud status when the coupon has already been exhausted. When an order leaves these status groups, unconfirm is called to restore the usage. The signatures differ: OpenCart 3.0 uses unconfirm($order_id), OpenCart 4.1 uses unconfirm(array $order_info). The moment of the call is determined by the status change method in catalog/model/checkout/order.php: OpenCart 3.0 — addOrderHistory(), OpenCart 4.1 — addHistory().

How to write your own total module

A typical task is adding a row such as "Cash on deliveryPayment upon receipt. It increases the risk of parcel refusals. More in the glossary → fee" or "Packaging". The catalog model for 4.1 minimally looks like this (the admin part with status and sorting is built as a regular settings form; see the module settings form):

Example: extension/mymodule/catalog/model/total/packing.php · OpenCart 4.1

namespace Opencart\Catalog\Model\Extension\Mymodule\Total;
class Packing extends \Opencart\System\Engine\Model {
	public function getTotal(array &$totals, array &$taxes, float &$total): void {
		if (!$this->cart->hasShipping()) {
			return;
		}

		$this->load->language('extension/mymodule/total/packing');

		$cost = (float)$this->config->get('total_packing_cost');
		$tax_class_id = (int)$this->config->get('total_packing_tax_class_id');

		if ($cost <= 0) {
			return;
		}

		$totals[] = [
			'extension'  => 'mymodule',
			'code'       => 'packing',
			'title'      => $this->language->get('text_packing'),
			'value'      => $cost,
			'sort_order' => (int)$this->config->get('total_packing_sort_order')
		];

		if ($tax_class_id) {
			foreach ($this->tax->getRates($cost, $tax_class_id) as $tax_rate) {
				$taxes[$tax_rate['tax_rate_id']] = ($taxes[$tax_rate['tax_rate_id']] ?? 0) + $tax_rate['amount'];
			}
		}

		$total += $cost;
	}
}

For 3.0, the logic is the same, but the class is ModelExtensionTotalPacking in catalog/model/extension/total/packing.php, the method is getTotal($total), and all accesses go through array elements: $total['totals'][] = …, $total['taxes'][$id] += …, $total['total'] += $cost. The extension key in the row is not needed for 3.0.

Rules to follow:

  • Choose sort_order deliberately: a fee that is taxed goes before tax (less than 5 by default), a discount that should reduce the final amount goes before total (less than 9).
  • Do not recalculate what is already in $total; work with the increment.
  • Do not read prices directly from the database: use $this->cart->getProducts(), which already accounts for options and discounts. How the library calculates them is described in the article about the Cart library.
  • If the module "spends" something (points, a promotion limit), implement confirm() and unconfirm(), and do not deduct in getTotal(): the latter is called on every view of the cart.

For complex promotions, such as "second item at a discount" or gifts, it is easier to use a ready-made solution than to extend your own total, for example Promotions and Gifts.

Summary

  • Order totals are a chain of getTotal() that jointly change $totals, $taxes, and $total; the order is set by total_{code}_sort_order.
  • In 3.0, the model receives an array of references ($total['totals'], etc.); in 4.1, three arguments by reference.
  • tax must come after shipping and the coupon, total last; 3.0 clamps a negative total to zero, 4.1 does not.
  • A coupon subtracts only percentage taxes from the discount and extracts its code from the row name, so do not remove the brackets from the translation.
  • Rows are stored in order_total (in 4.1 with the extension column), and confirm/unconfirm are called when entering and leaving processing statuses; the unconfirm signature differs between versions.

The next step is to understand how totals and products get into an order during checkout. All articles in the section are collected on the page Cart, checkout and orders in code.

FAQ

Why can the total in the cart and in the order differ?
Totals are recalculated at every step from the current session data: the selected shipping method, coupon, reward points and the address used for taxes. If the address or shipping cost changes between steps, the total changes too, and the order is saved with the value at the moment of confirmation.
Can you hide a total line but still include it in the sum?
Not by default: a line added to totals is displayed, and without the line the sum would change unnoticed by the customer. If you need this, change the cart and email templates, but for transparency it's better to show all components of the sum.
Why is the coupon available again after the order status changes?
If the order leaves the processing and complete status groups, the core calls the coupon's unconfirm, and the usage history record is deleted. This is standard behavior for cancelled orders.
Can you edit order_total manually in the database?
Technically yes, but order.total, order_total and the amounts in payment systems and reports must match. Change amounts through order editing in the admin so the totals are recalculated through the module chain.
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.