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:

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:

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:

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

Converting EUR to GBP works the same way:

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

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.

Add a comment