Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 27 ยท Extension types

Order Total Extensions

Write OpenCart order total extensions: the getTotal contract, sort order, discounts, fees and vouchers, how tax is collected, and rounding to cents.

The summary at the bottom of an OpenCart cart or checkout, with lines such as Sub-Total, Coupon, Shipping, Tax and Total, is not one calculation. It is a pipeline: a list of small order total extensions, each of which looks at the cart, adds its own line to a shared list, and changes the running total. Coupons, gift vouchers, reward points, handling fees, shipping and tax are all built this way. When you need a surcharge, a loyalty discount or a "round up for charity" line, you write an order total extension.

In this lesson you will learn the getTotal contract, why sort order matters so much, how discounts and fees interact with tax, and how to avoid rounding mistakes. The real OpenCart code is read-only here, because OpenCart cannot run on this site. The runnable examples are plain PHP stand-ins that follow the same idea. The money rules behind it are explained in Money as Integers and Taxes. The previous lesson, Building a Shipping Extension, produces the shipping line that this pipeline adds up.

How the pipeline runs

When OpenCart needs the totals (cart page, checkout, order confirmation), it builds three variables: an empty $totals list, an empty $taxes list and a $total number. It then loads each enabled extension of type total, in the order given by its sort order setting, and calls the extension's getTotal() method. Each call receives the three variables by reference, so it can append a line, add to the tax list, and change the running total. At the end, OpenCart adds the collected taxes as lines, which is why the Tax extension has a high sort order and the Total extension is last.

flowchart TD
    S["Start: totals = [], taxes = [], total = 0"] --> A["sub_total (sort 1)"]
    A --> B["your discount (sort 2)"]
    B --> C["shipping (sort 3)"]
    C --> D["your fee (sort 4)"]
    D --> E["tax (sort 5)"]
    E --> F["total (sort 9)"]
    F --> G["Show lines to the customer and store them in order_total"]

Each total extension is called in sort order with the same three shared variables; the result is stored with the order.

The finished lines are saved in the order_total table when the order is created. This matters later: the amounts are a snapshot. Changing the extension afterwards does not change old orders.

The getTotal contract

An extension of type total has an admin part (a settings form with status and sort order, as in Admin Settings Forms) and a catalog model. The catalog model lives in a model/total folder of your extension. A simplified version for OpenCart 4.0.2.x (read-only; names and types differ slightly in other versions, so compare with the core total extensions of your release):

PHP
<?php
namespace Opencart\Catalog\Model\Extension\Acme\Total;

class Handling extends \Opencart\System\Engine\Model {
    public function getTotal(array &$totals, array &$taxes, float &$total): void {
        if (!$this->config->get('total_handling_status')) {
            return;
        }

        $fee = (float)$this->config->get('total_handling_fee');

        if ($this->cart->getSubTotal() >= (float)$this->config->get('total_handling_free_over')) {
            return;
        }

        $this->load->language('extension/acme/total/handling');

        $totals[] = [
            'extension'  => 'acme',
            'code'       => 'handling',
            'title'      => $this->language->get('text_handling'),
            'value'      => $fee,
            'sort_order' => (int)$this->config->get('total_handling_sort_order')
        ];

        $tax_class_id = (int)$this->config->get('total_handling_tax_class_id');

        if ($tax_class_id) {
            $tax_rates = $this->tax->getRates($fee, $tax_class_id);

            foreach ($tax_rates as $tax_rate) {
                if (!isset($taxes[$tax_rate['tax_rate_id']])) {
                    $taxes[$tax_rate['tax_rate_id']] = $tax_rate['amount'];
                } else {
                    $taxes[$tax_rate['tax_rate_id']] += $tax_rate['amount'];
                }
            }
        }

        $total += $fee;
    }
}

Settings use the total_ prefix plus the extension code, as in total_handling_status. There are four things every getTotal() must get right:

  1. Return early when not applicable. A disabled or non-matching extension adds nothing. It must not add a zero line unless you want that line to show.
  2. Append one entry to $totals with code, title, value and sort_order. The value is a positive or negative number: discounts use a negative value so the line prints as a minus.
  3. Report tax through $taxes, keyed by tax rate id, if your line is taxable. The tax extension later turns the list into lines. Skip this and the fee is silently untaxed.
  4. Change $total by the same amount. Forgetting this is the classic bug where a line appears but the grand total does not move.

