Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 27 ยท Extension types

Building a Shipping Extension

Build an OpenCart shipping extension: the getQuote contract, the quote array, geo zones, tax classes, weight tiers, free-shipping thresholds and caching.

A shipping extension answers one question at checkout: "How much will it cost to send this cart to this address, and which options can the customer pick?" OpenCart asks every enabled shipping extension that question, collects the answers, and shows them as the list of delivery methods. Flat rate, weight based, pickup and free shipping all work this way, and so does a connection to a carrier's rate service.

In this lesson you will learn the contract your model has to fulfil (getQuote), the exact shape of the quote array, how geo zones, tax classes and settings fit in, and how to design weight-based and threshold-based rates. 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 logic, so you can test the rules. If you want the business side of shipping first, read Shipping Rates and Delivery Options. Files and folders are explained in Anatomy of an Extension.

How checkout finds your quotes

When a customer reaches the shipping step, the catalog code loads the list of installed shipping extensions, skips those whose status is off, and for each one loads its catalog model and calls getQuote() with the delivery address. Whatever it returns is merged into one list, sorted by each method's sort_order, and the customer's choice is stored in the session.

flowchart LR
    A["Checkout asks for shipping methods"] --> B["For each enabled shipping extension"]
    B --> C["Load model and call getQuote(address)"]
    C --> D{"Empty array?"}
    D -->|"yes"| E["Method is not offered"]
    D -->|"no"| F["Add to method list"]
    F --> G["Sort by sort_order and show"]

Checkout calls getQuote on every enabled shipping extension; an empty array means "not available for this address".

Note the last point: an extension that does not apply, for example because the address is outside its zone, simply returns an empty array. It does not throw an error.

The files of a shipping extension

A shipping extension has an admin side (settings form) and a catalog side (the model that makes quotes). In OpenCart 4 the paths below sit inside your extension folder (read-only tree, names are examples):

TEXT
extension/acme/
  install.json
  admin/
    controller/shipping/zoneweight.php     settings form
    language/en-gb/shipping/zoneweight.php labels
    view/template/shipping/zoneweight.twig form
  catalog/
    model/shipping/zoneweight.php          getQuote()
    language/en-gb/shipping/zoneweight.php method title

Settings are saved in the setting table under keys that begin with shipping_ plus your extension code, for example shipping_zoneweight_status and shipping_zoneweight_sort_order. How the admin form saves them is covered in Admin Settings Forms.

The getQuote contract

This is a simplified version of a model for OpenCart 4.0.2.x. The exact class names, namespace and signature differ a little between 4.0.x and 4.1.x, so compare with the shipping extensions shipped with your version before copying anything (read-only):

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

