How to exchange Magento 2 currency in a few steps?

Learn how to exchange Magento 2 currency with the following steps in this blog.

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
Build your Amazon-like multi-vendor marketplace website @ $249/- now!!!
           Get your free live demo now: Click here

Exchange the Magento 2 currency

Exchange currency from base to other

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

,$toCurrency);

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

Exchange currency from A 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;

}


Click here to start a Magento store today with 300+ features in it.

Related:

Magento currency exchange


Posted

in

, ,

by

Comments

Leave a Reply

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