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 Shipping Module: getQuote and Cost Calculation in 3.0 and 4.1

How to write an OpenCart 3.0 and 4.1 shipping module: the getQuote method, quote array format, multiple shipping options, tax, geo zones, and pitfalls with session-cached costs.

8 min read OC 3.0 OC 4.1

The heart of any OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → shipping module is the method in the getQuote($address) model. The core calls it for every enabled shipping methodAn extension that calculates the cost: "Extensions → Extensions," type "Shipping." More in the glossary → once the customer has entered an address, and displays everything the method returns: the method name and one or more options with their costs. The selected option, together with its price, is stored in the session. From there, the shipping totals module adds it to the order total, and checkout/confirm saves the name and code to the order.

Let's look at the getQuote() format in OpenCart 3.0 (3.0.4.1 and 3.0.5.1) and 4.1 (4.1.0.4), using the core weight module as an example. Then we'll write our own method with several options and see where the cost can differ from the actual charge. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling work differently.

Where does the shipping module live, and how does the core call it?

ItemOpenCart 3.0OpenCart 4.1
Catalog modelcatalog/model/extension/shipping/{code}.php, class ModelExtensionShipping{Code}extension/{ext}/catalog/model/shipping/{code}.php, class Opencart\Catalog\Model\Extension\{Ext}\Shipping\{Code}
SignaturegetQuote($address)getQuote(array $address): array
Who calls it at checkoutcheckout/shipping_method controllercheckout/shipping_method model, getMethods() method
Cart calculatorextension/total/shipping, method quoteextension/opencart/total/shipping, method quote (route extension/opencart/total/shipping.quote)
Core modulesflat, free, item, pickup, weight, and integrations with foreign carriersflat, free, item, pickup, weight

The core goes through all installed extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → of the shipping type, takes those that have shipping_{code}_status, calls getQuote() with the shipping address from the session (session->data['shipping_address']), and sorts the non-empty results by their sort_order. The result is stored in session->data['shipping_methods']. The module settings are in the setting table with the shipping_{code}_ prefix. For how to build the admin settings form, see the article on the module settings form.

Extensions → Extensions → type “Shipping”: status and sort order of shipping methods
Extensions → Extensions → type “Shipping”: status and sort order of shipping methods · OpenCart 4.1.0.4

What should getQuote return?

An empty array means the method is unavailable for this address or cart. Otherwise, it returns a method array with a nested array of options in quote. The structure is the same in both versions, but the name field differs.

KeyOpenCart 3.0OpenCart 4.1Meaning
Method: nametitlenamegroup heading at checkout
codesamemodule code, e.g. weight
quotesamearray of options, key is the subcode
sort_order, errorsamesort order and error text (or false)
Option: nametitlenamegoes to the order as the shipping name
Option: codesame{code}.{підкод}
Option: cost, tax_class_id, textsameprice without tax, tax class, formatted price

The option code and the array key in quote must match. When the selection is saved, the core splits the POST value at the dot and looks up shipping_methods[код]['quote'][підкод]. This leads to two rules: the subcode cannot contain a dot, and the array key must equal the part after the dot. In the weight module, this is 'weight_' . $geo_zone_id as the key and 'weight.weight_' . $geo_zone_id as the code.

A module moved from 3.0 to 4.1 without replacing title with name will show empty names at checkoutThe order placement page. The fewer fields, the higher the conversion. More in the glossary → and save an empty shipping name to the order. This is the most common migration mistake.

How does the weight module calculate the cost?

The core weight module clearly shows the typical logic, which is the same in both branches:

  1. For each geo zone with shipping_weight_{geo_zone_id}_status enabled, it checks whether the address falls within it (country and region, or “all regions”). In 3.0, this is a direct query to zone_to_geo_zone; in 4.1, it is model_localisation_geo_zone->getGeoZone().
  2. The cart weight is taken from $this->cart->getWeight(). It is already converted to the store's weight unit (config_weight_class_id) and includes only products flagged as “requires shipping”.
  3. The rate table in the settings has the form вага:ціна,вага:ціна. The first row where the weight is not less than the cart weight is used.
  4. A separate option is added for each matching geo zone, so one address can get several prices if the geo zones overlap.

The module builds the text field itself: tax->calculate($cost, $tax_class_id, config_tax) plus currency->format() in the session currency. The cost field is always in the store's base currency and without tax. The shipping totals module adds exactly this amount to the total, while tax under tax_class_id is added to the tax array. For how the totals are calculated afterward, see the article on order totals.

How to write your own getQuote with several options

A typical case in Ukraine is a carrier offering delivery to a branch, to a parcel locker, and to the address, with different rates and free shipping above a certain amount.

Example: getQuote with three options · OpenCart 4.1

