How to exchange currency in Magento 2

In core Magento, it has charges from base currency to other currencies. It is quite simple to exchange currency from 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

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 :

Last Update: April 7, 2018  

March 21, 2018   121   Nandini R    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
Google+
http://www.webnexs.com/blog/kb/how-exchange-currency-magento-2
Twitter
LinkedIn