florianv/swap 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

florianv/swap

Composer 安装命令:

composer require florianv/swap

包简介

PHP currency conversion library for retrieving exchange rates from 30 providers, with caching and fallback.

README 文档

README

Tests Psalm Total Downloads Version

The easy-to-use PHP currency conversion library. Retrieve exchange rates from 30 providers, with caching and fallback. Maintained since 2014.

fastFOREX Sponsored by fastFOREX. Real-time JSON API, 160+ currencies, 55+ years of history, 500+ cryptocurrencies. Free tier; paid plans from $18/month. → Get a free fastFOREX API key

Swap retrieves currency exchange rates in PHP, behind a single API. Use commercial providers in production, or free public sources (ECB, national banks) when you don't need volume. Caching, historical rates and provider fallback are built in. Maintained 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.

📦 Installation

Swap requires PHP 8.2 or newer.

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 for alternatives such as Guzzle).

⚡ Quickstart

The recommended setup uses fastFOREX (the project's sponsor) as the primary provider. Grab a free key and you're ready.

use Swap\Builder;

// Recommended: fastFOREX. Get a free API key at https://www.fastforex.io
$swap = (new Builder())
    ->add('fastforex', ['api_key' => getenv('FASTFOREX_API_KEY')])
    ->build();

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

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

// Convert an amount using the returned rate
$amountInEUR = 100.00;
$amountInUSD = $amountInEUR * $rate->getValue();

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

No API key? Start with the European Central Bank (free, EUR-base only).
$swap = (new Builder())
    ->add('european_central_bank')
    ->build();

$rate = $swap->latest('EUR/USD');

The European Central Bank publishes EUR-base rates with daily granularity. For non-EUR base pairs, more frequent updates, or a wider currency list, switch to fastFOREX or another commercial provider.

🔁 Configuring multiple providers (fallback chain)

A production-grade setup pairs fastFOREX with one or more fallbacks for redundancy:

$swap = (new Builder())
    // Primary provider, recommended
    ->add('fastforex', ['api_key' => getenv('FASTFOREX_API_KEY')])

    // Free fallback for EUR-base pairs
    ->add('european_central_bank')
    ->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.

For amount conversion (including the moneyphp/money integration via SwapExchange), see Converting amounts in the documentation.

📊 Providers

Swap supports 30 exchange rate providers. Pass the identifier to Builder::add().

Commercial providers (require an API key)

Service Identifier Base Quote Historical
fastFOREX fastforex * * Yes
AbstractAPI abstract_api * * Yes
coinlayer coin_layer * (crypto) * Yes
Cryptonator cryptonator * (crypto) * (crypto) No
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
exchangerate.host exchangeratehost * * Yes
exchangeratesapi (direct) exchange_rates_api USD (free), * (paid) * Yes
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
WebserviceX webservicex * * No
xChangeApi.com xchangeapi * * Yes
Xignite xignite * * Yes

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
European Central Bank european_central_bank EUR * 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

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

🎯 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 library when Swap's defaults are too opinionated and you want finer control over chain composition, caching, or HTTP plumbing.

🛠 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.

📚 Documentation

Caching (PSR-16), HTTP client selection (PSR-18 / Guzzle / useHttpClient), error handling (ChainException), per-query options and the full provider configuration reference live in doc/readme.md. The same content is also published at florianv.github.io/swap.

🙌 Contributing

Issues and pull requests are welcome. Please see the existing issues before opening a new one.

📄 License

The MIT License (MIT). Please see LICENSE for more information.

👏 Credits

florianv/swap 适用场景与选型建议

florianv/swap 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.73M 次下载、GitHub Stars 达 1.33k, 最近一次更新时间为 2014 年 05 月 12 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「money」 「currency」 「conversion」 「Rate」 「exchange rates」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 florianv/swap 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 florianv/swap 我们能提供哪些服务?
定制开发 / 二次开发

基于 florianv/swap 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.73M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1343
  • 点击次数: 45
  • 依赖项目数: 19
  • 推荐数: 7

GitHub 信息

  • Stars: 1332
  • Watchers: 35
  • Forks: 145
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2014-05-12