In some special cases, you might want to give a free tax for customers, right? I will show you how to create a free tax coupon in Magento 2 programmatically.
If your Magento store doesn’t collect tax, then you don’t have any problem; however, if the store is collecting taxes, you will find a trouble where Magento store doesn’t provide such a way to free tax for a tax-calculated order.
The common solution for this is to use a special coupon to allow free tax for the order.
What we’ll do is to create an observer for the event sales_quote_address_collect_totals_before
and apply free tax class for the order items.
This is how to implement it.
The first step is to define an observer in events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_quote_address_collect_totals_before">
<observer name="vendor_module_free_tax_coupon"
instance="Vendor\Module\Observer\FreeTaxCoupon" />
</event>
</config>
Then we will need to implement the Vendor\Module\Observer\FreeTaxCoupon
observer.
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Quote\Model\Quote;
class RemoveOrderTaxFromProduct implements ObserverInterface
{
public function execute(Observer $observer)
{
/** @var Quote $quote */
$quote = $observer->getEvent()->getQuote();
$couponCode = $quote->getCouponCode();
$taxFreeCouponCode = 'FREETAXCOUPON';
if ($couponCode === $taxFreeCouponCode) {
/** @var \Magento\Quote\Model\Quote\Item $item */
foreach ($quote->getAllItems() as $item) {
$product = $item->getProduct();
$product->setTaxClassId(0);
}
}
}
}
You can replace the FREETAXCOUPON
by the coupon you want.
Also, you can extract the coupon out as a config or maps with a coupon (Marketing section) to make it convenient for store admin to manage.
That’s how you create a free tax coupon in Magento 2 programmatically.
Have fun!