1

I have used checkout_cart_product_add_after event, to add the custom price in catalog product.

I used the code for to add custom price,

$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);

Above code is not working while multi-currency. On cart page, if I added the product custom price with $10 it is showing $10.

When I am changing currency from the switcher to INR, It was showing ₹10.

If I disabled event and add to cart same product, it's working properly in both currencies.

Does anyone have an idea about this issue?

4
  • Did you declared the value of $price in to the file only as a static value or it is a dynamic value coming from somewhere else? Commented Oct 31, 2018 at 7:18
  • No, we do some calculation and set price in the item. Commented Oct 31, 2018 at 9:22
  • Did you get any solution for this? Commented Dec 26, 2019 at 7:21
  • hi, do u got any solution for the above issue
    – S.Venky
    Commented Jul 13, 2020 at 12:19

3 Answers 3

0

I know I am answering this late, but may be it help someone in the future.

I recently ran into the same issue and below is the solution that I used to handle this scenario.

What I did is added an observer on sales_quote_collect_totals_before event, please find the below sample code.

in etc/frontend/events.xml add the below code

<event name="sales_quote_collect_totals_before">
    <observer name="sales_quote_collect_totals_before_observer" instance="Company\Module\Observer\CollectTotalsBefore" />
</event>

Create a new file CollectTotalsBefore.php inside Company\Module\Observer\ and add the below code in that file

<?php

namespace Company\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Model\Session;

/**
 * Class CollectTotalsBefore
 */
class CollectTotalsBefore implements ObserverInterface
{

    /**
     * @var Session
     */
    protected $_session;

    /**
     * ProductAddAfter constructor.
     * @param Session $session
     */
    public function __construct(
        Session $session
    )
    {
        $this->_session = $session;
    }

    /**
     * @param EventObserver $observer
     * @return $this|void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
           $quote = $observer->getEvent()->getQuote();
           $items = $quote->getAllVisibleItems();
           foreach($items as $item) {
               $item = ($item->getParentItem() ? $item->getParentItem() : $item);
              if($item->getCustomPrice()){
                   $this->convertPriceFromBaseCurrencyToCurrentCurrency($finalPrice);
                   $item->setCustomPrice($finalPrice);
                   $item->setOriginalCustomPrice($finalPrice);
                   $item->getProduct()->setIsSuperMode(true);
               }
            }
        return $this;
    }
    
    public function convertPriceFromBaseCurrencyToCurrentCurrency($price)
    {
        $curentCurrencyCode =  $this->storeManager->getStore()
            ->getCurrentCurrency()
            ->getCode();
        $baseCurrencyCode =  $this->storeManager->getStore()
            ->getBaseCurrency()
            ->getCode();

        if($baseCurrencyCode != $curentCurrencyCode){
            $rate = $this->currencyFactory->create()
                ->load($baseCurrencyCode)
                ->getAnyRate($curentCurrencyCode);

            $price = $price * $rate;
        }
        return $price;
    }
}

This is the solution I have implemented, this will check the cart before cart totals and in case if the currency is changed, it will convert the quote items price into the current currency and reset the custom price.

Do comment in case of any issues of clarification.

0

I faced the same issue while using the above code to add a custom price. I found the below GitHub link which helped me to solve it.

  1. https://github.com/magento/magento2/issues/27161

  2. https://github.com/magento/magento2/issues/33134

[Magento Version 2.4.x]

app/code/Msquare/ModuleName/etc/frontend

events.xml

<?xml version="1.0"?>
<!--
/**
 * @category Msquare
 * @package Msquare_CustomPriceFix
 * @author Mahesh Makwana <[email protected]>
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="custom_price_add" instance="Msquare\CustomPriceFix\Observer\CustomPrice" />
    </event>
</config>

app/code/Msquare/ModuleName/Observer

CustomPrice.php

<?php
/**
 * @category Msquare
 * @package Msquare_CustomPriceFix
 * @author Mahesh Makwana <[email protected]>
 */
namespace Msquare\CustomPriceFix\Observer;

use Msquare\CustomPriceFix\Helper\Data as DataHelper;
use Magento\Framework\Currency\Data\Currency as CurrencyData;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class CustomPrice implements ObserverInterface
{
    /**
     * @param DataHelper $dataHelper
     */
    public function __construct(
        protected DataHelper $dataHelper
    ) {}

    public function execute(Observer $observer)
    {
        $item = $observer->getEvent()->getData('quote_item');
        $item = ($item->getParentItem() ? $item->getParentItem() : $item);
        $price = 100; //set your price here

        $curentCurrency = $this->dataHelper->getCurrentCurrency();
        $baseCurrency = $this->dataHelper->getBaseCurrency();
        if ($curentCurrency != $baseCurrency) {
            $currencyObj = $this->dataHelper->getCurrencyFactory();
            $rate = $currencyObj->load($baseCurrency)->getAnyRate($curentCurrency);
            $price *= $rate;
            $price = (float) $currencyObj->format($price, ['display' => CurrencyData::NO_SYMBOL], false);
        }

        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }

}

app/code/Msquare/ModuleName/Helper

Data.php

<?php
/**
 * @category Msquare
 * @package Msquare_CustomPriceFix
 * @author Mahesh Makwana <[email protected]>
 */
namespace Msquare\CustomPriceFix\Helper;

use Magento\Checkout\Model\CartFactory;
use Magento\Directory\Model\CurrencyFactory;
use Magento\Store\Model\StoreManagerInterface;

class Data
{
    public function __construct(
        protected StoreManagerInterface $storeManager,
        protected CurrencyFactory $currencyFactory,
        protected CartFactory $cartFactory
    ) {}

