ARTICLE

Magento 2 Custom Totals Collectors: Adding a Fee or Surcharge With sales.xml, Quote Totals, and Invoice and Credit Memo Totals

Magento 2 Custom Totals Collectors: Adding a Fee or Surcharge With sales.xml, Quote Totals, and Invoice and Credit Memo Totals

A Magento 2 custom fee is a totals collector: a class registered in sales.xml that adds an amount to the quote, with matching collectors for invoices and credit memos. The quote part is quick to write. The real work is preventing double counting, storing base and display amounts, taxing the fee, and refunding it correctly.

Most tutorials stop after the fee appears in the cart. That leaves a fee that is charged at checkout and then disappears from the invoice, cannot be refunded, ignores currency conversion, and is counted twice on some orders. This guide walks the whole path, from the quote to the credit memo, and covers what changes on a Hyva storefront.

What a totals collector is and where it runs

Magento does not calculate a cart total in one place. It runs an ordered list of collector classes, each responsible for one line: subtotal, discount, shipping, tax, grand total. Magento\Quote\Model\Quote\TotalsCollector loops over every address on the quote, runs each collector for that address, and sums the address results into the quote.

The same idea repeats two more times later in the order lifecycle. When an invoice is created, Invoice::collectTotals() runs a separate list of invoice collectors. When a credit memo is created, a third list runs. These three lists are independent. A fee registered only on the quote exists only on the quote.

So a complete fee module has three collectors, one per stage, plus storage and display. If you are still planning the module, it helps to be clear on how the documents relate first; our guide to invoices, shipments, and credit memos in Magento 2 covers partial invoicing and refunds in detail.

Registering collectors in sales.xml

All three lists are declared in etc/sales.xml, in different sections:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd">
    <section name="quote">
        <group name="totals">
            <item name="fee" instance="Vendor\Fee\Model\Quote\Total\Fee" sort_order="420"/>
        </group>
    </section>
    <section name="order_invoice">
        <group name="totals">
            <item name="fee" instance="Vendor\Fee\Model\Invoice\Total\Fee" sort_order="160"/>
        </group>
    </section>
    <section name="order_creditmemo">
        <group name="totals">
            <item name="fee" instance="Vendor\Fee\Model\Creditmemo\Total\Fee" sort_order="210"/>
        </group>
    </section>
</config>

The sort_order decides when your collector runs relative to core, and it changes the behavior of the fee. These are the core values in the 2.4-develop branch, read from the sales.xml files of the Quote, Tax, SalesRule, Weee, and Sales modules:

Collector quote order_invoice order_creditmemo
subtotal 100 50 50
tax_subtotal 200 n/a n/a
weee 225 600 100
discount 300 100 150
shipping 350 150 200
tax_shipping 375 n/a n/a
shipping_discount 400 n/a n/a
tax 450 200 250
weee_tax 460 n/a n/a
grand_total 550 350 400

Two rules follow from the quote column. A fee that should be taxed must run before tax at 450. A fee that should flow into the grand total automatically must run before grand_total at 550. A value such as 420 satisfies both and still lets the fee depend on subtotal, discount, and shipping.

Popular tutorials use 150, which runs before discount and shipping, so a percentage fee cannot see either. Adobe’s own price adjustments tutorial uses 1000, which runs after the grand total and therefore has to add itself to the grand total by hand.

Execution order is not display order. Where the row appears in the summary is controlled by the sales/totals_sort configuration, which Adobe documents as the Checkout Totals Sort Order setting. Core defaults are subtotal 10, discount 20, shipping 30, tax 40, and grand total 100. Add your own code there through config.xml.

Writing the quote collector

The quote collector extends Magento\Quote\Model\Quote\Address\Total\AbstractTotal and implements two methods. collect() calculates and sets the amount. fetch() returns the row for display.

public function collect(
    Quote $quote,
    ShippingAssignmentInterface $shippingAssignment,
    Total $total
) {
    parent::collect($quote, $shippingAssignment, $total);

    if (!count($shippingAssignment->getItems())) {
        return $this;
    }

    $baseFee = $this->calculator->getBaseFee($quote, $total);
    $fee = $this->priceCurrency->convert($baseFee, $quote->getStore());

    $total->setBaseTotalAmount($this->getCode(), $baseFee);
    $total->setTotalAmount($this->getCode(), $fee);

    return $this;
}

public function fetch(Quote $quote, Total $total)
{
    return [
        'code'  => $this->getCode(),
        'title' => __('Handling Fee'),
        'value' => $total->getData('fee_amount'),
    ];
}

Call setCode('fee') in the constructor. With that code, setTotalAmount() stores the value in the total’s amounts array and also sets the data key fee_amount. setBaseTotalAmount() sets base_fee_amount. The parent collect() resets both to zero on each run, which is why you always call it first.

Three details in this short method are where most fee modules go wrong.

The empty items guard

