# 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.

Джерело: https://opencartcode.com/en/wiki/dev-flows/order-total-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

**Order total in OpenCart** is a chain of total modules, each of which adds its own row to the cart and [order totals](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#order-totals): 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](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-types)). In the admin they are located under [Extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) → 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 · OpenCart 4.1.0.4

| What | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Catalog model | `catalog/model/extension/total/{code}.php`, class `ModelExtensionTotal{Code}` | `extension/{ext}/catalog/model/total/{code}.php`, class `Opencart\Catalog\Model\Extension\{Ext}\Total\{Code}` |
| Signature | `getTotal($total)`, where `$total` is an array with references `totals`, `taxes`, `total` | `getTotal(array &$totals, array &$taxes, float &$total): void` |
| Who assembles the chain | controllers, e.g. `checkout/confirm` and `checkout/cart` | core 4.1 (catalog) calls `getTotal()` of each module |
| Core modules | sub_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 [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) 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.

```mermaid
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.

> Sorting in the admin is not cosmetic. If you change the order of modules "to make it look nicer", you change the order total. The core determines the display order of rows by the same `sort_order`, so you cannot separately configure "calculate it this way but display it differently" without code.

## 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 class](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#tax-class) 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](https://opencartcode.com/en/wiki/dev-mvc/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

```php
		// 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](https://opencartcode.com/en/wiki/dev-database/table-order-opencart).

### 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

```php
				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 delivery](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#cash-on-delivery) 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](https://opencartcode.com/en/wiki/dev-extensions/module-settings-form-opencart)):

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

```php
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](https://opencartcode.com/en/wiki/dev-flows/opencart-shopping-cart).
- 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](https://opencartcode.com/en/marketplace/product/promoaktsiyi-ta-podarunky-promotion-system).

## 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](https://opencartcode.com/en/wiki/dev-flows).

## 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.
