您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CurrencyService.php 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\{Cache, Http};
  4. class CurrencyService
  5. {
  6. public function getExchangeRates($base)
  7. {
  8. $api_key = config('services.currency_api.key');
  9. $base_url = config('services.currency_api.base_url');
  10. $req_url = "{$base_url}/{$api_key}/latest/{$base}";
  11. $response = Http::get($req_url);
  12. if ($response->successful()) {
  13. $responseData = $response->json();
  14. if (isset($responseData['conversion_rates'])) {
  15. return $responseData['conversion_rates'];
  16. }
  17. }
  18. return null;
  19. }
  20. public function updateCachedExchangeRates(string $base): void
  21. {
  22. $rates = $this->getExchangeRates($base);
  23. if ($rates !== null) {
  24. $expirationTimeInSeconds = 60 * 60 * 24; // 1 day (24 hours)
  25. foreach ($rates as $code => $rate) {
  26. $cacheKey = 'currency_data_' . $base . '_' . $code;
  27. Cache::put($cacheKey, $rate, $expirationTimeInSeconds);
  28. }
  29. }
  30. }
  31. public function getCachedExchangeRate(string $defaultCurrencyCode, string $code): ?float
  32. {
  33. $cacheKey = 'currency_data_' . $defaultCurrencyCode . '_' . $code;
  34. $cachedRate = Cache::get($cacheKey);
  35. if ($cachedRate === null) {
  36. $this->updateCachedExchangeRates($defaultCurrencyCode);
  37. $cachedRate = Cache::get($cacheKey);
  38. }
  39. return $cachedRate;
  40. }
  41. }