TotalsCollector runs every collector once per quote address. A standard order has a billing address and a shipping address, and only one of them carries the items. Without the count($shippingAssignment->getItems()) check, a flat fee is added for both addresses and the customer sees it doubled. Core’s own shipping collector uses the same guard. On a multishipping order the fee applies once per address that has items, so decide whether that is what the business wants.

Do not touch the grand total

The core Grand collector adds array_sum($total->getAllTotalAmounts()) to the grand total. If your collector runs before 550 and has called setTotalAmount(), the fee is already included. Several widely copied examples also call setGrandTotal(getGrandTotal() + $fee), which counts the fee a second time. Only add to the grand total yourself when your collector runs after 550.

Base and display currency

Every amount in Magento is stored twice: in the base currency and in the currency the customer sees. The common tutorials set both to the same number, which is wrong on any store view with a different display currency. Calculate the fee in base currency, then convert with PriceCurrencyInterface::convert() as the core shipping collector does.

Storing the fee and copying it to the order

After the collectors run, Magento calls $address->addData($total->getData()). The fee is saved on the address only if quote_address has fee_amount and base_fee_amount columns. Add them with declarative schema, and mirror the pattern core uses for shipping:

  • quote_address: fee_amount, base_fee_amount
  • sales_order: fee_amount, base_fee_amount, fee_invoiced, base_fee_invoiced, fee_refunded, base_fee_refunded
  • sales_invoice and sales_creditmemo: fee_amount, base_fee_amount

Having the columns is not enough, because nothing copies a custom column from the quote to the order. Magento\Quote\Model\Quote\Address\ToOrder::convert() copies fields listed in the sales_convert_quote_address fieldset and then dispatches the sales_convert_quote_to_order event with the order and the quote. Core fields are declared in fieldset.xml with a to_order aspect. For a custom field, an observer on that event that reads the fee from the address and sets it on the order is the dependable route. If integrations need the value through the API, expose it properly with extension attributes instead of relying on the raw column.

Invoice and credit memo collectors

This is the stage most guides skip, and it is where accounting problems start. Without these collectors, the order grand total includes the fee but the invoice grand total does not, so the order never shows as fully paid.

Invoice collectors extend Magento\Sales\Model\Order\Invoice\Total\AbstractTotal and receive the invoice. Unlike the quote, the invoice Grand collector does nothing, so every invoice collector must add its own amount:

public function collect(Invoice $invoice)
{
    $order = $invoice->getOrder();
    $fee = $order->getData('fee_amount') - $order->getData('fee_invoiced');
    $baseFee = $order->getData('base_fee_amount') - $order->getData('base_fee_invoiced');

    $invoice->setData('fee_amount', $fee);
    $invoice->setData('base_fee_amount', $baseFee);
    $invoice->setGrandTotal($invoice->getGrandTotal() + $fee);
    $invoice->setBaseGrandTotal($invoice->getBaseGrandTotal() + $baseFee);

    return $this;
}

Partial invoices need a decision. Core’s shipping collector checks the order’s previous invoices and charges shipping on the first one only. Subtracting fee_invoiced as above gives the same result: the whole fee lands on the first invoice and later invoices get zero.

Credit memos follow the same shape with Magento\Sales\Model\Order\Creditmemo\Total\AbstractTotal. The credit memo Grand collector only applies the adjustment refund and adjustment fee fields, so your collector adds the fee to the grand total itself. Core shipping limits a refund to the order’s shipping amount minus what was already refunded. Do the same with fee_amount - fee_refunded, or a second credit memo will refund the fee twice.

Finally, the fee_invoiced and fee_refunded counters on the order do not update themselves. Core maintains its own counters inside the invoice and credit memo models; yours need an observer or plugin that runs when an invoice is registered and when a credit memo is refunded. If you are unsure which mechanism fits, see our comparison of plugins, observers, and preferences.

Making the fee taxable

Setting a tax class on a fee does nothing by itself. The core tax collector only taxes what it is told about. In Magento\Tax\Model\Sales\Total\Quote\Tax, the method mapQuoteExtraTaxables() reads $address->getAssociatedTaxables(). To have a fee taxed, your quote collector appends an entry to that array before the tax collector runs, which is the first reason to stay below 450.

The entry is an array with the keys defined in CommonTaxCollector: type, code, unit_price, base_unit_price, quantity, tax_class_id, price_includes_tax, and associated_item_code. For an order-level fee the associated item code is the constant ASSOCIATION_ITEM_CODE_FOR_QUOTE. The price_includes_tax key is read with no fallback for quote-level taxables, so leave it out and you get an error.

The calculated tax is added to the quote’s tax total, and the breakdown is available through the total’s extra taxable details. If you need to store the fee’s tax separately, a second small collector that runs after tax can read those details. The core invoice and credit memo tax collectors handle item and shipping tax only, so your invoice and credit memo collectors must carry the fee’s tax as well. Stores using a third-party tax service should confirm with a test order how the connector treats extra taxables before the fee goes live.

Displaying the fee everywhere it should appear

The fetch() array becomes a total segment, but each surface renders totals differently. A fee has to be added to each one.

