fix: 更换汇率API为开放免费接口,解决403错误

This commit is contained in:
claw_bot 2026-03-10 07:32:47 +00:00
parent 1d99099fca
commit 1b8c98b7d6

View File

@ -50,17 +50,17 @@ public class ExchangeRateService : IExchangeRateService
try try
{ {
// 以USD为基础货币获取所有汇率 // 使用免费的开放汇率接口无需API key
var response = await _httpClient.GetFromJsonAsync<ExchangeRateResponse>($"https://v6.exchangerate-api.com/v6/4a8a42b4b9a3c4d5e6f7a8b9/latest/{BaseCurrency}"); var response = await _httpClient.GetFromJsonAsync<OpenExchangeRateResponse>($"https://open.er-api.com/v6/latest/{BaseCurrency}");
if (response == null || response.ConversionRates == null || response.Result != "success") if (response == null || response.Rates == null || response.Result != "success")
{ {
_logger.LogError("汇率API调用失败: {Message}", response?.ErrorType ?? "未知错误"); _logger.LogError("汇率API调用失败: {Message}", response?.ErrorType ?? "未知错误");
throw new Exception("汇率服务暂时不可用"); throw new Exception("汇率服务暂时不可用");
} }
// 转换为USD -> 目标币种的汇率字典 // 转换为USD -> 目标币种的汇率字典
var usdRates = response.ConversionRates; var usdRates = response.Rates;
// 计算 from -> to 的汇率:(1 from = x USD) * (1 USD = y to) = x*y to // 计算 from -> to 的汇率:(1 from = x USD) * (1 USD = y to) = x*y to
decimal fromToUsd = 1 / usdRates[fromCurrency.ToUpper()]; decimal fromToUsd = 1 / usdRates[fromCurrency.ToUpper()];
@ -125,7 +125,7 @@ public class ExchangeRateService : IExchangeRateService
} }
/// <summary> /// <summary>
/// 汇率API响应模型 /// 汇率API响应模型exchangerate-api.com
/// </summary> /// </summary>
public class ExchangeRateResponse public class ExchangeRateResponse
{ {
@ -133,3 +133,13 @@ public class ExchangeRateResponse
public string ErrorType { get; set; } = string.Empty; public string ErrorType { get; set; } = string.Empty;
public Dictionary<string, decimal> ConversionRates { get; set; } = new(); public Dictionary<string, decimal> ConversionRates { get; set; } = new();
} }
/// <summary>
/// 开放汇率API响应模型er-api.com
/// </summary>
public class OpenExchangeRateResponse
{
public string Result { get; set; } = string.Empty;
public string ErrorType { get; set; } = string.Empty;
public Dictionary<string, decimal> Rates { get; set; } = new();
}