class Zoneweight extends \Opencart\System\Engine\Model {
    public function getQuote(array $address): array {
        $this->load->language('extension/acme/shipping/zoneweight');

        $geo_zone_id = (int)$this->config->get('shipping_zoneweight_geo_zone_id');

        $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone_to_geo_zone`
            WHERE `geo_zone_id` = '" . $geo_zone_id . "'
            AND `country_id` = '" . (int)$address['country_id'] . "'
            AND (`zone_id` = '" . (int)$address['zone_id'] . "' OR `zone_id` = '0')");

        $status = ($this->config->get('shipping_zoneweight_status') && $query->num_rows);

        $method_data = [];

        if ($status) {
            $weight = $this->cart->getWeight();
            $cost = $this->costForWeight($weight); // your own pure logic

            $quote_data = [];
            $quote_data['zoneweight'] = [
                'code'         => 'zoneweight.zoneweight',
                'name'         => $this->language->get('text_description'),
                'cost'         => $cost,
                'tax_class_id' => $this->config->get('shipping_zoneweight_tax_class_id'),
                'text'         => $this->currency->format(
                    $this->tax->calculate($cost, $this->config->get('shipping_zoneweight_tax_class_id'), $this->config->get('config_tax')),
                    $this->session->data['currency']
                )
            ];

            $method_data = [
                'code'       => 'zoneweight',
                'name'       => $this->language->get('text_title'),
                'quote'      => $quote_data,
                'sort_order' => $this->config->get('shipping_zoneweight_sort_order'),
                'error'      => false
            ];
        }

        return $method_data;
    }
}

Read it in three parts:

  1. The zone check. A geo zone is a named group of country and region pairs configured under System > Localisation > Geo Zones. The table zone_to_geo_zone links a geo zone to countries and zones, where a zone_id of 0 means "the whole country". The query asks: is this address inside the zone chosen in the settings? Notice the (int) casts around everything that comes from the address, which is the SQL safety habit from Models, the Registry and the Database.
  2. The status. The method is offered only when the setting is on and the address is in the zone.
  3. The returned array. One method (your extension) containing one or more quotes.

The shape of the quote array

The returned structure has two levels. The outer level describes the shipping method (your extension), and the inner quote array holds the choices under it. A carrier extension usually returns several inner quotes (standard, express, next day), while a flat rate has one.

Key Level Meaning
code method Extension code, such as zoneweight
name method Title shown as the group heading
quote method Array of choices, keyed by a short code
sort_order method Position among all shipping methods
error method false, or a message when the method is listed but failed
code quote extensioncode.quotecode, for example zoneweight.zoneweight
name quote Text shown next to the radio button
cost quote Price before tax as a number
tax_class_id quote Tax class used to add tax on top; 0 for none
text quote The already formatted price string

The code of a quote is what gets stored in the session when the customer picks it. Later, the order total step looks up the matching shipping total by splitting that code into the extension and the quote. That is why a quote code must be stable: never put a price or a changing timestamp in it.

The cost is the net price. The text shows the price including tax when the store is configured to display prices with tax. The tax itself is added again in the totals step (see Order Total Extensions), which is why you pass the tax_class_id rather than a gross price.

Pricing rules: weight, price and thresholds

Most shipping extensions boil down to a small table of rules. Typical ones:

  • Weight tiers. Up to 1 kg costs a, up to 5 kg costs b, up to 20 kg costs c. OpenCart's own weight-based extension stores such a list per geo zone as weight:cost pairs in a setting. The cart provides $this->cart->getWeight(), already converted to the store's default weight class.
  • Price tiers. The same idea using $this->cart->getSubTotal() instead of weight.
  • Free shipping threshold. If the sub-total is at least a limit, the cost is 0. The method is still returned (with cost 0), so customers see "Free shipping" instead of nothing. A common mistake is to compare against a total that already includes the shipping you are computing.
  • No match. If the weight is above the highest tier, return an empty array or an error message, not a cost of zero.

Keep this decision logic in a plain class that does not touch the registry. It is then easy to test, which Testing and Debugging Extensions builds on, and money should be handled in integer cents as described in Money as Integers.

A rate calculator stand-in

The stand-in below is not OpenCart code. It is the pure logic such a model would delegate to: geo zones made of country codes, weight tiers per zone, a free threshold, and a tax class applied for the displayed text. Everything is in integer cents, so the output is exact.

PHP Zones, weight tiers and free shipping

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.

The three outcomes match what a real getQuote() must handle: an empty array for Japan (outside every zone), an error entry for the 9 kg parcel to Europe (no matching tier), and normal quotes, where the 120.00 order gets free shipping. The shown price includes 20 percent tax, while cost stays net.

Caching remote rates

If your extension calls a carrier's rate service, remember that getQuote() can run many times per visit: when the customer opens the cart estimator, when the shipping step loads, and when the checkout refreshes. Calling a slow remote API each time makes checkout feel broken. Three rules help:

  • Build a cache key from everything that changes the price: destination, total weight, parcel count and currency. Never reuse a rate when one of them differs.
  • Use OpenCart's cache class ($this->cache->get() and ->set(), expiry is set globally to one hour by default) or keep the last answer in the session for the duration of checkout. Make sure the cache does not keep rates for days.
  • Set short timeouts on the remote call (a few seconds) and return a fallback rate or an error message when the call fails, rather than letting checkout hang.

The next stand-in shows a cached remote-rate client with a counter, so you can see how many remote calls really happen. It uses a fake carrier, so no network is involved.

PHP A cache in front of a slow carrier

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.

Six requests cost only three remote calls, because the key contains both destination and weight. A key with only the country would have returned a wrong price for the heavier parcel, which is the classic cache bug.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should getQuote() return when the delivery address is outside the extension's geo zone?

    An empty array means "not available here". A cost of 0 would wrongly offer free delivery, and exceptions would break checkout.
  2. 2. Which part of the quote array decides which choice is stored when the customer picks it?

    The code (for example zoneweight.zoneweight) is saved in the session and used later to find the matching quote, so it must stay stable.
  3. 3. Why does the quote contain a net cost and a tax_class_id instead of a gross price?

    Tax depends on the tax class and the address and is added in the totals step. The text key is only for display.
  4. 4. What is the main risk of a cache key that contains only the destination country for remote rates?

    The key must include everything that changes the price, such as weight, parcel count and currency.

Summary

  • Checkout calls getQuote() on every enabled shipping extension; an empty array means the method is not offered.
  • The result has two levels: the method (code, name, sort_order, error) and its quote choices (code, name, cost, tax_class_id, text).
  • Geo zones restrict where a method applies; cast every address value you put into SQL.
  • Weight tiers, price tiers and free-over thresholds are small pure rules: keep them out of the controller and use integer cents.
  • Cache remote rates with a key that holds everything affecting the price, and set short timeouts with a safe fallback.

Next: Order Total Extensions