JuHeApiService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using Dm;
  2. using Newtonsoft.Json;
  3. using OASystem.Domain;
  4. using OASystem.Domain.Dtos.SmallFun;
  5. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  6. using OASystem.Domain.ViewModels.SmallFun;
  7. using System.DirectoryServices.Protocols;
  8. using System.Net.Http;
  9. using System.Net.Http.Json;
  10. using System.Text.Json;
  11. using Ubiety.Dns.Core;
  12. namespace OASystem.API.OAMethodLib.JuHeAPI
  13. {
  14. /// <summary>
  15. /// 聚合Api 服务
  16. /// </summary>
  17. public class JuHeApiService: IJuHeApiService
  18. {
  19. private readonly HttpClient _httpClient;
  20. private readonly string _appKey = "0f5429e9fbb8637c0ff3f14bbb42c732"; //配置您申请的appkey
  21. /// <summary>
  22. /// 初始化
  23. /// </summary>
  24. /// <param name="clientFactory"></param>
  25. public JuHeApiService(IHttpClientFactory clientFactory)
  26. {
  27. _httpClient = clientFactory.CreateClient("PublicJuHeApi"); ;
  28. }
  29. /// <summary>
  30. /// 获取汇率
  31. /// </summary>
  32. /// <returns></returns>
  33. public async Task<JuHeAPIResult> GetExchangeRateAsync()
  34. {
  35. var result = new JuHeAPIResult() { Resultcode = "-2",Reason="未知错误" };
  36. string rateDataString = await RedisRepository.RedisFactory
  37. .CreateRedisRepository()
  38. .StringGetAsync<string>("JuHeApiExchangeRate");//string 取
  39. if (string.IsNullOrEmpty(rateDataString))
  40. {
  41. #region 请求接口并存入缓存
  42. string url = string.Format("/finance/exchange/rmbquot");
  43. try
  44. {
  45. var exchangeReq = await _httpClient.PostAsync(url,
  46. new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
  47. {
  48. new KeyValuePair<string, string>("key",_appKey),//你申请的key
  49. new KeyValuePair<string, string>("type","0"), //两种格式(0或者1,默认为0)
  50. new KeyValuePair<string, string>("bank","3") //(0:工商银行,1:招商银行,2:建设银行,3:中国银行,
  51. //4:交通银行,5:农业银行,默认为:0)
  52. }));
  53. if (exchangeReq.IsSuccessStatusCode)
  54. {
  55. var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
  56. result = System.Text.Json.JsonSerializer.Deserialize<JuHeAPIResult>(stringResponse,
  57. new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
  58. if (result.Resultcode == "200")
  59. {
  60. List<ExchangeRateModel> rateList = new List<ExchangeRateModel>();
  61. #region 处理数据类型
  62. JArray jar = JArray.Parse(result.Result.ToJson());
  63. for (int i = 0; i < jar.Count; i++)
  64. {
  65. JObject j = JObject.Parse(jar[i].ToString());
  66. for (int x = 1; x < j.Count + 1; x++)
  67. {
  68. string rateName = "data" + x;
  69. string rateDataStr = j[rateName].ToString();
  70. if (!string.IsNullOrEmpty(rateDataStr))
  71. {
  72. ExchangeRateModel exchangeRate = JsonConvert.DeserializeObject<ExchangeRateModel>(rateDataStr);
  73. rateList.Add(exchangeRate);
  74. }
  75. }
  76. }
  77. #endregion
  78. TimeSpan ts = DateTime.Now.AddMinutes(120) - DateTime.Now; //设置redis 过期时间 120分钟
  79. await RedisRepository
  80. .RedisFactory
  81. .CreateRedisRepository()
  82. .StringSetAsync<string>("JuHeApiExchangeRate", rateList.ToJson(), ts);//string 存
  83. result.Result = rateList;
  84. }
  85. else
  86. {
  87. result.Reason = string.Format("聚合APIError[Error_Code:{0} Resultcode:{1} Msg:{2}]",
  88. result.Error_code, result.Resultcode, result.Result);
  89. }
  90. }
  91. else
  92. {
  93. result.Reason = "汇率接口请求失败!";
  94. }
  95. }
  96. catch (Exception ex)
  97. {
  98. result.Reason = ex.Message;
  99. }
  100. #endregion
  101. }
  102. else
  103. {
  104. result.Resultcode = "200";
  105. result.Result = JsonConvert.DeserializeObject<List<ExchangeRateModel>>(rateDataString);
  106. }
  107. return result;
  108. }
  109. /// <summary>
  110. /// 获取汇率 Single
  111. /// </summary>
  112. /// <param name="currencyCode">币种code</param>
  113. /// <returns></returns>
  114. public async Task<Result> GetSingleRateAsync(string currencyCode)
  115. {
  116. var result = new Result();
  117. if (currencyCode.ToUpper() == "CNY" )
  118. {
  119. return result;
  120. }
  121. var resultData = await GetExchangeRateAsync();
  122. var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
  123. var currencyModel = rateCurrencyData.Where(a => a.CurrencyCode == currencyCode).FirstOrDefault();
  124. if (currencyModel != null)
  125. {
  126. if (resultData.Resultcode == "200")
  127. {
  128. if (resultData.Result != null)
  129. {
  130. result.Code = 0;
  131. result.Data = ((List<ExchangeRateModel>)resultData.Result).Where(a => a.Name == currencyModel.CurrencyName).FirstOrDefault();
  132. }
  133. }
  134. else
  135. {
  136. result.Msg = resultData.Reason;
  137. }
  138. }
  139. return result;
  140. }
  141. /// <summary>
  142. /// 获取汇率 Single
  143. /// </summary>
  144. /// <param name="currencyCodes">币种codes</param>
  145. /// <returns></returns>
  146. public async Task<Result> PostItemRateAsync(string[] currencyCodes)
  147. {
  148. var result = new Result();
  149. if (currencyCodes.Length <= 0 || currencyCodes.Contains("CNY"))
  150. {
  151. result.Msg = "币种Code集合不能为空!";
  152. return result;
  153. }
  154. var resultData = await GetExchangeRateAsync();
  155. var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
  156. var currencyModel = rateCurrencyData.Where(a => currencyCodes.Any(b => a.CurrencyCode == b)).FirstOrDefault();
  157. if (currencyModel != null)
  158. {
  159. if (resultData.Resultcode == "200")
  160. {
  161. if (resultData.Result != null)
  162. {
  163. result.Code = 0;
  164. result.Data = ((List<ExchangeRateModel>)resultData.Result).Where(a => a.Name == currencyModel.CurrencyName).FirstOrDefault();
  165. }
  166. }
  167. else
  168. {
  169. result.Msg = resultData.Reason;
  170. }
  171. }
  172. return result;
  173. }
  174. /// <summary>
  175. /// 获取汇率转换结果
  176. /// </summary>
  177. /// <returns></returns>
  178. public async Task<Result> GetExchangeRateAsync(ExchangeRateDto dto)
  179. {
  180. var result = new Result() { Code = -2, Msg = "未知错误" };
  181. var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
  182. if (dto.CurrencyCodePer.ToUpper() == "CNY")
  183. {
  184. var currencyModelSuf = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodeSuf).FirstOrDefault();
  185. if (currencyModelSuf == null)
  186. {
  187. result.Msg = "转换后币种未找到!";
  188. return result;
  189. }
  190. var rateModelSuf = await GetSingleRateAsync(currencyModelSuf.CurrencyCode);
  191. if (rateModelSuf.Code != 0)
  192. {
  193. result.Msg = rateModelSuf.Msg;
  194. return result;
  195. }
  196. if (string.IsNullOrEmpty(rateModelSuf.Data.FSellPri))
  197. {
  198. result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelSuf.CurrencyName, currencyModelSuf.CurrencyCode);
  199. return result;
  200. }
  201. decimal moneySuf = Convert.ToDecimal(rateModelSuf.Data.FSellPri) / 100 ; //fSellPri
  202. decimal settlementMoney = dto.Money / moneySuf;
  203. var rateView = new ExchangeRateView {
  204. CurrencyCodePre = dto.CurrencyCodePer,
  205. CurrencyNamePre = "人民币",
  206. MoneyPre = dto.Money,
  207. CurrencyCodeSuf = dto.CurrencyCodeSuf,
  208. CurrencyNameSuf = currencyModelSuf.CurrencyName,
  209. MoneySuf = CommonFun.CutDecimalWithN( settlementMoney,4),
  210. UpdateTime = string.Format("{0} {1}", rateModelSuf.Data.Date, rateModelSuf.Data.Time)
  211. };
  212. result.Code = 0;
  213. result.Msg = "成功!";
  214. result.Data = rateView;
  215. return result;
  216. }
  217. else
  218. {
  219. var currencyModelPre = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodePer).FirstOrDefault();
  220. if (currencyModelPre == null)
  221. {
  222. result.Msg = "转换前币种未找到!";
  223. return result;
  224. }
  225. var rateModelPre = await GetSingleRateAsync(currencyModelPre.CurrencyCode);
  226. if (rateModelPre.Code != 0)
  227. {
  228. result.Msg = rateModelPre.Msg;
  229. return result;
  230. }
  231. if (string.IsNullOrEmpty(rateModelPre.Data.FSellPri))
  232. {
  233. result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelPre.CurrencyName, currencyModelPre.CurrencyCode);
  234. return result;
  235. }
  236. decimal moneyPre = (Convert.ToDecimal(rateModelPre.Data.FSellPri) / 100) * dto.Money; //fSellPri
  237. if (dto.CurrencyCodeSuf.ToUpper() == "CNY")
  238. {
  239. var rateView = new ExchangeRateView
  240. {
  241. CurrencyCodePre = dto.CurrencyCodePer,
  242. CurrencyNamePre = currencyModelPre.CurrencyName,
  243. MoneyPre = dto.Money,
  244. CurrencyCodeSuf = "CNY",
  245. CurrencyNameSuf = "人民币",
  246. MoneySuf = CommonFun.CutDecimalWithN(moneyPre, 4),
  247. UpdateTime = string.Format("{0} {1}", rateModelPre.Data.Date, rateModelPre.Data.Time)
  248. };
  249. result.Code = 0;
  250. result.Msg = "成功!";
  251. result.Data = rateView;
  252. }
  253. else
  254. {
  255. var currencyModelSuf = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodeSuf).FirstOrDefault();
  256. if (currencyModelSuf == null)
  257. {
  258. result.Msg = "转换后币种未找到!";
  259. return result;
  260. }
  261. var rateModelSuf = await GetSingleRateAsync(currencyModelSuf.CurrencyCode);
  262. if (rateModelSuf.Code != 0)
  263. {
  264. result.Msg = rateModelSuf.Msg;
  265. return result;
  266. }
  267. if (string.IsNullOrEmpty(rateModelSuf.Data.FSellPri))
  268. {
  269. result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelSuf.CurrencyName, currencyModelSuf.CurrencyCode);
  270. return result;
  271. }
  272. decimal moneySuf = Convert.ToDecimal(rateModelSuf.Data.FSellPri) / 100; //fSellPri
  273. decimal settlementMoney = moneyPre / moneySuf;
  274. var rateView = new ExchangeRateView
  275. {
  276. CurrencyCodePre = dto.CurrencyCodePer,
  277. CurrencyNamePre = currencyModelPre.CurrencyName,
  278. MoneyPre = dto.Money,
  279. CurrencyCodeSuf = dto.CurrencyCodeSuf,
  280. CurrencyNameSuf = currencyModelSuf.CurrencyName,
  281. MoneySuf = CommonFun.CutDecimalWithN(settlementMoney, 4),
  282. UpdateTime = string.Format("{0} {1}", rateModelSuf.Data.Date, rateModelSuf.Data.Time)
  283. };
  284. result.Code = 0;
  285. result.Msg = "成功!";
  286. result.Data = rateView;
  287. }
  288. }
  289. return result;
  290. }
  291. }
  292. }