介绍
在构建 web 应用程序时,有时你可能需要一些处理来自世界各地不同货币的功能。为了能处理不同货币,你需要找到汇率。
本文将探讨如何使用Laravel Exchange Rates软件包与<本土链接>exchangeratesapi.io本土链接>API进行交互。我们还将探讨如何使用它来获取最新或历史汇率以及在不同货币之间转换货币价值。
<p align="center"> <img src="https://ashallendesign.co.uk/images/custom/laravel-exchange-rates-logo.png" alt="Laravel Exchange Rates" width="600"> </p>安装
要开始使用 Laravel Exchange Rates软件包,我们首先需要运行以下命令使用 Composer 安装它:
composer require ashallendesign/laravel-exchange-rates
获取您的API密钥
现在我们已经安装了软件包,我们需要从https://exchangeratesapi.io/pricing获取API密钥。你可以免费注册或者根据你需要的功能使用付费层。
配置
现在,你可以使用以下命令发布软件包的配置文件:
php artisan vendor:publish --provider="AshAllenDesign\LaravelExchangeRates\Providers\ExchangeRatesProvider"
现在您应该已经有了一个新的 config/laravel-exchange-rates.php
文件。默认情况下,该软件包的配置设置为通过HTTP进行请求。但是,如果您正在使用生产环境并且使用了API的付费层级之一,强烈建议使用HTTPS。为此,您可以简单地更新配置文件,并将 api_url
字段更改为以 https://
开头,而不是以 http://
开头。
return [
// ...
'api_url' => env('EXCHANGE_RATES_API_URL', 'http://api.exchangeratesapi.io/v1/'),
// ...
];
您还需要确保将您的API密钥添加到您的 .env
文件中。
EXCHANGE_RATES_API_KEY={Your-API-Key-Here}
获取单日汇率
要获取一种货币兑换另一种货币的汇率,我们可以使用包的 ->exchangeRate()
方法。
例如,如果我们想获取今天从'GBP'兑换到'EUR'的汇率,可以编写如下代码:
$exchangeRates = new ExchangeRate();
$result = $exchangeRates->exchangeRate('GBP', 'EUR');
// $result: '1.10086'
然而,如果我们想获取特定日期的汇率,我们可以传递一个代表我们想要的那天的 Carbon
日期对象。例如,如果我们想获取2021年1月1日从'GBP'兑换到'EUR'的汇率,可以使用以下代码:
$exchangeRates = new ExchangeRate();
$result = $exchangeRates->exchangeRate('GBP', 'EUR', Carbon::create('2021-01-01'));
// $result: '1.10086'
获取两天间的汇率
如果我们想获取给定日期范围内两种货币之间的汇率,我们可以使用包的 ->exchangeRateBetweenDateRange()
方法。
假设我们想获取过去3天从'GBP'到'EUR'的汇率,我们可以这样编写代码:
$exchangeRates = new ExchangeRate();
$result = $exchangeRates->exchangeRateBetweenDateRange(
'GBP',
'EUR',
Carbon::now()->subDays(3),
Carbon::now(),
);
// $result: [
// '2021-07-07' => 1.1092623405
// '2021-07-08' => 1.1120625424
// '2021-07-09' => 1.1153867604
// ];
单个日期的货币转换
该软件包不仅允许我们获取货币之间的汇率,还允许我们将一种货币的价值转换为另一种货币。为此,我们可以使用 ->convert()
方法。
例如,我们可以使用今天的汇率将1英镑'GBP'转换为'EUR'。
$exchangeRates = new ExchangeRate();
$result = $exchangeRates->convert(100, 'GBP', 'EUR', Carbon::now());
// $result: 110.15884906
您可能会注意到我们传递了100
作为第一个参数。这是因为该软件包要求我们使用货币最低单位传递货币价值。例如,在这个案例中,我们想要将1英镑转换,因此我们传递了100,因为1英镑等于100便士。
两天间的货币转换
类似地,您也可以使用该软件包将货币从一个货币转换为另一个货币。为此,我们可以使用 ->convertBetweenDateRange()
方法。
假设我们想使用过去3天的汇率将1英镑'GBP'转换为'EUR'。我们可以这样编写代码:
$exchangeRates = new ExchangeRate();
$exchangeRates->convertBetweenDateRange(
100,
'GBP',
'EUR',
Carbon::now()->subDays(3),
Carbon::now()
);
// $result: [
// '2020-07-07' => 110.92623405,
// '2020-07-08' => 111.20625424,
// '2020-07-09' => 111.53867604,
// ];
通过使用包的缓存提高性能
默认情况下,包将来自 exchangeratesapi.io API 的所有API响应缓存起来。这可以为性能提供显著提升,并减少您服务器的带宽。此外,如果您已经检索过汇率,这也阻止了您使用您一些每月的API请求。
但是,如果您由于任何原因需要从API获取新鲜的结果而不是缓存的结果,该软件包提供了一个 ->shouldBustCache()
方法,我们可以使用它。
让我们看看如何从API获取一个新鲜汇率并忽略任何缓存汇率:
$exchangeRates = new ExchangeRate();
$exchangeRates->shouldBustCache()->convert(100, 'GBP', 'EUR', Carbon::now());
使用包的验证规则
有时您可能允许用户选择将要转换的货币。在这种情况下,确保您的用户只能输入由Exchange Rates API支持的货币非常重要。
为此,Laravel Exchange Rates 包含一个名为 ValidCurrency
的验证规则来验证货币。
假设我们有一个表单请求正在用来验证请求中发送的货币。我们的表单请求可能看起来像这样:
<?php
namespace App\Http\Requests;
use AshAllenDesign\LaravelExchangeRates\Rules\ValidCurrency;
use Illuminate\Foundation\Http\FormRequest;
class MyAwesomeRequest extends FormRequest
{
// ...
public function rules(): array
{
return [
'currency' => ['required', new ValidCurrency()],
];
}
// ...
}
测试
如果您正在为与 Laravel 交易所利率包打交道的代码编写测试,您可能会希望阻止实际的 API 请求。因此,您可能会想使用依赖注入或使用包提供的门面实例化 `ExchangeRate
` 类。实际上,如果您对这类东西感兴趣,我建议您阅读我的文章"如何使您的 Laravel 应用程序更具可测试性"。
让我们快速看一下如何编写一个基本测试,用于获取今天的 'GBP' 到 'EUR' 的汇率。我们的控制器可能看起来像这样
use AshAllenDesign\LaravelExchangeRates\Classes\ExchangeRate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class MyAwesomeController extends Controller
{
public function __invoke(Request $request, ExchangeRate $exchangeRate): JsonResponse
{
$rate = $exchangeRates->exchangeRate('GBP', 'EUR');
return response()->json(['rate' => $rate]);
}
}
现在,让我们为这个控制器方法编写一个测试。我们将假设该方法的路由名称为 `awesome.route
`。我们的测试可能看起来像这样
use AshAllenDesign\LaravelExchangeRates\Classes\ExchangeRate;
use Mockery\MockInterface;
use Tests\TestCase;
class MyAwesomeControllerTest extends TestCase
{
/** @test */
public function success_response_is_returned(): void
{
// Create the mock of the service class.
$this->mock(ExchangeRate::class, function (MockInterface $mock): void {
$mock->shouldReceive('exchangeRate')
->once()
->withArgs(['GBP', 'EUR'])
->andReturn(123.456);
});
$this->postJson(route('awesome.route'))
->assertExactJson([
'rate' => 123.456
]);
}
}
结论
希望这篇文章能向您展示如何使用 Laravel 交易所利率包与 Exchange Rates API 进行交互以获取汇率和货币转换。它还应该让您对如何编写使用此包的代码的测试有简要的了解。
如果这篇帖子对您有所帮助,我很想了解。同样,如果您有任何反馈可以使这篇帖子更好,我也很乐意听到。
如果您想在我发布新帖子时随时收到更新,请随意订阅我的通讯。
继续构建令人惊叹的东西!🚀
joedixon, bdsumon4u 点赞了这篇文章