Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
255 changes: 180 additions & 75 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,101 +1,206 @@
# <img src="https://s3.amazonaws.com/swap.assets/swap_logo.png" height="30px" width="30px"/> Swap
# Swap

[![Tests](https://github.com/florianv/swap/actions/workflows/tests.yml/badge.svg)](https://github.com/florianv/swap/actions/workflows/tests.yml)
[![Psalm](https://github.com/florianv/swap/actions/workflows/psalm.yml/badge.svg)](https://github.com/florianv/swap/actions/workflows/psalm.yml)
[![Total Downloads](https://img.shields.io/packagist/dt/florianv/swap.svg?style=flat-square)](https://packagist.org/packages/florianv/swap)
[![Version](http://img.shields.io/packagist/v/florianv/swap.svg?style=flat-square)](https://packagist.org/packages/florianv/swap)

Swap allows you to retrieve currency exchange rates from various services such as **[Fixer](https://fixer.io/)**, **[Currency Data](https://currencylayer.com)** or **[Exchange Rates Data](https://exchangeratesapi.io/)** and optionally cache the results.
It is integrated to other libraries like [moneyphp/money](https://github.com/moneyphp/money) and provides
a [Symfony Bundle](https://github.com/florianv/FlorianvSwapBundle) and a [Laravel Package](https://github.com/florianv/laravel-swap).
> _The easy-to-use PHP currency conversion library. Retrieve exchange rates from 30 providers, with caching and fallback. Maintained since 2014._

## QuickStart
Swap is a mature PHP **currency conversion library** for retrieving and working with exchange rates. It provides a single, easy-to-use API on top of multiple exchange rate providers, ranging from public sources (the European Central Bank, several national banks, exchangerate.host) to commercial **exchange rate APIs** that require an API key. Caching, historical rates, and a fallback chain are built in. Used in real-world PHP applications since 2014.

## 💡 What is Swap?

- Swap is a PHP library for currency conversion and exchange rate retrieval.
- It exposes a wide range of exchange rate providers behind a common interface.
- It caches results via PSR-16 SimpleCache.
- It supports historical rates.
- It supports a fallback chain. When a provider errors, the next provider in the chain is tried.

## 🎯 When should you use Swap?

- Use Swap when you need to retrieve exchange rates in a PHP application: currency conversion workflows, multi-currency pricing, invoice totals, reconciliation, or historical FX data.
- Use the lower-level [Exchanger](https://github.com/florianv/exchanger) library when Swap's defaults are too opinionated and you want finer control over chain composition, caching, or HTTP plumbing.

## Why not call an exchange rate API directly?

You can integrate a single exchange rate API directly in your application.

Swap is useful when you need more than a single provider:

- **Provider abstraction** — switch providers without rewriting your code
- **Fallback support** — if one provider fails, another can be used automatically
- **Unified interface** — all providers share the same API
- **Caching** — reduce API calls and improve performance
- **Flexibility** — combine public and commercial providers

For simple use cases, calling a single API may be enough.

Swap becomes valuable when you need reliability, flexibility, or long-term maintainability.

## 📦 Installation

Swap requires PHP 8.2 or newer.

```bash
$ composer require php-http/curl-client nyholm/psr7 php-http/message florianv/swap
composer require florianv/swap symfony/http-client nyholm/psr7
```

`symfony/http-client` is the PSR-18 HTTP client and `nyholm/psr7` provides the PSR-17 factories. Any PSR-18 / PSR-17 implementation works (see the [documentation](doc/readme.md) for alternatives such as Guzzle).

## ⚡ Quickstart

```php
use Swap\Builder;

// Build Swap
// Build Swap with the European Central Bank (free, no API key required).
$swap = (new Builder())
->add('european_central_bank')
->build();

// Use the Fixer service as first level provider
->add('apilayer_fixer', ['api_key' => 'Get your key here: https://fixer.io/'])

// Use the currencylayer service as first fallback
->add('apilayer_currency_data', ['api_key' => 'Get your key here: https://currencylayer.com'])

// Use the exchangerates service as second fallback
->add('apilayer_exchange_rates_data', ['api_key' => 'Get your key here: https://exchangeratesapi.io/'])
->build();

// Get the latest EUR/USD rate
// EUR → USD exchange rate
$rate = $swap->latest('EUR/USD');

// 1.129
$rate->getValue();
$rate->getValue(); // e.g. 1.0823 (a float)
$rate->getDate()->format('Y-m-d'); // e.g. 2026-04-29
$rate->getProviderName(); // 'european_central_bank'

// 2016-08-26
$rate->getDate()->format('Y-m-d');
// Convert an amount using the returned rate
$amountInEUR = 100.00;
$amountInUSD = $amountInEUR * $rate->getValue();

// Get the EUR/USD rate 15 days ago
$rate = $swap->historical('EUR/USD', (new \DateTime())->modify('-15 days'));
// Retrieve a historical rate
$past = $swap->historical('EUR/USD', new \DateTime('-15 days'));
```

## Documentation

The documentation for the current branch can be found [here](https://github.com/florianv/swap/blob/master/doc/readme.md).

## Services

Here is the list of the currently implemented services:

| Service | Base Currency | Quote Currency | Historical |
|---------------------------------------------------------------------------|----------------------|----------------|----------------|
| [Fixer](https://fixer.io/) | EUR (free, no SSL), * (paid) | * | Yes |
| [Currency Data](https://currencylayer.com) | USD (free), * (paid) | * | Yes |
| [Exchange Rates Data](https://exchangeratesapi.io/) | USD (free), * (paid) | * | Yes |
| [Abstract](https://www.abstractapi.com) | * | * | Yes |
| [coinlayer](https://coinlayer.com) | * Crypto (Limited standard currencies) | * Crypto (Limited standard currencies) | Yes |
| [Fixer](https://fixer.io) | EUR (free, no SSL), * (paid) | * | Yes |
| [Currency Data](https://currencylayer.com) | USD (free), * (paid) | * | Yes |
| [exchangeratesapi](https://exchangeratesapi.io) | USD (free), * (paid) | * | Yes |
| [European Central Bank](https://www.ecb.europa.eu/home/html/index.en.html) | EUR | * | Yes |
| [National Bank of Georgia](https://nbg.gov.ge) | * | GEL | Yes |
| [National Bank of the Republic of Belarus](https://www.nbrb.by) | * | BYN (from 01-07-2016),<br>BYR (01-01-2000 - 30-06-2016),<br>BYB (25-05-1992 - 31-12-1999) | Yes |
| [National Bank of Romania](http://www.bnr.ro) | RON, AED, AUD, BGN, BRL, CAD, CHF, CNY, CZK, DKK, EGP, EUR, GBP, HRK, HUF, INR, JPY, KRW, MDL, MXN, NOK, NZD, PLN, RSD, RUB, SEK, TRY, UAH, USD, XAU, XDR, ZAR | RON, AED, AUD, BGN, BRL, CAD, CHF, CNY, CZK, DKK, EGP, EUR, GBP, HRK, HUF, INR, JPY, KRW, MDL, MXN, NOK, NZD, PLN, RSD, RUB, SEK, TRY, UAH, USD, XAU, XDR, ZAR | Yes |
| [National Bank of Ukranie](https://bank.gov.ua) | * | UAH | Yes |
| [Central Bank of the Republic of Turkey](http://www.tcmb.gov.tr) | * | TRY | Yes |
| [Central Bank of the Republic of Uzbekistan](https://cbu.uz) | * | UZS | Yes |
| [Central Bank of the Czech Republic](https://www.cnb.cz) | * | CZK | Yes |
| [Central Bank of Russia](https://cbr.ru) | * | RUB | Yes |
| [Bulgarian National Bank](http://bnb.bg) | * | BGN | Yes |
| [WebserviceX](http://www.webservicex.net) | * | * | No |
| [1Forge](https://1forge.com) | * (free but limited or paid) | * (free but limited or paid) | No |
| [Cryptonator](https://www.cryptonator.com) | * Crypto (Limited standard currencies) | * Crypto (Limited standard currencies) | No |
| [CurrencyDataFeed](https://currencydatafeed.com) | * (free but limited or paid) | * (free but limited or paid) | No |
| [Open Exchange Rates](https://openexchangerates.org) | USD (free), * (paid) | * | Yes |
| [Xignite](https://www.xignite.com) | * | * | Yes |
| [Currency Converter API](https://www.currencyconverterapi.com) | * | * | Yes (free but limited or paid) |
| [xChangeApi.com](https://xchangeapi.com) | * | * | Yes |
| [fastFOREX.io](https://www.fastforex.io) | USD (free), * (paid) | * | No |
| [exchangerate.host](https://www.exchangerate.host) | * | * | Yes |
| Array | * | * | Yes |

Additionally, you can add your own services as long as they implement the `ExchangeRateService` interface.

## Integrations

- A Symfony Bundle [FlorianvSwapBundle](https://github.com/florianv/FlorianvSwapBundle)
- A Laravel Package [florianv/laravel-swap](https://github.com/florianv/laravel-swap)

## Credits
Swap retrieves the rate; your application multiplies the amount by `$rate->getValue()` to perform the conversion.

- [Florian Voutzinos](https://github.com/florianv)
- [All Contributors](https://github.com/florianv/swap/contributors)
## 🔁 Configuring multiple providers (fallback chain)

```php
$swap = (new Builder())
->add('your_primary_provider', ['api_key' => 'YOUR_KEY']) // see Providers below
->add('your_fallback_provider', ['api_key' => 'YOUR_KEY'])
->add('european_central_bank') // free fallback for EUR-base pairs
->build();
```

Providers are tried in order. If a provider does not support the requested currency pair, it is skipped silently. If a provider throws an error, the next provider is tried. If every provider fails, a `ChainException` is thrown with all collected errors.

## 🛠 Common use cases

- Display localized prices in multi-currency storefronts.
- Compute invoice totals across currencies.
- Reconcile multi-currency ledgers using historical rates.
- Power internal FX dashboards with rate history.
- Build currency conversion infrastructure for fintech and ERP applications.

## 🧭 Which package should I use?

The Swap ecosystem is a layered toolkit for currency conversion in PHP:

- **Swap.** The easy-to-use, high-level API (this package).
- **Exchanger.** Lower-level, more granular alternative; direct access to the 30 provider implementations and the `ExchangeRateService` interface.
- **Laravel Swap.** Laravel application of Swap.
- **Symfony Swap.** Symfony integration of Swap.

All four packages are MIT-licensed and require PHP 8.2 or newer.

## 📊 Providers

Start with a single provider (for example the European Central Bank), then add others as needed.

## License
Swap supports 30 exchange rate providers via [Exchanger](https://github.com/florianv/exchanger). Pass the **identifier** to `Builder::add()`.

### Public providers (no API key required)

| Service | Identifier | Base | Quote | Historical |
| ------------------------------------------ | ------------------------------------- | -------------- | -------------- | ---------- |
| Bulgarian National Bank | `bulgarian_national_bank` | * | BGN | Yes |
| Central Bank of the Czech Republic | `central_bank_of_czech_republic` | * | CZK | Yes |
| Central Bank of the Republic of Turkey | `central_bank_of_republic_turkey` | * | TRY | Yes |
| Central Bank of the Republic of Uzbekistan | `central_bank_of_republic_uzbekistan` | * | UZS | Yes |
| Cryptonator | `cryptonator` | * (crypto) | * (crypto) | No |
| European Central Bank | `european_central_bank` | EUR | * | Yes |
| exchangerate.host | `exchangeratehost` | * | * | Yes |
| National Bank of Georgia | `national_bank_of_georgia` | * | GEL | Yes |
| National Bank of Romania | `national_bank_of_romania` | (limited list) | (limited list) | Yes |
| National Bank of the Republic of Belarus | `national_bank_of_republic_belarus` | * | BYN | Yes |
| National Bank of Ukraine | `national_bank_of_ukraine` | * | UAH | Yes |
| Russian Central Bank | `russian_central_bank` | * | RUB | Yes |
| WebserviceX | `webservicex` | * | * | No |

### Commercial providers (require an API key)

| Service | Identifier | Base | Quote | Historical |
| ------------------------------- | ------------------------------ | -------------------- | ----- | ---------- |
| AbstractAPI | `abstract_api` | * | * | Yes |
| coinlayer | `coin_layer` | * (crypto) | * | Yes |
| Currency Converter API | `currency_converter` | * | * | Yes |
| Currency Data (APILayer) | `apilayer_currency_data` | USD (free), * (paid) | * | Yes |
| CurrencyDataFeed | `currency_data_feed` | * | * | No |
| currencylayer (direct) | `currency_layer` | USD (free), * (paid) | * | Yes |
| Exchange Rates Data (APILayer) | `apilayer_exchange_rates_data` | USD (free), * (paid) | * | Yes |
| exchangeratesapi (direct) | `exchange_rates_api` | USD (free), * (paid) | * | Yes |
| fastFOREX.io | `fastforex` | USD (free), * (paid) | * | No |
| Fixer (APILayer) | `apilayer_fixer` | EUR (free), * (paid) | * | Yes |
| Fixer (direct) | `fixer` | EUR (free), * (paid) | * | Yes |
| 1Forge | `forge` | * | * | No |
| Open Exchange Rates | `open_exchange_rates` | USD (free), * (paid) | * | Yes |
| xChangeApi.com | `xchangeapi` | * | * | Yes |
| Xignite | `xignite` | * | * | Yes |

You can also add your own provider by implementing the `Exchanger\Contract\ExchangeRateService` interface and passing the instance to `Builder::addExchangeRateService()`.

## ⚙ Caching, HTTP client, and error handling

- **Caching.** Swap uses PSR-16 `SimpleCache`. Configure once on the builder:

```php
$swap = (new Builder())->useSimpleCache($psr16Cache)->add('european_central_bank')->build();
```

Disable caching for a single query: `$swap->latest('EUR/USD', ['cache' => false])`.
Override the TTL for a single query: `$swap->latest('EUR/USD', ['cache_ttl' => 3600])`.

- **HTTP client.** Any PSR-18 client (`symfony/http-client`, `php-http/guzzle7-adapter`, etc.) is supported and auto-discovered via `php-http/discovery`. To pass an explicit instance, use `Builder::useHttpClient()`.

- **Errors.** When every configured provider has either skipped (unsupported pair) or thrown, Swap raises an `Exchanger\Exception\ChainException` containing all collected exceptions.

## 📚 Documentation

The full documentation is in [`doc/readme.md`](doc/readme.md), and is also published at [florianv.github.io/swap](https://florianv.github.io/swap/).

## 🧩 Related packages

The Swap ecosystem:

- [**Swap**](https://github.com/florianv/swap): easy-to-use PHP currency conversion library.
- [**Exchanger**](https://github.com/florianv/exchanger): lower-level, more granular alternative; direct access to provider implementations.
- [**Laravel Swap**](https://github.com/florianv/laravel-swap): Laravel application of Swap.
- [**Symfony Swap**](https://github.com/florianv/symfony-swap): Symfony integration of Swap.

## 🤝 Sponsorship

The Swap ecosystem is open to selected sponsorships from exchange rate API providers and financial infrastructure companies.

Sponsorship can include:

- Documentation visibility
- Integration examples
- Ecosystem-level visibility across Swap, Exchanger, Laravel Swap, and Symfony Swap

For inquiries, contact the maintainer via [GitHub](https://github.com/florianv).

## 🙌 Contributing

Issues and pull requests are welcome. Please see the existing [issues](https://github.com/florianv/swap/issues) before opening a new one.

## 📄 License

The MIT License (MIT). Please see [LICENSE](https://github.com/florianv/swap/blob/master/LICENSE) for more information.

## 👏 Credits

- [Florian Voutzinos](https://github.com/florianv)
- [All contributors](https://github.com/florianv/swap/contributors)
10 changes: 8 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
{
"name": "florianv/swap",
"description": "Exchange rates library for PHP",
"description": "PHP currency conversion library for retrieving exchange rates from 30 providers, with caching and fallback.",
"license": "MIT",
"keywords": [
"currency",
"money",
"rate",
"conversion",
"exchange rates"
"exchange rates",
"currency conversion",
"currency conversion library",
"php currency conversion",
"exchange rate api",
"forex",
"forex api"
],
"authors": [
{
Expand Down
Loading