About the author
Leonardo Losoviz is a freelance developer and writer, constantly striving to integrate innovative paradigms (serverless PHP, server components, GraphQL) … More about Leonardo ↬
Products and services are increasingly being acquired and purchased online. Since we live in a global town, many of our visitors are likely to be in a country other than our own and use a currency other than our own.
If we want to provide an excellent user experience for them, to increase the chances of them buying our product, and returning to the site, we can do something very simple: show the price of the store items in their own currency. To achieve this, we can convert the price of the item from a base currency (e.g. EUR) into the visitor’s currency (e.g. CNY) using the exchange rate between the two currencies at that particular time.
Exchange rates change constantly, on an hourly basis (and even faster). This means that we cannot store a predefined list of exchange rates in our application; it must be collected in real time. However, this is not a problem these days. Thanks to APIs that provide currency exchange data, we can easily add a currency converter to our online stores.
In this article we will give an introduction ExchangeRatesApi.io, a popular API solution that provides data for current and historical exchange rates for 168 currencies.
What we want to achieve
Simply put: we want to do what Amazon does: Give the option to the user in our online store to display the prices in a currency of their choice.
If you visit a product page in amazon.co.ukthe price is offered in British pounds:
But we can also see the price in another currency if we want to. In the country / region settings there is the option to change the currency:
After clicking “Change”, a selected input is presented with several predefined currencies. Among me, I chose the Euro:
Finally, on the product page, the price is displayed in euros:
If we have access to exchange rate data via an API, we can implement the same features for our own online stores.
How do we do it
ExchangeRatesApi.io offers a REST API, which provides the latest forex data for 168 currencies. It is always up to date and compiles the data from a broad base of commercial sources and banks around the world.
After to log in to their service (clue: they have a free level), we will get an API access key:
We grab our API access key, and add it to the endpoint:
https://api.exchangeratesapi.io/v1/latest ?access_key=YOUR_API_KEY
Copy / paste the endpoint into your browser to visualize the answer:
As can be appreciated in the picture above, the data for all 168 currencies were tracked. To limit the results to just a few of them, we have indicate the currency codes via param symbols.
For example, to retrieve data for the USD, British Pound, Australian Dollar, Japanese Yen, and Chinese Yuan (compared to the Euro, which is the base currency by default), we run this endpoint:
https://api.exchangeratesapi.io/v1/latest ?access_key=YOUR_API_KEY &symbols=USD,GBP,AUD,JPY,CNY
The answer is the following:
{ "success": true, "timestamp": 1620904263, "base": "EUR", "date": "2021-05-13", "rates": { "USD": 1.207197, "GBP": 0.860689, "AUD": 1.568196, "JPY": 132.334216, "CNY": 7.793428 } }
What data can we get?
ExchangeRatesApi.io provides several REST endpoints to access different sets of data. Depending on the enrolled plan, endpoints may or may not be available (their prices page explain which functions are covered by each level).
The endpoints below must be attached https://api.exchangeratesapi.io/v1/ (e.g: latest word https://api.exchangeratesapi.io/v1/latest), and add the access_key param with your API access key.
Latest rates
The latest end point provide real-time exchange rate data for all available currencies or for a specific set.
Currency conversion
The convert end point enables you to convert an amount of any currency to any other of the supported 168 currencies.
Historical rates
This end point has the shape YYYY-MM-DD (as 2021-03-20), which corresponds to the date by which we want to upload historical exchange rate information.
Time series data
The timeseries end point gives the daily historical data for exchange rates between two specified dates, for a maximum time frame of 365 days.
Fluctuation data
The fluctuation end point gives the fluctuation data between specified dates, for a maximum time frame of 365 days.
Get information from the API
To implement the currency converter, we can use the convert end point (for which we must be subscribed at the basic level):
https://api.exchangeratesapi.io/v1/convert ?access_key=YOUR_API_KEY &from=GBP &to=JPY &amount=25
The answer we will get is as follows:
{ "success": true, "query": { "from": "GBP", "to": "JPY", "amount": 25 }, "info": { "timestamp": 1620904845, "rate": 154.245331 }, "historical": "", "date": "2021-05-14", "result": 3856.079212 }
Because the data is exposed via a REST API, we can easily retrieve it for any application based on any stack, whether running on the client or server side, without installing any additional library.
Client side
The following JavaScript code joins the API and prints the converted amount and exchange rate in the console:
// Set endpoint and your access key const access_key = 'YOUR_API_KEY'; const from = 'GPB'; const to = 'JPY'; const amount = 25; const url = `https://api.exchangeratesapi.io/v1/convert?access_key=${ access_key }&from=${ from }&to=${ to }&amount=${ amount }`; // Get the most recent exchange rates via the "latest" endpoint: fetch(url) .then(response => response.json()) .then(data => { // If our tier does not support the requested endpoint, we will get an error if (data.error) { console.log('Error:', data.error); return; } // We got the data console.log('Success:', data); console.log('Converted amount: ' + data.result); console.log('(Exchange rate: ' + data.info.rate + ')'); }) .catch((error) => { console.error('Error:', error); }); Server side
The following code shows how to connect to the REST API and print the converted result, within a PHP application.
The same procedure can be implemented for other languages:
- Define the endpoint URL, attach your API access key.
- Link to the endpoint, retrieve the answer in JSON format.
- Decode the JSON data in an object / array.
- Obtain the converted amount below the
resultproperty.
// Set endpoint and your access key $access_key = 'YOUR_API_KEY'; $from = 'GBP'; $to = 'JPY'; $amount = 25; // Initialize CURL: $ch = curl_init("https://api.exchangeratesapi.io/v1/convert?access_key=${access_key}&from=${from}&to=${to}&amount=${amount}"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Get the JSON data: $json = curl_exec($ch); curl_close($ch); // Decode JSON response: $conversionResult = json_decode($json, true); // Access the converted amount echo $conversionResult['result']; Closure
ExchangeRatesApi.io was born as a open source project, with the intention of giving current and historical exchange rates published by the European Central Bank, and written in Python.
If you want to incorporate currency conversion into your online store, follow Amazon, and provide your visitors with a compelling user experience, you can download and install the open source project.
And you can also make it a lot easier: if you want to make your currency converter work for any programming language in no time, you will always have access to up-to-date data containing a wide variety of commercial sources, and super-fast API with almost 100% uptime (99.9% in the last 12 months) ExchangeRatesApi.io.
from WordPress https://ift.tt/3p7m6le
via IFTTT

No comments: