JuHeApiService.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. using OASystem.Domain.Dtos.SmallFun;
  2. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  3. using OASystem.Domain.ViewModels.SmallFun;
  4. using System.Text.Json;
  5. namespace OASystem.API.OAMethodLib.JuHeAPI
  6. {
  7. /// <summary>
  8. /// 聚合Api 服务
  9. /// </summary>
  10. public class JuHeApiService : IJuHeApiService
  11. {
  12. private readonly HttpClient _httpClient;
  13. private readonly HttpClient _httpClientTranslate;
  14. private readonly string _appKey = "0f5429e9fbb8637c0ff3f14bbb42c732"; //配置您申请的appkey
  15. private readonly string _appkey_textTranslate = "59db9edbac297e30695973aa1d856391"; //文本翻译 appkey
  16. /// <summary>
  17. /// 初始化
  18. /// </summary>
  19. /// <param name="clientFactory"></param>
  20. public JuHeApiService(IHttpClientFactory clientFactory)
  21. {
  22. _httpClient = clientFactory.CreateClient("PublicJuHeApi");
  23. _httpClientTranslate = clientFactory.CreateClient("PublicJuHeTranslateApi");
  24. }
  25. #region 汇率
  26. /// <summary>
  27. /// 获取汇率
  28. /// </summary>
  29. /// <returns></returns>
  30. public async Task<JuHeAPIResult> GetExchangeRateAsync()
  31. {
  32. var result = new JuHeAPIResult() { Resultcode = "-2", Reason = "未知错误" };
  33. string rateDataString = await RedisRepository.RedisFactory
  34. .CreateRedisRepository()
  35. .StringGetAsync<string>("JuHeApiExchangeRate");//string 取
  36. if (string.IsNullOrEmpty(rateDataString))
  37. {
  38. #region 请求接口并存入缓存
  39. string url = string.Format("/finance/exchange/rmbquot");
  40. try
  41. {
  42. var exchangeReq = await _httpClient.PostAsync(url,
  43. new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
  44. {
  45. new KeyValuePair<string, string>("key",_appKey),//你申请的key
  46. new KeyValuePair<string, string>("type","0"), //两种格式(0或者1,默认为0)
  47. new KeyValuePair<string, string>("bank","3") //(0:工商银行,1:招商银行,2:建设银行,3:中国银行,
  48. //4:交通银行,5:农业银行,默认为:0)
  49. }));
  50. if (exchangeReq.IsSuccessStatusCode)
  51. {
  52. var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
  53. result = System.Text.Json.JsonSerializer.Deserialize<JuHeAPIResult>(stringResponse,
  54. new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
  55. if (result.Resultcode == "200")
  56. {
  57. List<ExchangeRateModel> rateList = new List<ExchangeRateModel>();
  58. #region 处理数据类型
  59. JArray jar = JArray.Parse(result.Result.ToJson());
  60. for (int i = 0; i < jar.Count; i++)
  61. {
  62. JObject j = JObject.Parse(jar[i].ToString());
  63. for (int x = 1; x < j.Count + 1; x++)
  64. {
  65. string rateName = "data" + x;
  66. string rateDataStr = j[rateName].ToString();
  67. if (!string.IsNullOrEmpty(rateDataStr))
  68. {
  69. ExchangeRateModel exchangeRate = JsonConvert.DeserializeObject<ExchangeRateModel>(rateDataStr);
  70. exchangeRate.FBuyPri = HandleMinusValue(exchangeRate.FBuyPri);
  71. exchangeRate.FSellPri = HandleMinusValue(exchangeRate.FSellPri);
  72. exchangeRate.MBuyPri = HandleMinusValue(exchangeRate.MBuyPri);
  73. exchangeRate.MSellPri = HandleMinusValue(exchangeRate.MSellPri);
  74. exchangeRate.BankConversionPri = HandleMinusValue(exchangeRate.BankConversionPri);
  75. rateList.Add(exchangeRate);
  76. }
  77. }
  78. }
  79. #endregion
  80. TimeSpan ts = DateTime.Now.AddMinutes(120) - DateTime.Now; //设置redis 过期时间 120分钟
  81. await RedisRepository
  82. .RedisFactory
  83. .CreateRedisRepository()
  84. .StringSetAsync<string>("JuHeApiExchangeRate", rateList.ToJson(), ts);//string 存
  85. result.Result = rateList;
  86. }
  87. else
  88. {
  89. result.Reason = string.Format("聚合APIError[Error_Code:{0} Resultcode:{1} Msg:{2}]",
  90. result.Error_code, result.Resultcode, result.Result);
  91. }
  92. }
  93. else
  94. {
  95. result.Reason = "汇率接口请求失败!";
  96. }
  97. }
  98. catch (Exception ex)
  99. {
  100. result.Reason = ex.Message;
  101. }
  102. #endregion
  103. }
  104. else
  105. {
  106. result.Resultcode = "200";
  107. result.Result = JsonConvert.DeserializeObject<List<ExchangeRateModel>>(rateDataString);
  108. }
  109. return result;
  110. }
  111. /// <summary>
  112. /// 处理金额带“-”的币种汇率信息
  113. /// </summary>
  114. /// <param name="input"></param>
  115. /// <returns></returns>
  116. private string HandleMinusValue(string? input)
  117. {
  118. return string.IsNullOrEmpty(input) || input.Contains("-") ? "1.00" : input;
  119. }
  120. /// <summary>
  121. /// 获取汇率 Single
  122. /// </summary>
  123. /// <param name="currencyCode">币种code</param>
  124. /// <returns></returns>
  125. public async Task<Result> GetSingleRateAsync(string currencyCode)
  126. {
  127. var result = new Result();
  128. if (currencyCode.ToUpper() == "CNY")
  129. {
  130. return result;
  131. }
  132. var resultData = await GetExchangeRateAsync();
  133. var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
  134. var currencyModel = rateCurrencyData.Where(a => a.CurrencyCode == currencyCode).FirstOrDefault();
  135. if (currencyModel != null)
  136. {
  137. if (resultData.Resultcode == "200")
  138. {
  139. if (resultData.Result != null)
  140. {
  141. result.Code = 0;
  142. result.Data = ((List<ExchangeRateModel>)resultData.Result).Where(a => a.Name == currencyModel.CurrencyName).FirstOrDefault();
  143. }
  144. }
  145. else
  146. {
  147. result.Msg = resultData.Reason;
  148. }
  149. }
  150. return result;
  151. }
  152. /// <summary>
  153. /// 获取汇率 Single
  154. /// </summary>
  155. /// <param name="currencyCodes">币种codes</param>
  156. /// <returns></returns>
  157. public async Task<List<ExchangeRateModel>> PostItemRateAsync(string[] currencyCodes)
  158. {
  159. List<ExchangeRateModel> result = new List<ExchangeRateModel>();
  160. //if (currencyCodes.Length <= 0)
  161. //{
  162. // return result;
  163. //}
  164. var resultData = await GetExchangeRateAsync();
  165. var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
  166. var currencyModel = rateCurrencyData.WhereIF(currencyCodes.Length >0,a => currencyCodes.Any(b => a.CurrencyCode == b)).ToList();
  167. if (currencyModel.Count > 0)
  168. {
  169. if (resultData.Resultcode == "200")
  170. {
  171. if (resultData.Result != null)
  172. {
  173. var data = (List<ExchangeRateModel>)resultData.Result;
  174. foreach (var item in currencyModel)
  175. {
  176. ExchangeRateModel exchangeRateModel = data.Where(it => it.Name.Equals(item.CurrencyName)).FirstOrDefault();
  177. if (exchangeRateModel != null)
  178. {
  179. result.Add(exchangeRateModel);
  180. }
  181. }
  182. //result = ((List<ExchangeRateModel>)resultData.Result).Where(a => a.Name == currencyModel.CurrencyName).ToList();
  183. }
  184. }
  185. }
  186. return result;
  187. }
  188. /// <summary>
  189. /// 获取汇率转换结果
  190. /// </summary>
  191. /// <returns></returns>
  192. public async Task<Result> GetExchangeRateAsync(ExchangeRateDto dto)
  193. {
  194. var result = new Result() { Code = -2, Msg = "未知错误" };
  195. var rateCurrencyData = AppSettingsHelper.Get<RateCurrencyModel>("RateCurrency");
  196. if (dto.CurrencyCodePer.ToUpper() == "CNY")
  197. {
  198. var currencyModelSuf = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodeSuf).FirstOrDefault();
  199. if (currencyModelSuf == null)
  200. {
  201. result.Msg = "转换后币种未找到!";
  202. return result;
  203. }
  204. var rateModelSuf = await GetSingleRateAsync(currencyModelSuf.CurrencyCode);
  205. if (rateModelSuf.Code != 0)
  206. {
  207. result.Msg = rateModelSuf.Msg;
  208. return result;
  209. }
  210. if (string.IsNullOrEmpty(rateModelSuf.Data.FSellPri))
  211. {
  212. result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelSuf.CurrencyName, currencyModelSuf.CurrencyCode);
  213. return result;
  214. }
  215. decimal moneySuf = Convert.ToDecimal(rateModelSuf.Data.FSellPri) / 100; //fSellPri
  216. decimal settlementMoney = dto.Money / moneySuf;
  217. var rateView = new ExchangeRateView
  218. {
  219. CurrencyCodePre = dto.CurrencyCodePer,
  220. CurrencyNamePre = "人民币",
  221. MoneyPre = dto.Money,
  222. CurrencyCodeSuf = dto.CurrencyCodeSuf,
  223. CurrencyNameSuf = currencyModelSuf.CurrencyName,
  224. MoneySuf = CommonFun.CutDecimalWithN(settlementMoney, 4),
  225. UpdateTime = string.Format("{0} {1}", rateModelSuf.Data.Date, rateModelSuf.Data.Time)
  226. };
  227. result.Code = 0;
  228. result.Msg = "成功!";
  229. result.Data = rateView;
  230. return result;
  231. }
  232. else
  233. {
  234. var currencyModelPre = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodePer).FirstOrDefault();
  235. if (currencyModelPre == null)
  236. {
  237. result.Msg = "转换前币种未找到!";
  238. return result;
  239. }
  240. var rateModelPre = await GetSingleRateAsync(currencyModelPre.CurrencyCode);
  241. if (rateModelPre.Code != 0)
  242. {
  243. result.Msg = rateModelPre.Msg;
  244. return result;
  245. }
  246. if (string.IsNullOrEmpty(rateModelPre.Data.FSellPri))
  247. {
  248. result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelPre.CurrencyName, currencyModelPre.CurrencyCode);
  249. return result;
  250. }
  251. decimal moneyPre = (Convert.ToDecimal(rateModelPre.Data.FSellPri) / 100) * dto.Money; //fSellPri
  252. if (dto.CurrencyCodeSuf.ToUpper() == "CNY")
  253. {
  254. var rateView = new ExchangeRateView
  255. {
  256. CurrencyCodePre = dto.CurrencyCodePer,
  257. CurrencyNamePre = currencyModelPre.CurrencyName,
  258. MoneyPre = dto.Money,
  259. CurrencyCodeSuf = "CNY",
  260. CurrencyNameSuf = "人民币",
  261. MoneySuf = CommonFun.CutDecimalWithN(moneyPre, 4),
  262. UpdateTime = string.Format("{0} {1}", rateModelPre.Data.Date, rateModelPre.Data.Time)
  263. };
  264. result.Code = 0;
  265. result.Msg = "成功!";
  266. result.Data = rateView;
  267. }
  268. else
  269. {
  270. var currencyModelSuf = rateCurrencyData.Where(a => a.CurrencyCode == dto.CurrencyCodeSuf).FirstOrDefault();
  271. if (currencyModelSuf == null)
  272. {
  273. result.Msg = "转换后币种未找到!";
  274. return result;
  275. }
  276. var rateModelSuf = await GetSingleRateAsync(currencyModelSuf.CurrencyCode);
  277. if (rateModelSuf.Code != 0)
  278. {
  279. result.Msg = rateModelSuf.Msg;
  280. return result;
  281. }
  282. if (string.IsNullOrEmpty(rateModelSuf.Data.FSellPri))
  283. {
  284. result.Msg = string.Format("{0}({1})暂无汇率!", currencyModelSuf.CurrencyName, currencyModelSuf.CurrencyCode);
  285. return result;
  286. }
  287. decimal moneySuf = Convert.ToDecimal(rateModelSuf.Data.FSellPri) / 100; //fSellPri
  288. decimal settlementMoney = moneyPre / moneySuf;
  289. var rateView = new ExchangeRateView
  290. {
  291. CurrencyCodePre = dto.CurrencyCodePer,
  292. CurrencyNamePre = currencyModelPre.CurrencyName,
  293. MoneyPre = dto.Money,
  294. CurrencyCodeSuf = dto.CurrencyCodeSuf,
  295. CurrencyNameSuf = currencyModelSuf.CurrencyName,
  296. MoneySuf = CommonFun.CutDecimalWithN(settlementMoney, 4),
  297. UpdateTime = string.Format("{0} {1}", rateModelSuf.Data.Date, rateModelSuf.Data.Time)
  298. };
  299. result.Code = 0;
  300. result.Msg = "成功!";
  301. result.Data = rateView;
  302. }
  303. }
  304. return result;
  305. }
  306. #endregion
  307. #region 文本翻译
  308. /// <summary>
  309. /// 文本翻译
  310. /// </summary>
  311. /// <param name="source">原文,数据类型为字符串,也可为数组(元素必须为字符串类型);每次请求的字符串长度之和尽量不要超过 </param>
  312. /// <param name="trans_type">翻译方向:en2zh(英文-中文),zh2en(中文-英文),ja2zh(日文-中文),zh2ja(中文-日文),ko2zh(韩文-中文),zh2ko(中文-韩文)</param>
  313. /// <returns></returns>
  314. public async Task<string> GetTextTranslateAsync(string source, string trans_type = "zh2en")
  315. {
  316. string res = "";
  317. var result = new JuHeAPIResult() { Resultcode = "10020", Reason = "接口维护" };
  318. #region 请求接口
  319. string url = string.Format($"/translate/query");
  320. var exchangeReq = await _httpClientTranslate
  321. .PostAsync(url,
  322. new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
  323. {
  324. new KeyValuePair<string, string>("key",_appkey_textTranslate),//你申请的key
  325. new KeyValuePair<string, string>("source",source),
  326. new KeyValuePair<string, string>("trans_type",trans_type)
  327. }));
  328. if (exchangeReq.IsSuccessStatusCode)
  329. {
  330. var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
  331. JuHeTransResult result1 = System.Text.Json.JsonSerializer.Deserialize<JuHeTransResult>(stringResponse,
  332. new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
  333. if (result1.error_code == 0)
  334. {
  335. res = result1.result.data.res;
  336. }
  337. else
  338. {
  339. res = string.Format("聚合APIError[Error_Code:{0} Resultcode:{1} Msg:{2}]",
  340. result1.error_code, result1.reason, result1.result);
  341. }
  342. }
  343. else
  344. {
  345. result.Reason = "汇率接口请求失败!";
  346. }
  347. #endregion
  348. return res;
  349. }
  350. #endregion
  351. #region 洲 当前时间
  352. /// <summary>
  353. /// 获取全球当前时间
  354. /// </summary>
  355. /// <param name="continent">
  356. /// 洲际:非洲、美洲、南极洲、北极、亚洲、大西洋、 欧洲、太平洋
  357. /// </param>
  358. /// <returns></returns>
  359. public async Task<JuHeAPIResult> GetContinentTimezoneAsync(string continent)
  360. {
  361. var continentEn = string.Empty;
  362. if (string.IsNullOrEmpty(continent)) return new JuHeAPIResult(-1, "请输入州");
  363. if (continent.Equals("非洲")) continent = $"africa";
  364. else if (continent.Equals("非洲")) continent = $"africa";
  365. else if (continent.Equals("美洲")) continent = $"america";
  366. else if (continent.Equals("南极洲")) continent = $"antarctica";
  367. else if (continent.Equals("北极")) continent = $"arctic";
  368. else if (continent.Equals("亚洲")) continent = $"asia";
  369. else if (continent.Equals("大西洋")) continent = $"atlantic";
  370. else if (continent.Equals("欧洲")) continent = $"europe";
  371. else if (continent.Equals("太平洋")) continent = $"pacific";
  372. else return new JuHeAPIResult(-1, "请输入正确的州");
  373. #region 请求接口
  374. string url = string.Format($"/fapig/timezone/show");
  375. var exchangeReq = await _httpClientTranslate.PostAsync(url,
  376. new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
  377. {
  378. //new KeyValuePair<string, string>("key",_appkey_textTranslate),//你申请的key
  379. new KeyValuePair<string, string>("key","f3d6b2272d46e0ca9d1c9aca38d8a92c"),//你申请的key
  380. new KeyValuePair<string, string>("c",continent)
  381. }));
  382. if (exchangeReq.IsSuccessStatusCode)
  383. {
  384. var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
  385. var result = System.Text.Json.JsonSerializer.Deserialize<JuHeAPIResult>(stringResponse,
  386. new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
  387. return result;
  388. }
  389. #endregion
  390. return new JuHeAPIResult(-1, "世界时间接口请求失败!");
  391. }
  392. #endregion
  393. }
  394. }