How to Create a Currency Conversion System on Your Website

Exchange rates can present a real challenge to any website selling products or services internationally, but in this blog post we will show you how simple it can actually be.

First of all you/your client will need to sign up to an exchange rate service; in this example our client chose currencylayer.com with which I had no previous experience but turned out to be easy to use.

Getting the Exchange Rates

You will receive an [access key] which is required to return your results. Place that into the code below:

$page = @file_get_contents("http://apilayer.net/api/live?access_key=[access key]¤cies=EUR,USD,GBP,INR,AUD,CAD,SGD,ZAR,NZD,JPY,CHF,MXN,CNY,SEK,RUB,HKD,NOK,TRY,KRW,BRL&format=1");
$obj = json_decode($page);
foreach($obj->quotes as $currency=>$rate){
  if($currency && $rate){
    // Save results
  }
}

As you can see the code is straightforward; all you need to do is choose which currencies you need, retrieve the URL’s contents as a JSON object and save the results. The basic account package sets the source currency as USD so every result will be based on that. See this snippet of the results in our database:

You can see that the rates are all from the point of view of the USD, so the exchange rate from USD to USD is obviously 1, USD to GBP is 0.754080 and USD to EUR is 0.879385.

Simply run this script at often as you need (by the minute, hour or day depending on how critical your figures are) to keep your data up to date.

Converting Between Currencies

It may not seem obvious at first but having a single currency source not only keeps the data tidy but also allows you to convert between any two currencies within the data set. Let’s take a closer look at how we do that.

Converting to USD

As our base currency is USD this is simple: if we want to convert from GBP we take the USDGBP rate and divide our price by that to get the amount in USD. For Euros we take the USDEUR rate etc. etc. So £10 GBP in USD is:

10/0.754080 = $13.26

Converting to other currencies

This is more tricky; first we need to get the two exchange rates and divide them. Let’s say we want to convert the above figure ($13.26) back into GBP.

We get the USDUSD and USDGBP figures (from the table shown above) and divide:

1/0.754080 = 1.3261

Then we take the amount we want to convert and divide by the result:

13.26/1.3261 = £10

Converting EUR to GBP works the same way:

0.879385/0.754080 = 1.1661
10/1.1661 = 8.58

So €10 = £8.58. We can check this by converting it back:

0.754080/0.879385 = 0.8575
8.58/0.8575 = 10

So there you have it; a fully working currency conversion system for your website.

This code is free to use at your own discretion. It comes without warranty. Please feel free to feedback any edits.


We'd love to hear from you!

If you think Bronco has the skills to take your business forward then what are you waiting for?

Get in Touch Today!

Discussion

Add a Comment

Get in touch