You are here:

How to add Openexchangerates Currency Conversion Service to Magento?

Openexchangerates is an effective way for Magento user when the built in Webservicex currency service stopped working. It offers both a free and several levels of premium services. The free option allows for up to 1000 API requests per month. This amount is quite enough for the standard use case in Magento.

Now, let’s create a free account and get your App ID!

First, we will name it to define the module name space. We will call it Magento_Openexchangerates. And then create Helper, Model, and etc folder

It will have 2 system configuration options are accessible from System> Configuration> General> Currency, the App Id and the Connection timeout.

The name will show up in the service selection drop downs and the model will be our new currency exchange class that will handle the retrieval and processing of the currency rates from Openexchangerates API

There are some good examples of the various use cases and features; however, we just focus on the API call provided by the free access which retrieves all available rates in one hit by simply calling http://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID. We can get data back as JSON; therefore, parsing and processing in the next time are very easy.

To execute our rates retrieval, we have the Model/Currency/Import/Openexchangerates.php file with our class that extends Mage_Directory_Model_Currency_Import_Abstract:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

<?php

/**

 * @category    Magento

 * @package     Magento_Openexchangerates

 * @author      Robert Popovic

 * @copyright   Copyright (c) 2014 Magento

 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)

 */

 

/**

 * Currency rate import model (From www.webservicex.net)

 *

 * @category   Magento

 * @package    Magento_Openexchangerates

 * @author     Robert Popovic for Magento

 */

class Magebase_Openexchangerates_Model_Currency_Import_Openexchangerates extends Mage_Directory_Model_Currency_Import_Abstract

{

    /**

     * Openexchangerates API URL

     * @var string

     */

    protected $_url = ‘http://openexchangerates.org/api/latest.json?app_id={{APP_ID}}';

    protected $_messages = array();

 

     /**

     * HTTP client

     *

     * @var Varien_Http_Client

     */

    protected $_httpClient;

    /**

     * Fetched and cached rates array

     * @var array

     */

    protected $_rates;

 

    /**

     * Initialise our obkject with the full rates retrieved from Openexchangerates as the

     * free version only allows us to get the complete set of rates. But that’s ok, we are

     * caching it and then processing the individual rates

     *

     * @throws Exception

     */

    public function __construct()

    {

        $this->_httpClient = new Varien_Http_Client();

        $app_id = Mage::getStoreConfig(‘currency/mb_openexchangerates/app_id’);

        if (!$app_id) {

            $e = new Exception(Mage::helper(‘mb_openexchangerates’)->__(‘No Openexchangerates App Id set!’));

            Mage::logException($e);

            throw $e;

        }

        $url = str_replace(‘{{APP_ID}}’, $app_id, $this->_url);

 

        $response = $this->_httpClient

            ->setUri($url)

            ->setConfig(array(‘timeout’ => Mage::getStoreConfig(‘currency/mb_openexchangerates/timeout’)))

            ->request(‘GET’)

            ->getBody();

 

        // response is in json format

        if( !$response ) {

            $this->_messages[] = Mage::helper(‘mb_openexchangerates’)->__(‘Cannot retrieve rate from %s.’, $url);

        } else {

            // check response content – returns array

            $response = Zend_Json::decode($response);

            if (array_key_exists(‘error’, $response)) {

                $this->_messages[] = Mage::helper(‘mb_openexchangerates’)->__(‘API returned error %s: %s’, $response[‘status’], $response[‘description’]);

            } elseif (array_key_exists(‘base’, $response) && array_key_exists(‘rates’, $response)) {

                $this->_rates = $response[‘rates’];

 

            } else {

                Mage::log(‘Openexchangerates API request: %s’,$url);

                Mage::log(‘Openexchangerates API response: ‘.print_r($response,true));

                $this->_messages[] = Mage::helper(‘mb_openexchangerates’)->__(‘Unknown response from API, check system.log for details.’);

            }

        }

    }

 

    /**

     * Convert an individual rate

     * Note that the Openxchangerates free service gives all rates based on USD

     * so we do a cross-currency conversion via USD as the base.

     *

     * @param string $currencyFrom

     * @param string $currencyTo

     * @param int $retry

     * @return float

     */

    protected function _convert($currencyFrom, $currencyTo, $retry=0)

    {

        if (sizeof($this->_messages) > 0) {

            return null;

        }

        $rate = null;

 

        if (array_key_exists($currencyFrom, $this->_rates) && array_key_exists($currencyTo, $this->_rates)) {

            // convert via base currency, whatever it is.

            $rate = (float) ($this->_rates[$currencyTo] * (1/$this->_rates[$currencyFrom]));

        } else {

            $this->_messages[] = Mage::helper(‘mb_openexchangerates’)->__(‘Can\’t convert from ‘.$currencyFrom.’ to ‘.$currencyTo.’. Rate doesn\’t exist.’);

        }

 

        return $rate;

    }

    /**

     * Trim currency rate to 6 decimals

     *

     * @param float $number

     * @return float

     */

    protected function _numberFormat($number)

    {

        return number_format($number, 6);

    }

}

It will have two idiosyncrasies with this service in comparison to the operating of the old service. We will get all rates in one request if you don’t want to pay for the premium service. And there is another thing that the returned rates are all based on the exchange rate against the US dollar. So you have to handle this.

We need to retrieve the rates in the class constructor as the instantiated class when ‘Import Rates’ button clicked. Then cache this rates array from the JSON response in our_rates class property

Magento has all the configured currencies and calls the _convert($currencyFrom, $currencyTo, $retry=0) method for each individual currency. At this stage, you just need to look up the currency codes in the array keys. The only thing we need to do is cross-convert to currencies since the rates are based on USD, hence the formula.

We also have an empty helper:

1

2

3

4

5

6

7

8

9

10

11

12

<?php

/**

 * Helper class

 *

 * @category   Magento

 * @package    Magento_Openexchangerates

 * @author     Robert Popovic for Magento

 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)

 */

class Magento_Openexchangerates_Helper_Data extends Mage_Core_Helper_Abstract

{

}

And the last thing is the app/etc/modules/Magento_Openexchangerates.xml file:

1

2

3

4

5

6

7

8

9

10

11

12

<?xml version=”1.0″ encoding=”UTF-8″?>

<config>

    <modules>

        <Magento_Openexchangerates>

            <active>true</active>

            <codePool>local</codePool>

            <depends>

                <Mage_Directory />

            </depends>

        </Magento_Openexchangerates>

    </modules>

</config>

 

That’s all about adding Openexchangerates to Magento. Hope that you can do it smoothly.

Related articles
 

404

GET IT TOUTH

MageHit - No1 Magento Development Company

Contact Us

Back to Top