    /**
     * Get base currency code
     *
     * @return string
     */
    public function getBaseCurrency()
    {
        return $this->storeManager->getStore()->getBaseCurrency()->getCurrencyCode();
    }

    /**
     * Get current currency code
     *
     * @return string
     */
    public function getCurrentCurrency()
    {
        return $this->storeManager->getStore()->getCurrentCurrency()->getCurrencyCode();
    }

    /**
     * Get currency factory
     *
     * @return CurrencyFactory
     */
    public function getCurrencyFactory()
    {
        return $this->currencyFactory->create();
    }

    /**
     * Get cart items
     *
     * @return CartFactory
     */
    public function getCartItems()
    {
        return $this->cartFactory->create()->getQuote()->getAllItems();
    }

}

app/code/Msquare/ModuleName/etc/frontend

di.xml

<?xml version="1.0"?>
<!--
/**
 * @category Msquare
 * @package Msquare_CustomPriceFix
 * @author Mahesh Makwana <[email protected]>
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Directory\Controller\Currency\SwitchAction">
        <plugin name="custom_price_fix"
                type="Msquare\CustomPriceFix\Plugin\Direcotry\Controller\Currency\SwitchAction"
                sortOrder="10"/>
    </type>
</config>

app/code/Msquare/ModuleName/Plugin/Direcotry/Controller/Currency

SwitchAction.php

<?php
/**
 * @category Msquare
 * @package Msquare_CustomPriceFix
 * @author Mahesh Makwana <[email protected]>
 */
namespace Msquare\CustomPriceFix\Plugin\Direcotry\Controller\Currency;

use Msquare\CustomPriceFix\Helper\Data as DataHelper;
use Magento\Directory\Controller\Currency\SwitchAction as SwitchActionParent;
use Magento\Framework\Currency\Data\Currency as CurrencyData;

class SwitchAction
{
    /**
     * @param DataHelper $dataHelper
     */
    public function __construct(
        protected DataHelper $dataHelper
    ) {}

    /**
     * Currency switcher before plugin
     *
     * @param SwitchActionParent $subject
     *
     * @return void
     */
    public function beforeExecute(SwitchActionParent $subject)
    {
        $items = $this->dataHelper->getCartItems();
        $currencyObj = $this->dataHelper->getCurrencyFactory();
        $baseCurrency = $this->dataHelper->getBaseCurrency();
        $newCurrency = (string) $subject->getRequest()->getParam('currency');
        if ($newCurrency != $baseCurrency) {
            /* Update Price for Other Currency */
            $rate = $currencyObj->load($baseCurrency)->getAnyRate($newCurrency);
            foreach ($items as $item) {
                $customPrice = $item->getBasePrice();
                $customPrice *= $rate;
                $customPrice = (float) $currencyObj->format($customPrice, ['display' => CurrencyData::NO_SYMBOL], false);
                $item->setCustomPrice($customPrice);
                $item->setOriginalCustomPrice($customPrice);
                $item->getProduct()->setIsSuperMode(true);
                $item->save();
            }

        } else {
            /* Update Price for Base Currency */
            foreach ($items as $item) {
                $item->setCustomPrice($item->getBasePrice());
                $item->setOriginalCustomPrice($item->getBasePrice());
                $item->getProduct()->setIsSuperMode(true);
                $item->save();
            }
        }
    }
}

Github Issue : https://github.com/magento/magento2/issues/33134#issuecomment-1724410098

1
0

This is an on-going issue which still exists in latest versions of Magento 2.4: https://github.com/magento/magento2/issues/33134

I fixed it on a couple Magentos 2.3.x applying these couple patches: https://github.com/araujophillips/magento2-issue-33134/tree/master

Important, I have only tested it on Magento 2.3.x However, since this part of the code didn't change too much on 2.4.x it should be compatible or really close to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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