You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CurrencyService.php 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Carbon;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Support\Facades\Http;
  6. class CurrencyService
  7. {
  8. public function getExchangeRate($from, $to)
  9. {
  10. $date = Carbon::today()->format('Y-m-d');
  11. $req_url = 'https://api.exchangerate.host/convert?from=' . $from . '&to=' . $to . '&date=' . $date;
  12. $response = Http::get($req_url);
  13. if ($response->successful()) {
  14. $responseData = $response->json();
  15. if ($responseData['success'] === true) {
  16. return $responseData['info']['rate'];
  17. }
  18. }
  19. return null;
  20. }
  21. public function getCachedExchangeRate(string $defaultCurrencyCode, string $code): ?float
  22. {
  23. // Include both the default currency code and the target currency code in the cache key
  24. $cacheKey = 'currency_data_' . $defaultCurrencyCode . '_' . $code;
  25. // Attempt to retrieve the cached exchange rate
  26. $cachedData = Cache::get($cacheKey);
  27. // If the cached exchange rate exists, return it
  28. if ($cachedData !== null) {
  29. return $cachedData['rate'];
  30. }
  31. // If the cached exchange rate does not exist, retrieve it from the API
  32. $rate = $this->getExchangeRate($defaultCurrencyCode, $code);
  33. // If the API call was successful, cache the exchange rate
  34. if ($rate !== null) {
  35. // Store the exchange rate in the cache for 24 hours
  36. $dataToCache = compact('rate');
  37. $expirationTimeInSeconds = 60 * 60 * 24; // 24 hours
  38. Cache::put($cacheKey, $dataToCache, $expirationTimeInSeconds);
  39. }
  40. return $rate;
  41. }
  42. }