Magento 2 插件中获取商品最终价格的正确方法

本文旨在解决在 Magento 2 插件中获取商品最终价格(包括目录价格规则折扣)时遇到的问题。通过示例代码,详细讲解了如何使用 `getPriceInfo()` 方法获取简单商品和可配置商品的常规价格和最终价格,并强调了在获取可配置商品最终价格时需要注意的细节。 确保在插件中正确获取并使用商品最终价格,避免价格计算错误。

在 Magento 2 开发插件时,正确获取商品最终价格至关重要,尤其是在存在目录价格规则等折扣的情况下。 直接使用 vendor/magento/module-catalog/Model/Product/Type/Price::getFinalPrice() 方法可能无法如预期计算出包含折扣的价格。本文将介绍一种更可靠的方法,通过 getPriceInfo() 获取商品的常规价格和最终价格,并针对不同类型的商品(简单商品和可配置商品)提供相应的代码示例。

获取简单商品的价格

对于简单商品,可以使用以下代码获取常规价格和最终价格:

getPriceInfo()->getPrice('regular_price')->getValue();
        $specialPrice = $product->getPriceInfo()->getPrice('special_price')->getValue();

        return [
            'regular_price' => $regularPrice,
            'final_price' => $specialPrice, // 这里实际上已经包含了目录价格规则的折扣
        ];
    }
}

代码解释:

  • $product->getPriceInfo()->getPrice('regular_price')->getValue(): 获取商品的常规价格。
  • $product->getPriceInfo()->getPrice('special_price')->getValue(): 获取商品的最终价格,它已经考虑了目录价格规则等折扣。

获取可配置商品的价格

对于可配置商品,获取价格的方式略有不同,需要区分常规价格和最终价格:

getTypeId() == 'configurable') {
            $basePrice = $product->getPriceInfo()->getPrice('regular_price');

            $regularPrice = $basePrice->getMinRegularAmount()->getValue();
            $finalPrice = $product->getFinalPrice();

            return [
                'regular_price' => $regularPrice,
                'final_price' => $finalPrice,
            ];
        }

        return [
            'regular_price' => 0,
            'final_price' => 0,
        ];
    }
}

代码解释:

  • $product->getTypeId() == 'configurable': 判断商品类型是否为可配置商品。
  • $basePrice = $product->getPriceInfo()->getPrice('regular_price'): 获取常规价格信息对象。
  • $regularPrice = $basePrice->getMinRegularAmount()->getValue(): 获取可配置商品中最低的常规价格。
  • $finalPrice = $product->getFinalPrice(): 获取可配置商品的最终价格,这个价格已经包含了目录价格规则的折扣。

注意: 获取可配置商品最终价格时,直接使用 $product->getFinalPrice() 方法是更简洁有效的方式。

使用示例

以下是如何在你的插件中使用上述代码的示例:

priceHelper = $priceHelper;
    }

    public function afterGetName(Product $product, $result)
    {
        $productType = $product->getTypeId();
        if ($productType == 'simple') {
            $prices = $this->priceHelper->getSimpleProductPrices($product);
        } elseif ($productType == 'configurable') {
            $prices = $this->priceHelper->getConfigurableProductPrices($product);
        } else {
            $prices = ['regular_price' => 0, 'final_price' => 0];
        }

        $regularPrice = $prices['regular_price'];
        $finalPrice = $prices['final_price'];

        // 使用价格进行后续操作
        return $result . " (Regular Price: " . $regularPrice . ", Final Price: " . $finalPrice . ")";
    }
}

总结

通过使用 getPriceInfo() 方法,可以更准确地获取 Magento 2 中商品(包括简单商品和可配置商品)的常规价格和最终价格,尤其是在存在目录价格规则等折扣的情况下。 请务必根据商品类型选择正确的方法,并确保在你的插件中正确使用这些价格信息。 此外,定期清理缓存和重新索引数据也是确保价格信息准确性的重要步骤。