money icon indicating copy to clipboard operation
money copied to clipboard

Have currency converter implementation using any free and reliable online service

Open zpbappi opened this issue 7 years ago • 2 comments

Provide an implementation of ICurrencyConverter using an online service (free + reliable). This can be optionally consumed by the users. I would like to get your thoughts on:

  • Should such an implementation be in the package with a namespace like Money.Contrib.CurrencyConverter?
  • Should I publish the currency converters as a separate contrib package all together?

zpbappi avatar Feb 18 '18 05:02 zpbappi

Finding a free and reliable API provider that doesn't limit API calls to 1,000 per month seems to be problematic: https://www.quora.com/Is-there-an-API-for-real-time-currency-conversion Others that I found followed the same pattern.

I'm inclined to think the currency converter should live in a separate package for extensibility purposes.

RocketSquirrel avatar Jul 25 '18 10:07 RocketSquirrel

Hi, The issue opened long time ago, but I found a free API and implemented in my own project. Firstly I converted Money project to .Net version 8.0 (I use this version) and implemented the API. The implementation is below:

namespace Money
{
    public class FrankfurterApiConvertedDto
    {
        public decimal Amount { get; set; }
        public string Base { get; set; }
        public DateTime Date { get; set; }
        public Dictionary<Currency, decimal> Rates { get; set; }
    }


    public class FrankfurterApiCurrencyConverter<T> : ICurrencyConverter<T> 
        where T : struct
    {
        private readonly HttpClient _httpClient;

        public FrankfurterApiCurrencyConverter()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("https://api.frankfurter.app/");
        }

        public T Convert(T fromAmount, Currency fromCurrency, Currency toCurrency)
        {
            if (fromCurrency == toCurrency)
            {
                return fromAmount;
            }

            var converterAddress = $"latest?amount=1&from={fromCurrency}&to={toCurrency}";
            var rate = _httpClient.GetFromJsonAsync<FrankfurterApiConvertedDto>(converterAddress).GetAwaiter().GetResult();

            var rateConvertedToT = NumericTypeHelper.ConvertTo<T>(rate.Rates[toCurrency]);

            return BinaryOperationHelper.MultiplyChecked(fromAmount, rateConvertedToT);
        }
    }
}

The API does not support all of the currencies, a check is needed, API has a supported currencies method. Also as I remember, rates are updated once in a day, you can look at the documentation.

HttpClient usage may be wrong, I generally use Typed Http Clients in web projects. It is just an idea of a free API usage.

I don't totaly use Money project as is, I was inspired by your project, thank you for your work.

hasankaplan-github avatar Jul 10 '24 10:07 hasankaplan-github