Knowledge base

Adjust shipping costs in Shopware 6 using code

Sometimes you will want to change the standard Shopware way of calculating shipping costs. You can do this using different plugins. You might want to do this when multiple variable factors play a role in the calculation of the shipping costs. For example, when you use an external carrier. 

To adjust the shipping costs of an order that is made within a Shopware 6 e-commerce store, you will firstly need to check if your shop uses the decorator design pattern. This decorator design pattern is the file that is used for calculating the shipping costs. (/src/Core/Checkout/Cart/Delivery/DeliveryCalculator.php

You can implement changes to this file to adjust how your shipping costs are calculated. 

To create the decorator, you will need to create a path, leading to the DeliveryCalculater file. To do this, you’ll need to make a file called DeliveryCalculatorDecotor. In this file, you will add the total content of the original DeliveryCalculator

After adding the content, you will need to change the class name into: class DeliveryCalculatorDecorator extends DeliveryCalculator. After you’ve done this, you will need to add the following code into your services.xml

<service id="PluginNamespace\Core\Checkout\Cart\Delivery\DeliveryCalculatorDecorator"
decorates="Shopware\Core\Checkout\Cart\Delivery\DeliveryCalculator">
	<argument type="service" id="Shopware\Core\Checkout\Cart\Price\QuantityPriceCalculator"/>
	<argument type="service" id="Shopware\Core\Checkout\Cart\Tax\PercentageTaxRuleBuilder"/>
	<argument type="service" id="Shopware\Core\Checkout\Cart\Tax\TaxDetector"/>
	<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
</service>

With the above code, you will indicate that you want to decorate the original Shopware file with your own decorator. But, because it’s a new class, you will need to provide all the services. When you’ve implemented the above code, you are able to really adjust the final shipping costs. 

To adjust the shipping costs, you will need to find the calculateShippingCosts function, within the DeliveryCalculatorDecorator file. The reason why you can only find it in this place has to do with the integrity and availability of the file. When adjusting the shipping costs on other places within the DeliveryCalculator, the price of the shipping costs will only be placed within an object, where there are setters but no getters. This results in the fact that you won’t be able to adjust the original shipping costs. 

Are you experiencing any trouble with adjusting the shipping costs of your business on Shopware 6? Memo ICT is the official Shopware Business Partner and is ready to assist you with our team of experts.