Surface How totals are rendered What you add
Luma checkout and cart Knockout components under sidebar > summary > totals in checkout_index_index.xml and checkout_cart_index.xml A JS component extending abstract-total that reads totals.getSegment('fee')
REST cart totals CartTotalRepository converts collector output to total_segments Nothing; the segment appears from fetch()
GraphQL cart prices CartPrices resolver returns a fixed set of fields A schema extension; the fee is inside grand_total but has no field
Customer order view and emails Magento\Sales\Block\Order\Totals calls initTotals() on child blocks A child block that calls addTotal() on the parent
Admin order view Magento\Sales\Block\Adminhtml\Order\Totals A child block in the adminhtml sales_order_view layout
PDF invoices Totals declared in etc/pdf.xml A <total> node with source_field set to the fee column

The GraphQL row matters for headless and app projects. The grand total is correct, but a storefront that builds its own summary from individual fields will show lines that do not add up until you extend the schema.

Showing the fee on Hyva Checkout

Hyva Checkout does not use the Knockout summary, so the Luma JS component is not needed there. The price summary is a block tree. Per the Hyva documentation on totals sort order, you add a child block to price-summary.total-segments in hyva_checkout_components.xml, with the alias equal to the total code:

<referenceBlock name="price-summary.total-segments">
    <block name="price-summary.total-segments.fee" as="fee"
           template="Vendor_Fee::checkout/total-segments/fee.phtml"/>
</referenceBlock>

The visible order comes from the same sales/totals_sort configuration as Luma. Layout before and after attributes do not change it.

Hyva Checkout also has a setting called Collect Totals During Segment Retrieval, added in version 1.1.23 and enabled by default, which recollects totals when segments are fetched. Hyva’s documentation warns that recollecting several times in one request can cause issues. A collector that is not idempotent, for example one that adds to a running value instead of setting it, will show that problem here first. If you are planning a checkout move, our Hyva development services team scopes custom totals as part of that work.

When not to write a collector

A custom collector is the right tool on Magento Open Source and on self-managed Adobe Commerce when the fee logic is yours. There are cases where another route fits better:

  • On Adobe Commerce with App Builder, the out-of-process totals collector module lets a webhook return fees with a code, label, and base amount, without code in the Commerce application. Adobe’s documentation for it does not describe tax handling, so check that before relying on it for a taxable fee.
  • If the fee belongs to a payment method, build it into that method’s module so the two are enabled together. Our guide to building a custom payment method in Magento 2 covers the structure.
  • If the “fee” is really a shipping cost, a carrier or table rate is simpler and already invoices and refunds correctly.

None of this transfers to other platforms. A fee on Shopify, Shopware, or BigCommerce is built with that platform’s own extension points, so multi-platform merchants should specify the business rule once and implement it separately on each.

A test plan before release

Run these cases on staging before a fee goes live:

  1. Single address order: fee appears once in cart, checkout, order, invoice, and email.
  2. Store view with a different display currency: base and display amounts differ and both are stored.
  3. Virtual-only cart, which has no shipping address items.
  4. Multishipping order, to confirm the per-address behavior is intended.
  5. Two partial invoices: fee is on the first only, and the order closes as fully paid.
  6. Two partial credit memos: fee is refunded once, and the refundable total reaches zero.
  7. Taxable fee with tax-inclusive and tax-exclusive price settings.
  8. Coupon applied and removed, to confirm the fee recalculates and does not accumulate.

Bemeir is a Brooklyn ecommerce agency focused on Magento development services and Hyva. You can read more about Bemeir or see the payment, tax, and shipping providers in our technology partner network.

FAQ

What sort_order should a custom fee use in sales.xml?

For the quote section, pick a value after shipping (350) and before tax (450) if the fee is taxable or depends on shipping, and always before grand_total (550) if you want it included automatically. A value such as 420 covers both. Invoice and credit memo sections have their own, different core values.

Why is my Magento 2 custom fee added twice?

There are two usual causes. The collector runs for both the billing and shipping address because it lacks the empty items guard, or it sets a total amount and also adds the fee to the grand total while running before the core grand total collector, which already sums all amounts.

Does a custom fee appear on invoices and credit memos automatically?

No. Quote, invoice, and credit memo totals are three separate collector lists in sales.xml. The invoice and credit memo grand total collectors do not sum custom amounts, so each of your collectors must add the fee to the document’s grand total and you must track invoiced and refunded amounts on the order.

How do I make a custom fee taxable in Magento 2?

Add the fee to the address’s associated taxables array in your quote collector, with a tax class ID and the price_includes_tax flag, and make sure the collector runs before the core tax collector at sort order 450. Then carry the fee’s tax through your invoice and credit memo collectors.

Do I need a JavaScript component for the fee on Hyva Checkout?

No. Hyva Checkout renders totals from a PHP block tree. You add a child block to price-summary.total-segments whose alias matches the total code, and set its position with the sales/totals_sort configuration.

Let us help you get started on a project with Magento 2 Custom Totals Collectors: Adding a Fee or Surcharge With sales.xml, Quote Totals, and Invoice and Credit Memo Totals and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.