This is a PHP client for the ForexAPI. It provides an easy-to-use interface for interacting with the API's endpoints.
The ForexAPI offers a free plan and provides foreign exchange rates and currency conversion.
The API documentation can be found at https://forexapi.eu/en/docs.
- PHP 7.4 or higher
- json extension
- Composer
Use Composer to install the ForexAPI PHP Client:
composer require forexapi/client
This package does not come with a Http Client. You can use any PSR-18 compatible client.
If you have multiple Http Clients installed, you can specify which one to use.
composer require guzzlehttp/guzzle forexapi/client
Create an instance of the Client
class directly with your API key:
use ForexAPI\Client\Client;
$client = new Client('your-api-key');
Create new instance using the ForexAPI\Client\ForexAPIClientBuilder
class:
use \ForexAPI\Client\ForexAPIClientBuilder;
$builder = (new ForexAPIClientBuilder())
->withApiKey('your-api-key')
->withBaseUri('https://forexapi.eu/api/')
->withHttpAdapter($yourCustomHttpAdapter)
->build()
;
Using your own PSR-18 client and PSR-17 request factory is optional. If you don't provide them, the client will try to discover them automatically.
use \ForexAPI\Client\ForexAPIClientBuilder;
$builder = (new ForexAPIClientBuilder())
->withApiKey('your-api-key')
->withPsr18Client($yourCustomPsr18Client)
->withPsr17RequestFactory($yourCustomPsr17RequestFactory)
->build()
;
To get a live quote for a specific currency pair:
$quote = $client->getLiveQuote('USD', 'PLN');
echo $quote->getBase(); // USD
echo $quote->getCounter(); // PLN
echo $quote->getBid(); // Bid price
echo $quote->getAsk(); // Ask price
echo $quote->getMid(); // Mid price
echo $quote->getTimestamp(); // Timestamp
To get the exchange rate between two currencies:
$exchangeRate = $client->getExchangeRate('USD', 'PLN');
echo $exchangeRate->getFrom(); // USD
echo $exchangeRate->getTo(); // PLN
echo $exchangeRate->getRate(); // Exchange rate
echo $exchangeRate->getTimestamp(); // Timestamp
If you would like to get multiple exchange rates at once, you can use the getExchangeRates
method.
It accepts an array of counter currencies as an argument:
$exchangeRate = $client->getExchangeRates('USD', ['PLN', 'EUR', 'GBP']);
To convert an amount from one currency to another:
$conversion = $client->convert('USD', 'PLN', 100.0);
echo $conversion->getFrom(); // USD
echo $conversion->getTo(); // PLN
echo $conversion->getAmount(); // 100.0
echo $conversion->getResult(); // Converted amount in PLN
echo $conversion->getTimestamp(); // Timestamp
If you would like to convert to multiple currencies at once, you can use the convertMany
method:
$conversions = $client->convertMany('USD', ['PLN', 'EUR', 'GBP'], 100.0);
This library includes a suite of unit tests. Run them using PHPUnit:
./vendor/bin/phpunit
This project is licensed under the MIT License. See the LICENSE file for details.