123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446 |
- using OASystem.Domain.Dtos.SmallFun;
- using OASystem.Domain.ViewModels.JuHeExchangeRate;
- using OASystem.Domain.ViewModels.SmallFun;
- using System.Text.Json;
- namespace OASystem.API.OAMethodLib.JuHeAPI
- {
- /// <summary>
- /// 聚合Api 服务
- /// </summary>
- public class JuHeApiService : IJuHeApiService
- {
- private readonly HttpClient _httpClient;
- private readonly HttpClient _httpClientTranslate;
- private readonly string _appKey = "0f5429e9fbb8637c0ff3f14bbb42c732"; //配置您申请的appkey
- private readonly string _appkey_textTranslate = "59db9edbac297e30695973aa1d856391"; //文本翻译 appkey
- /// <summary>
- /// 初始化
- /// </summary>
- /// <param name="clientFactory"></param>
- public JuHeApiService(IHttpClientFactory clientFactory)
- {
- _httpClient = clientFactory.CreateClient("PublicJuHeApi");
- _httpClientTranslate = clientFactory.CreateClient("PublicJuHeTranslateApi");
- }
- #region 汇率
- /// <summary>
- /// 获取汇率
- /// </summary>
- /// <returns></returns>
- public async Task<JuHeAPIResult> GetExchangeRateAsync()
- {
- var result = new JuHeAPIResult() { Resultcode = "-2", Reason = "未知错误" };
- string rateDataString = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringGetAsync<string>("JuHeApiExchangeRate");//string 取
- if (string.IsNullOrEmpty(rateDataString))
- {
- #region 请求接口并存入缓存
- string url = string.Format("/finance/exchange/rmbquot");
- try
- {
- var exchangeReq = await _httpClient.PostAsync(url,
- new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
- {
- new KeyValuePair<string, string>("key",_appKey),//你申请的key
- new KeyValuePair<string, string>("type","0"), //两种格式(0或者1,默认为0)
- new KeyValuePair<string, string>("bank","3") //(0:工商银行,1:招商银行,2:建设银行,3:中国银行,
- //4:交通银行,5:农业银行,默认为:0)
- }));
- if (exchangeReq.IsSuccessStatusCode)
- {
- var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
- result = System.Text.Json.JsonSerializer.Deserialize<JuHeAPIResult>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (result.Resultcode == "200")
- {
- List<ExchangeRateModel> rateList = new List<ExchangeRateModel>();
- #region 处理数据类型
- JArray jar = JArray.Parse(result.Result.ToJson());
- for (int i = 0; i < jar.Count; i++)
- {
- JObject j = JObject.Parse(jar[i].ToString());
- for (int x = 1; x < j.Count + 1; x++)
- {
- string rateName = "data" + x;
- string rateDataStr = j[rateName].ToString();
- if (!string.IsNullOrEmpty(rateDataStr))
- {
- ExchangeRateModel exchangeRate = JsonConvert.DeserializeObject<ExchangeRateModel>(rateDataStr);
- rateList.Add(exchangeRate);
- }
- }
- }
- #endregion
- TimeSpan ts = DateTime.Now.AddMinutes(120) - DateTime.Now; //设置redis 过期时间 120分钟
- await RedisRepository
- .RedisFactory
- .CreateRedisRepository()
- .StringSetAsync<string>("JuHeApiExchangeRate", rateList.ToJson(), ts);//string 存
- result.Result = rateList;
- }
- else
- {
- result.Reason = string.Format("聚合APIError[Error_Code:{0} Resultcode:{1} Msg:{2}]",
- result.Error_code, result.Resultcode, result.Result);
- }
- }
- else
- {
- result.Reason = "汇率接口请求失败!";
- }
- }
- catch (Exception ex)
- {
- result.Reason = ex.Message;
- }
- #endregion
- }
- else
- {
- result.Resultcode = "200";
- result.Result = JsonConvert.DeserializeObject<List<ExchangeRateModel>>(rateDataString);
- }
- return result;
- }
- /// <summary>
- /// 获取汇率 Single
- /// </summary>
- /// <param name="currencyCode">币种code</param>
- /// <returns></returns>
- public async Task<Result> GetSingleRateAsync(string currencyCode)
- {
- var result = new Result();
- if (currencyCode.ToUpper() == "CNY")
- {
- return result;
- }
- var resultData = await GetExchangeRateAsync();
- var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
- var currencyModel = rateCurrencyData.Where(a => a.CurrencyCode == currencyCode).FirstOrDefault();
- if (currencyModel != null)
- {
- if (resultData.Resultcode == "200")
- {
- if (resultData.Result != null)
- {
- result.Code = 0;
- result.Data = ((List<ExchangeRateModel>)resultData.Result).Where(a => a.Name == currencyModel.CurrencyName).FirstOrDefault();
- }
- }
- else
- {
- result.Msg = resultData.Reason;
- }
- }
- return result;
- }
- /// <summary>
- /// 获取汇率 Single
- /// </summary>
- /// <param name="currencyCodes">币种codes</param>
- /// <returns></returns>
- public async Task<List<ExchangeRateModel>> PostItemRateAsync(string[] currencyCodes)
- {
- List<ExchangeRateModel> result = new List<ExchangeRateModel>();
- //if (currencyCodes.Length <= 0)
- //{
- // return result;
- //}
- var resultData = await GetExchangeRateAsync();
- var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
- var currencyModel = rateCurrencyData.WhereIF(currencyCodes.Length >0,a => currencyCodes.Any(b => a.CurrencyCode == b)).ToList();
- if (currencyModel.Count > 0)
- {
- if (resultData.Resultcode == "200")
- {
- if (resultData.Result != null)
- {
- var data = (List<ExchangeRateModel>)resultData.Result;
- foreach (var item in currencyModel)
- {
- ExchangeRateModel exchangeRateModel = data.Where(it => it.Name.Equals(item.CurrencyName)).FirstOrDefault();
- if (exchangeRateModel != null)
- {
- result.Add(exchangeRateModel);
- }
- }
- //result = ((List<ExchangeRateModel>)resultData.Result).Where(a => a.Name == currencyModel.CurrencyName).ToList();
- }
- }
- }
- return result;
- }
- /// <summary>
- /// 获取汇率转换结果
- /// </summary>
- /// <returns></returns>
- public async Task<Result> GetExchangeRateAsync(ExchangeRateDto dto)
- {
- var result = new Result() { Code = -2, Msg = "未知错误" };
- var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
- if (dto.CurrencyCodePer.ToUpper() == "CNY")
- {
- var currencyModelSuf = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodeSuf).FirstOrDefault();
- if (currencyModelSuf == null)
- {
- result.Msg = "转换后币种未找到!";
- return result;
- }
- var rateModelSuf = await GetSingleRateAsync(currencyModelSuf.CurrencyCode);
- if (rateModelSuf.Code != 0)
- {
- result.Msg = rateModelSuf.Msg;
- return result;
- }
- if (string.IsNullOrEmpty(rateModelSuf.Data.FSellPri))
- {
- result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelSuf.CurrencyName, currencyModelSuf.CurrencyCode);
- return result;
- }
- decimal moneySuf = Convert.ToDecimal(rateModelSuf.Data.FSellPri) / 100; //fSellPri
- decimal settlementMoney = dto.Money / moneySuf;
- var rateView = new ExchangeRateView
- {
- CurrencyCodePre = dto.CurrencyCodePer,
- CurrencyNamePre = "人民币",
- MoneyPre = dto.Money,
- CurrencyCodeSuf = dto.CurrencyCodeSuf,
- CurrencyNameSuf = currencyModelSuf.CurrencyName,
- MoneySuf = CommonFun.CutDecimalWithN(settlementMoney, 4),
- UpdateTime = string.Format("{0} {1}", rateModelSuf.Data.Date, rateModelSuf.Data.Time)
- };
- result.Code = 0;
- result.Msg = "成功!";
- result.Data = rateView;
- return result;
- }
- else
- {
- var currencyModelPre = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodePer).FirstOrDefault();
- if (currencyModelPre == null)
- {
- result.Msg = "转换前币种未找到!";
- return result;
- }
- var rateModelPre = await GetSingleRateAsync(currencyModelPre.CurrencyCode);
- if (rateModelPre.Code != 0)
- {
- result.Msg = rateModelPre.Msg;
- return result;
- }
- if (string.IsNullOrEmpty(rateModelPre.Data.FSellPri))
- {
- result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelPre.CurrencyName, currencyModelPre.CurrencyCode);
- return result;
- }
- decimal moneyPre = (Convert.ToDecimal(rateModelPre.Data.FSellPri) / 100) * dto.Money; //fSellPri
- if (dto.CurrencyCodeSuf.ToUpper() == "CNY")
- {
- var rateView = new ExchangeRateView
- {
- CurrencyCodePre = dto.CurrencyCodePer,
- CurrencyNamePre = currencyModelPre.CurrencyName,
- MoneyPre = dto.Money,
- CurrencyCodeSuf = "CNY",
- CurrencyNameSuf = "人民币",
- MoneySuf = CommonFun.CutDecimalWithN(moneyPre, 4),
- UpdateTime = string.Format("{0} {1}", rateModelPre.Data.Date, rateModelPre.Data.Time)
- };
- result.Code = 0;
- result.Msg = "成功!";
- result.Data = rateView;
- }
- else
- {
- var currencyModelSuf = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodeSuf).FirstOrDefault();
- if (currencyModelSuf == null)
- {
- result.Msg = "转换后币种未找到!";
- return result;
- }
- var rateModelSuf = await GetSingleRateAsync(currencyModelSuf.CurrencyCode);
- if (rateModelSuf.Code != 0)
- {
- result.Msg = rateModelSuf.Msg;
- return result;
- }
- if (string.IsNullOrEmpty(rateModelSuf.Data.FSellPri))
- {
- result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelSuf.CurrencyName, currencyModelSuf.CurrencyCode);
- return result;
- }
- decimal moneySuf = Convert.ToDecimal(rateModelSuf.Data.FSellPri) / 100; //fSellPri
- decimal settlementMoney = moneyPre / moneySuf;
- var rateView = new ExchangeRateView
- {
- CurrencyCodePre = dto.CurrencyCodePer,
- CurrencyNamePre = currencyModelPre.CurrencyName,
- MoneyPre = dto.Money,
- CurrencyCodeSuf = dto.CurrencyCodeSuf,
- CurrencyNameSuf = currencyModelSuf.CurrencyName,
- MoneySuf = CommonFun.CutDecimalWithN(settlementMoney, 4),
- UpdateTime = string.Format("{0} {1}", rateModelSuf.Data.Date, rateModelSuf.Data.Time)
- };
- result.Code = 0;
- result.Msg = "成功!";
- result.Data = rateView;
- }
- }
- return result;
- }
- #endregion
- #region 文本翻译
- /// <summary>
- /// 文本翻译
- /// </summary>
- /// <param name="source">原文,数据类型为字符串,也可为数组(元素必须为字符串类型);每次请求的字符串长度之和尽量不要超过 </param>
- /// <param name="trans_type">翻译方向:en2zh(英文-中文),zh2en(中文-英文),ja2zh(日文-中文),zh2ja(中文-日文),ko2zh(韩文-中文),zh2ko(中文-韩文)</param>
- /// <returns></returns>
- public async Task<string> GetTextTranslateAsync(string source, string trans_type = "zh2en")
- {
- string res = "";
- var result = new JuHeAPIResult() { Resultcode = "10020", Reason = "接口维护" };
- #region 请求接口
- string url = string.Format($"/translate/query");
- var exchangeReq = await _httpClientTranslate
- .PostAsync(url,
- new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
- {
- new KeyValuePair<string, string>("key",_appkey_textTranslate),//你申请的key
- new KeyValuePair<string, string>("source",source),
- new KeyValuePair<string, string>("trans_type",trans_type)
- }));
- if (exchangeReq.IsSuccessStatusCode)
- {
- var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
- JuHeTransResult result1 = System.Text.Json.JsonSerializer.Deserialize<JuHeTransResult>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (result1.error_code == 0)
- {
- res = result1.result.data.res;
- }
- else
- {
- res = string.Format("聚合APIError[Error_Code:{0} Resultcode:{1} Msg:{2}]",
- result1.error_code, result1.reason, result1.result);
- }
- }
- else
- {
- result.Reason = "汇率接口请求失败!";
- }
- #endregion
- return res;
- }
- #endregion
- #region 洲 当前时间
- /// <summary>
- /// 获取全球当前时间
- /// </summary>
- /// <param name="continent">
- /// 洲际:非洲、美洲、南极洲、北极、亚洲、大西洋、 欧洲、太平洋
- /// </param>
- /// <returns></returns>
- public async Task<JuHeAPIResult> GetContinentTimezoneAsync(string continent)
- {
- var continentEn = string.Empty;
- if (string.IsNullOrEmpty(continent)) return new JuHeAPIResult(-1, "请输入州");
- if (continent.Equals("非洲")) continent = $"africa";
- else if (continent.Equals("非洲")) continent = $"africa";
- else if (continent.Equals("美洲")) continent = $"america";
- else if (continent.Equals("南极洲")) continent = $"antarctica";
- else if (continent.Equals("北极")) continent = $"arctic";
- else if (continent.Equals("亚洲")) continent = $"asia";
- else if (continent.Equals("大西洋")) continent = $"atlantic";
- else if (continent.Equals("欧洲")) continent = $"europe";
- else if (continent.Equals("太平洋")) continent = $"pacific";
- else return new JuHeAPIResult(-1, "请输入正确的州");
- #region 请求接口
- string url = string.Format($"/fapig/timezone/show");
- var exchangeReq = await _httpClientTranslate.PostAsync(url,
- new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
- {
- //new KeyValuePair<string, string>("key",_appkey_textTranslate),//你申请的key
- new KeyValuePair<string, string>("key","f3d6b2272d46e0ca9d1c9aca38d8a92c"),//你申请的key
- new KeyValuePair<string, string>("c",continent)
- }));
- if (exchangeReq.IsSuccessStatusCode)
- {
- var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
- var result = System.Text.Json.JsonSerializer.Deserialize<JuHeAPIResult>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
-
- return result;
- }
- #endregion
- return new JuHeAPIResult(-1, "世界时间接口请求失败!");
- }
- #endregion
- }
- }
|