Magento – How to change Tax percentage during checkout

checkoutmagento2quotetax

We would like to change the Tax percentage on my current order during checkout.

Current setup:
Magento 2.1.4
Magestore OneStepCheckout

Current challenge:
We currently ask our customers some questions during checkout, and depending on theyre answers, they need to be given a different tax percentage (or different tax class), instead of standard 21%, they get 6%. On the total order.

Already tried solutions:
Solution 1: I created an observer, sales_quote_collect_totals_before and when fired I change the class of the products. The solution works when adding products to the cart, but when dispatching the event while in checkout, the product tax and total amount is not changed.
Solution 2: How to re-collect quote totals in Magento 2?
But I am not getting it to work.

I hope that, someone has a solution, or is able to point me in the right direction.

Best Answer

I looked into the taxes code and it seems that the tax calculation is done in vendor/magento/module-tax/Model/Calculation/AbstractAggregateCalculator.php calculateWithTaxNotInPrice function. The code first gets the tax rate request which contains all the information that is needed to calculate the tax rate (percent) -

$taxRateRequest = $this->getAddressRateRequest()->setProductClassId(
    $this->taxClassManagement->getTaxClassId($item->getTaxClassKey())
);

Afterwards the code does

$rate = $this->calculationTool->getRate($taxRateRequest);

which calculates the rate according to the provided request.

Therefore, the way I would implement the feature that you've described is in the following two steps:

  1. Inject the additional customer data that you need to the request by extending getAddressRateRequest() (probably by plugin)

  2. Override/extend getRate to change the rate according the $taxRateRequest (which should include your extra customer data, due to step 1)

Related Topic