Why sort order matters

The sort order decides which lines each extension can see and what its percentage applies to. Typical defaults put Sub-Total first, discounts next, Shipping, then fees, Tax, and Total last. If your percentage discount is called after shipping, the shipping fee is now part of the base. If it is called before, it is not. Neither is right by itself; the correct choice is whatever the shop's rules say, so write it down and make the position adjustable in the settings.

Two more consequences:

  • A voucher (a stored credit) should usually run after tax, because it behaves like a payment and does not reduce the taxable amount. A discount usually runs before tax, because it reduces the price that is taxed. The right treatment depends on the country's rules, so check with the shop owner's accountant.
  • The Total extension (sort order last) must see the final running value. If your extension has a bigger sort order than Total, its line appears below the grand total and is never added to it.

Discounts, fees and rounding

Five percent of 49.99 is 2.4995, which has no exact cent value. If you keep floats, every extension rounds a little differently, and the sum of the displayed lines can be a cent away from the displayed total. Compute in integer cents and round exactly once per line with a rule you control. For tax, this means rounding per line or per rate consistently, the same way your tax setup does.

Another typical trap is a discount larger than the base. A 20.00 coupon on a 15.00 cart must not produce a negative total. Cap the discount at the amount it applies to, and record the real, capped value in the line.

The stand-in below builds a mini pipeline with the same moving parts: three extensions plus tax and total, each appending a line and adjusting shared state, executed in sort order. Everything is in cents, tax is collected per rate and added at the end, and the discount is capped.

PHP A totals pipeline in integer cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the extensions were passed in a shuffled order for cart A and are sorted by sortOrder() before running, just as OpenCart sorts by the saved setting. The coupon is 10 percent of the sub-total, VAT is calculated on the reduced base, and the handling fee appears only when the order is below the limit. The final line equals the sum of the lines above it, which is the property you should test for in your own extension.

Vouchers and credit-like lines

Gift vouchers and store credit differ from discounts in what they are. A discount lowers the price; a voucher is a payment method in disguise. Therefore it comes after tax, reduces only the amount to pay and never goes below zero. It also needs state: the used amount has to be saved when the order is confirmed, not when the cart is shown, otherwise a customer who only views the cart would consume the voucher. The core coupon, voucher and reward extensions do this in a separate step that runs when the order is confirmed (check the total models of your version for the exact method), and you can also react through Events. Tie the "use up" step to the confirmed order and make it safe to repeat. The same idea is described for payments in Idempotency.

Admin side checklist

Your extension also needs its admin controller and language files (see Anatomy of an Extension). The setting keys for a total extension are total_<code>_status and total_<code>_sort_order, and the admin form must offer both. Add the extension's own fields (fee amount, free-over limit, tax class) with the same prefix. Remember that the sort order is data the merchant changes, so never hard-code the position in the model.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are $totals, $taxes and $total passed by reference to getTotal()?

    The totals form a pipeline. Each extension appends its line, adds tax and changes the running total that later extensions see.
  2. 2. A discount extension should store its line value as

    A negative value prints as a deduction and reduces the running total when added to it.
  3. 3. Your fee line shows up in the cart but the grand total did not change. What is the most likely mistake?

    A line in $totals is only display data. The running $total must be changed too.
  4. 4. Where should a fixed-amount discount larger than the cart value be limited?

    Cap it where it is calculated, so the stored line and the total agree and the order never goes negative.

Summary

  • Order total extensions form a pipeline: each getTotal(&$totals, &$taxes, &$total) appends a line and updates shared state.
  • Sort order controls what each line can see, so make it a setting and put Total last and Tax before it.
  • Discounts use negative values and usually run before tax; vouchers behave like payments and run after tax.
  • Report taxable lines through $taxes, change $total by the same amount, and return early when not applicable.
  • Compute in integer cents, round once per line, and cap discounts so the total never goes negative.
  • Finished lines are stored with the order as a snapshot.

Next: Themes and Frontend Customisation