namespace Opencart\Catalog\Model\Extension\Myship\Shipping;
class Myship extends \Opencart\System\Engine\Model {
	public function getQuote(array $address): array {
		$this->load->language('extension/myship/shipping/myship');

		// Лише Україна; country_id беріть з налаштувань модуля, а не хардкодьте
		if ((int)($address['country_id'] ?? 0) != (int)$this->config->get('shipping_myship_country_id')) {
			return [];
		}

		$tax_class_id = (int)$this->config->get('shipping_myship_tax_class_id');
		$free_from    = (float)$this->config->get('shipping_myship_free_total');
		$sub_total    = $this->cart->getSubTotal();
		$weight       = $this->cart->getWeight();

		$tariffs = [
			'warehouse' => (float)$this->config->get('shipping_myship_warehouse_cost'),
			'locker'    => (float)$this->config->get('shipping_myship_locker_cost'),
			'courier'   => (float)$this->config->get('shipping_myship_courier_cost')
		];

		$max_locker_weight = (float)$this->config->get('shipping_myship_locker_max_weight');

		$quote_data = [];

		foreach ($tariffs as $key => $cost) {
			if ($key == 'locker' && $max_locker_weight > 0 && $weight > $max_locker_weight) {
				continue;
			}

			if ($free_from > 0 && $sub_total >= $free_from && $key != 'courier') {
				$cost = 0;
			}

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

		if (!$quote_data) {
			return [];
		}

		return [
			'code'       => 'myship',
			'name'       => $this->language->get('heading_title'),
			'quote'      => $quote_data,
			'sort_order' => (int)$this->config->get('shipping_myship_sort_order'),
			'error'      => false
		];
	}
}

For 3.0, change the class to ModelExtensionShippingMyship in catalog/model/extension/shipping/myship.php, the language path to extension/shipping/myship, and the name keys to title, both at the method level and at the option level.

A few tips on calculation:

  • cart->getSubTotal() is the sum of the products without tax and without coupon discounts. If the free-shipping threshold should account for a coupon, this value is not enough. Either write honestly “from the product subtotal” or calculate the totals separately.
  • Don't show an option the customer cannot choose. If the rate depends on a city or branch that isn't in the address yet, return an option with error or an explanatory text, not one with a zero price.
  • The cost value is a number in the base currency. If the carrier's API returns the price in hryvnias and the store's base currency is different, convert it using currency->convert().

Why can the shipping cost become outdated?

The selected option is stored in session->data['shipping_method'] together with its price, and the shipping totals module then takes cost from there without calling getQuote() again. The core resets the selected method in these cases:

  • when a product is added, its quantity is changed, or an item is removed from the cart (checkout/cart, methods add, edit, and remove in both branches);
  • when a new shipping address is saved (checkout/shipping_address in both branches): the core removes from the session both the selected method and the list of shipping methods;
  • after a successful checkout in checkout/success.

So after any change to the cart or shipping address, the customer has to choose the shipping method again. However, between selecting the method and confirming the order, the price in the session is not updated. If the rate in the module settings or the carrier API response changes in the meantime, the order will get the price calculated at the moment of selection.

How does shipping data get into the order?

checkout/confirm takes session->data['shipping_method'] and the shipping address. OpenCart 3.0 writes the option name (title) to the shipping_method column of the order and the code to shipping_code. OpenCart 4.1 writes the entire option array as JSON to shipping_method, so it contains name, code, and cost. For a step-by-step explanation, see the article checkout in code.

A branch number, parcel locker, or waybill number (TTN) does not fit into the standard address. They are stored either in additional address fields (Custom FieldsYour own fields in registration or address, for example a tax ID number or a post office branch. More in the glossary →) or in the module's own table with the order_id key, which is filled by an event after the order is created. The approach to such tables is described in the article custom module tables. For an overview of ready-made integrations with Ukrainian carriers, see the blog: comparison of Nova Poshta, Ukrposhta, and Rozetka delivery modules. If you don't plan to write an integration from scratch, you could use, for example, “Nova Poshta API”.

Summary

  • A shipping module is primarily getQuote($address): an empty array or a method with options in quote.
  • In 3.0 the names are title, in 4.1 they are name; the option code {code}.{підкод} must match the key in quote.
  • cost is in the base currency and without tax; tax is set by tax_class_id, and the text module formats the price itself.
  • The cost of the selected option is stored in the session; the core resets the selection when the cart or shipping address changes, and the customer chooses the method again.
  • Cache API calls and handle their unavailability without breaking checkout.

Other articles in this section are on the page Cart, checkout, and orders in code.

FAQ

How do I make shipping free only for certain products?
In getQuote, loop through cart->getProducts() and check products by id, category, or attribute. The standard free shipping module relies only on the cart subtotal, so rules based on products require custom logic.
Why doesn't the shipping method appear at checkout?
Check the module status, the address geo zone, whether the cart contains products eligible for that shipping method, and that getQuote doesn't return an empty array due to an API error. It's helpful to temporarily log the address and result to the error log.
Can I change the shipping cost after the order has been placed?
Yes, by editing the order in the admin: it recalculates the cart and totals using the same modules. Don't change the shipping row in order_total directly, because then order.total won't match the totals.
How do I show the delivery time next to the price?
Add the time to the option name or to the text along with the price. The standard quote format has no separate field for delivery time, and the checkout template displays the name and text.
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.