I know this might be a simple question to ask, but I'm wondering what's the proper way to get the price of a product?
I know most of you might say "use Magento\Catalog\Api\Data\ProductInterface::getPrice()", but that returns the price like it's set in the admin. Just the value as it is in the database. But note that to answer the question "what's the price of the product?" there are several factors you need to consider:
- What's the store view?
- What's the current currency?
- What's the tax?
- Are the catalog prices including or excluding tax? (configuration settings)
- Should I display / calculate taxes on the frontend? (configuration settings)
- Is there a special price? (and what's the from/to date?)
- Are there any special catalog price rules?
- Are there tier prices?
- If the customer is logged in, are there different prices?
- Are there other modules that manipulate the price in some way?
As you can see, a simple getPrice()
won't do. So what I'm wondering, is there any Service Contract that I'm not aware of that takes all of the above in consideration and returns me the proper price?
Best Answer
You can use
getFinalPrice()
coming from the below product model.It also allows a
$qty
variable in case of tier prices.i.e.:
Reference:
NOTE:
It is not defined in
ProductInterface
, so it will not be part of service contract. But it will work anyway.UPDATE::
The best Magento2 way to preserve service contracts model is to create a new custom
ProductInteface
in a custom module and referencegetFinalPrice
as interface method.You will have to use the new
ProductInterface
in your project. This is the way to create a sort of service contract inside your project.If getFinalPrice will change, you will change only your custom model.