Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

CurrencyService.php 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. <?php
  2. namespace App\Services;
  3. use App\Contracts\CurrencyHandler;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Exception\GuzzleException;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Log;
  8. class CurrencyService implements CurrencyHandler
  9. {
  10. protected ?string $api_key;
  11. protected ?string $base_url;
  12. protected Client $client;
  13. public function __construct(?string $api_key, ?string $base_url, Client $client)
  14. {
  15. $this->api_key = $api_key;
  16. $this->base_url = $base_url;
  17. $this->client = $client;
  18. }
  19. /**
  20. * Determine if the Currency Exchange Rate feature is enabled.
  21. */
  22. public function isEnabled(): bool
  23. {
  24. return filled($this->api_key) && filled($this->base_url);
  25. }
  26. public function getSupportedCurrencies(): ?array
  27. {
  28. if (! $this->isEnabled()) {
  29. return null;
  30. }
  31. return Cache::remember('supported_currency_codes', now()->addMonth(), function () {
  32. $response = $this->client->get("{$this->base_url}/{$this->api_key}/codes");
  33. if ($response->getStatusCode() === 200) {
  34. $responseData = json_decode($response->getBody()->getContents(), true);
  35. if ($responseData['result'] === 'success' && filled($responseData['supported_codes'])) {
  36. return array_column($responseData['supported_codes'], 0);
  37. }
  38. }
  39. Log::error('Failed to retrieve supported currencies from Currency API', [
  40. 'status_code' => $response->getStatusCode(),
  41. 'response_body' => $response->getBody()->getContents(),
  42. ]);
  43. return null;
  44. });
  45. }
  46. public function getExchangeRates(string $baseCurrency, array $targetCurrencies): ?array
  47. {
  48. $cacheKey = "currency_rates_{$baseCurrency}";
  49. $cachedRates = Cache::get($cacheKey);
  50. if (Cache::missing($cachedRates)) {
  51. $cachedRates = $this->updateCurrencyRatesCache($baseCurrency);
  52. if (empty($cachedRates)) {
  53. return null;
  54. }
  55. }
  56. $filteredRates = array_intersect_key($cachedRates, array_flip($targetCurrencies));
  57. $filteredRates = array_filter($filteredRates);
  58. $filteredCurrencies = array_keys($filteredRates);
  59. $missingCurrencies = array_diff($targetCurrencies, $filteredCurrencies);
  60. if (filled($missingCurrencies)) {
  61. return null;
  62. }
  63. return $filteredRates;
  64. }
  65. public function getCachedExchangeRates(string $baseCurrency, array $targetCurrencies): ?array
  66. {
  67. if ($this->isEnabled()) {
  68. return $this->getExchangeRates($baseCurrency, $targetCurrencies);
  69. }
  70. return null;
  71. }
  72. public function getCachedExchangeRate(string $baseCurrency, string $targetCurrency): ?float
  73. {
  74. $rates = $this->getCachedExchangeRates($baseCurrency, [$targetCurrency]);
  75. if (isset($rates[$targetCurrency])) {
  76. return (float) $rates[$targetCurrency];
  77. }
  78. return null;
  79. }
  80. public function updateCurrencyRatesCache(string $baseCurrency): ?array
  81. {
  82. try {
  83. $response = $this->client->get("{$this->base_url}/{$this->api_key}/latest/{$baseCurrency}");
  84. if ($response->getStatusCode() === 200) {
  85. $responseData = json_decode($response->getBody()->getContents(), true);
  86. if ($responseData['result'] === 'success' && isset($responseData['conversion_rates'])) {
  87. Cache::put("currency_rates_{$baseCurrency}", $responseData['conversion_rates'], now()->addDay());
  88. return $responseData['conversion_rates'];
  89. }
  90. $errorType = $responseData['error-type'] ?? 'unknown';
  91. Log::error('API returned error', [
  92. 'error_type' => $errorType,
  93. 'response_body' => $responseData,
  94. ]);
  95. } else {
  96. Log::error('Failed to retrieve exchange rates from Currency API', [
  97. 'status_code' => $response->getStatusCode(),
  98. 'response_body' => $response->getBody()->getContents(),
  99. ]);
  100. }
  101. } catch (GuzzleException $e) {
  102. Log::error('Failed to retrieve exchange rates from Currency API', [
  103. 'message' => $e->getMessage(),
  104. 'code' => $e->getCode(),
  105. ]);
  106. }
  107. return null;
  108. }
  109. }