1

How can I get tax rate and tax percent from a product in magento2? In magento1 we use below code:

        $taxClassId = $item->getData("tax_class_id");
        $taxClasses = Mage::helper("core")->jsonDecode(Mage::helper("tax")->getAllRatesByProductClass());
        $taxRate = $taxClasses["value_" . $taxClassId];
        $taxAmount = (($item->getQty() * $itemPrice * $taxRate) / 100);
3

Here is not a API, but much more flexible approach for getting tax rate that I had to use once:

    // SETTING DEFAULT VALUES FOR CALCULATION EXAMPLE

    /** @var \Magento\Framework\App\Config\ScopeConfigInterface $config */
    $countryCode = $config->getValue(\Magento\Shipping\Model\Config::XML_PATH_ORIGIN_COUNTRY_ID);
    $customerTaxClassId = $config->getValue('tax/classes/default_customer_tax_class');

    /** @var \Magento\Catalog\Model\Product $product */
    $productTaxClassId = $product->getData('tax_class_id');

    // THE ACTUAL CALCULATION CALL

    /** @var \Magento\Tax\Model\Calculation $taxCalculation */
    $rate = $taxCalculation->getRate(
        new \Magento\Framework\DataObject(
            [
                'country_id' => $countryCode,
                'customer_class_id' => $customerTaxClassId,
                'product_class_id' => $productTaxClassId
            ]
        )
    );
1

I achieved getting tax rates by using \Magento\Tax\Api\TaxCalculationInterface:

    $rate = $this->taxCalculation->getCalculatedRate($productTaxClassId, $customerId, $storeId);
  • is it working for guest customer? In my case it's not working. getting tax rate 0. – Sameer Bhayani Aug 8 '18 at 13:49
  • If you go through the Implementation of \Magento\Tax\Api\TaxCalculationInterface (in my case Magento\Tax\Model\TaxCalculation) you can find a fallback for guests if $customerId is missing – Lukas Komarek Aug 22 '18 at 13:36
  • page cache doesn't allow customerId in blocks or templates – obscure Apr 14 at 16:55
  • @obscure you are right. But in this case customerId might be null. If it's null it is based on store address and default customer tax class current store. If you want to get the tax rate by current customer group u might try following: -Get TaxClassId by current group id (served by HTTP Context) - Call TaxCalculation::getRateRequest - Finally call Calculation::getRate – Lukas Komarek Apr 15 at 8:12
  • @LukasKomarek, how to apply custom tax price by product id? – jafar pinjar May 14 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.