Magento – Magento2: How to get tax rate and tax percent from product

magento2taxtax-class

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);

Best Answer

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
            ]
        )
    );