Magento currency: How to exchange it in a few steps?

In core Magento, it has charges from base currency to other currencies. It is quite simple to exchange currency from the base. However, if you need to exchange currency from current currency to base or other currencies.  Core Magento doesn’t support this function. In this tutorial, we will do it by the following steps:

  1. Exchange currency from base to other currency
  2. Exchange currency from another currency to base currency
  3. Exchange currency from a currency to a currency
Magento development, Implementations, Customization - All at one place, click here!!!

Magento currency: How to exchange it?

Exchange currency from base to other currency

$priceConverted = $this->_storeManager->getStore()->getBaseCurrency()->convert($price

,$toCurrency);

With $this->_storeManager is Magento\Store\Model\StoreManagerInterface

Exchange currency from another currency to base currency

$rateToBase = $this->_currencyFactory->create()->load($fromCurrency)->getAnyRate($this->_storeManager->getStore()->getBaseCurrency()->getCode());

$priceConverted = $price * $rateToBase;

With $this->_currencyFactory is \Magento\Directory\Model\CurrencyFactory

Exchange currency from a currency to a currency

public function currencyConvert($amount, $fromCurrency = null, $toCurrency = null)

{


  if(!$fromCurrency){

      $fromCurrency = $this->_storeManager->getStore()->getBaseCurrency();


  }


  if(!$toCurrency){



      $toCurrency = $this->_storeManager->getStore()->getCurrentCurrency();


  }

  if (is_string($fromCurrency)) {

      $rateToBase = $this->_currencyFactory->create()->load($fromCurrency)->getAnyRate($this->_storeManager->getStore()->getBaseCurrency()->getCode());


  } elseif ($fromCurrency instanceof \Magento\Directory\Model\Currency) {


      $rateToBase = $fromCurrency->getAnyRate($this->_storeManager->getStore()->getBaseCurrency()->getCode());


  }


  $rateFromBase = $this->_storeManager->getStore()->getBaseCurrency()->getRate($toCurrency);


  if($rateToBase && $rateFromBase){

      $amount = $amount * $rateToBase * $rateFromBase;


  } else {



      throw new InputException(__('Please correct the target currency.'));


  }


  return $amount;

}


Related:

Magento currency exchange

Last Update: May 24, 2021  

March 21, 2018   1133   Nandini Ramachandran    Magento, Magento 2 Tutorial, Operations    
Total 1 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn