Foreign Exchange Rates API with Currency Conversion in PHP

Recently I was working on a project where we needed to collect payment from users all over the world. The client is using Razorpay for receiving online payments. In Razorpay you need to convert the foreign currency rate into INR(Indian Rupees) and then charge the payment. To perform this task, I wanted to get foreign exchange rates API which I found at Exchange rates API.

The service provides both free and premium plans. The free plan allows you to hit 250 requests per month. You can pick up the plan based on your requirements.

You have to register with the service and grab your API key. This API key is required while calling their APIs.

Let’s see now how to use Exchange rates API and get the amount of foreign currency.

How to Use Exchange Rates API

Exchange Rates API provides API endpoints. Once we hit the endpoints along with parameters they return an appropriate response.

In order to give API calls and handling responses, we can choose either Guzzle(PHP HTTP client) or cURL. Both provide an easy and reliable way to interact with the APIs.

Let’s start with the Guzzle first. Install the Guzzle using the following command:

composer require guzzlehttp/guzzle

Upon installation, you can give an API call and receive the response using the code below.

<?php
require_once 'vendor/autoload.php';
 
use GuzzleHttp\Client;

try {
    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'http://api.exchangeratesapi.io/v1/',
    ]);
     
    // get all rates
    $response = $client->request('GET', 'latest', [
        'query' => [
            'access_key' => 'API_ACCESS_KEY',
            'symbols' => 'USD',
        ]
    ]);
     
    if($response->getStatusCode() == 200) {
        $body = $response->getBody();
        $arr_body = json_decode($body);
        print_r($arr_body);
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

Replace the placeholder API_ACCESS_KEY with your actual key. Run this script and you should get the latest exchange rate of USD. Notice base currency set to ‘EUR’. The user can set other currency symbols to the ‘base’ key.

Let’s say you want the INR price of USD dollars.

$response = $client->request('GET', 'latest', [
    'query' => [
        'access_key' => 'API_ACCESS_KEY',
        'base' => 'USD',
        'symbols' => 'INR',
    ]
]);

Exchange rates API also gives you historical data. In that case, you need to pass a date value for ‘start_date’ and ‘end_date’ keys.

$response = $client->request('GET', 'timeseries', [
    'query' => [
        'access_key' => 'API_ACCESS_KEY',
        'symbols' => 'USD',
        'start_date' => '2021-01-01',
        'end_date' => '2021-03-30'
    ]
]);

Interact with the API using cURL

I preferred to use a Guzzle for interacting with the API. But if someone wants to use cURL then they can use the code below. Make sure you have enabled the cURL extension on your server.

<?php
$url = "http://api.exchangeratesapi.io/v1/latest?access_key=API_ACCESS_KEY&symbols=USD";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
$arr_result = json_decode($response);
print_r($arr_result);

It’s all about getting foreign exchange rates in PHP. I hope you understand it and can use it in your development work. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

6 thoughts on “Foreign Exchange Rates API with Currency Conversion in PHP

  1. Your Article is very Good. Due to your article we get more information and knowledge. Your article is very usefull. ue to your article we get solutions how to perform pages. So keep it up. God Bless you.

Leave a Reply

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