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 4.3KB

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