Skip to content

Instantly share code, notes, and snippets.

@blorange2
Created July 15, 2022 16:10
Show Gist options
  • Save blorange2/2a7c1174be67e1003d30f05a62a7ad46 to your computer and use it in GitHub Desktop.
Save blorange2/2a7c1174be67e1003d30f05a62a7ad46 to your computer and use it in GitHub Desktop.
<?php
namespace App\Services;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
/**
* ExchangeRates is a wrapper class for the Exchange Retes API at https://api.exchangerate.host
*/
class ExchangeRates
{
public function __construct()
{
$this->baseUrl = 'https://api.exchangerate.host';
}
/**
* This method gets currency conversation data base on the given country codes
* If an amount is provided it will also provide the amount after conversion.
*
* @param $from the three letter currency code to convert from e.g. USD.
* @param $to the three letter currency code to convert to e.g. GBP
* @param $date the date to use when looking up the exchange rate.
* @param $amount the amount to convert. Note this is optional
* @param $placs how many decimals to round the conversion rate to
*
*/
public function convertCurrency(string $from, string $to, Carbon $date = null, string $amount = null, $places = 5)
{
$url = '/convert';
$response = Http::get($this->baseUrl . $url, [
'base' => $from,
'from' => $from,
'to' => $to,
'date' => $date ? $date->format('Y-m-d') : now()->format('Y-m-d'),
'amount' => $amount,
'places' => $places
]);
return $response->json();
}
/**
* This function retrieves historical currency rates based on a given date.
*
* @param Carbon $date a Carbon instance representing a date.
* @param $placs how many decimals to round the conversion rate to
*/
public function exchangeRateAtDate(Carbon $date = null, $places = 5, $symbols = null, string $base = 'GBP')
{
$symbols = is_array($symbols) ? implode(',', $symbols) : null;
$url = $date ? '/' . $date->format('Y-m-d') : '/latest';
$response = Http::get($this->baseUrl . $url, [
'base' => $base,
'places' => $places,
'symbols' => $symbols
]);
return $response->json();
}
/**
* This function retrieves a list of all available currencies.
* This could be used to simply check or even build a validation rule to ensure inputs will return data.
* Returned data contains a symbols array.
*/
public function currencies()
{
$url = '/symbols';
$response = Http::get($this->baseUrl . $url);
return $response->json();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment