YouDaoApiTools.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  2. using System.Text.Json;
  3. namespace OASystem.API.OAMethodLib.YouDaoAPI
  4. {
  5. /// <summary>
  6. /// 有道API Tools
  7. /// </summary>
  8. public static class YouDaoApiTools
  9. {
  10. private static readonly HttpClient _httpClient = new HttpClient { BaseAddress = new Uri("https://openapi.youdao.com") };
  11. //private static readonly IHttpClientFactory _httpClientFactory;
  12. private static readonly string _appKey = "0fe3bc01e109ed36"; //应用ID
  13. private static readonly string _appSecret = "1f2x9TrqJfSBEJ8iH9GEFGgTyaYGjEry"; //应用密钥
  14. #region OCR 调用翻译
  15. public static async Task<string> GetOCR_ReTrans(string txt)
  16. {
  17. var data = await GetReTrans(txt);
  18. string str = "";
  19. if (data == null && data.Code != 0)
  20. str = txt;
  21. else
  22. str = data.Data;
  23. return str;
  24. }
  25. #endregion
  26. /// <summary>
  27. /// 有道翻译
  28. /// 默认 中=>英
  29. /// </summary>
  30. /// <param name="txt">待翻译的文本</param>
  31. /// <param name="from">源语言</param>
  32. /// <param name="to">目标语言</param>
  33. /// <returns></returns>
  34. public static async Task<Result> GetReTrans(string txt, string from = "zh-CHS", string to = "en")
  35. {
  36. var result = new Result();
  37. #region MyRegion
  38. if (string.IsNullOrEmpty(txt))
  39. {
  40. result.Msg = "待翻译文本为空!";
  41. return result;
  42. }
  43. #endregion
  44. string url = string.Format("/api");
  45. #region 请求参数处理
  46. string q = txt;
  47. //input的计算方式为:input=q前10个字符 + q长度 + q后10个字符(当q长度大于20)或 input=q字符串(当q长度小于等于20);
  48. string input = q.Length <= 20 ? q : q.Substring(0, 10) + q.Length + q.Substring(q.Length - 10, 10);
  49. string salt = DateTime.Now.Millisecond.ToString();
  50. string curtime = GetUTCTime(true).ToString(); //UTC秒时间戳
  51. //sign = sha256(应用ID + input + salt + curtime + 应用密钥);
  52. string signStr = string.Format("{0}{1}{2}{3}{4}", _appKey, input, salt, curtime, _appSecret);
  53. string sign = SHA256EncryptString(signStr);
  54. #endregion
  55. var reqData = new FormUrlEncodedContent(
  56. new List<KeyValuePair<string, string>>()
  57. {
  58. //new KeyValuePair<string, string>("q",System.Web.HttpUtility.UrlEncode(q, Encoding.UTF8)),//待翻译文本 必须是UTF-8编码
  59. new KeyValuePair<string, string>("q",q), //待翻译文本 必须是UTF-8编码
  60. new KeyValuePair<string, string>("from",from), //源语言
  61. new KeyValuePair<string, string>("to",to), //目标语言
  62. new KeyValuePair<string, string>("appKey",_appKey), //应用ID
  63. new KeyValuePair<string, string>("salt",salt), //UUID
  64. new KeyValuePair<string, string>("sign",sign), //签名
  65. new KeyValuePair<string, string>("signType","v3"), //签名类型
  66. new KeyValuePair<string, string>("curtime",curtime), //TUC 时间戳
  67. });
  68. var reTransReq = await _httpClient.PostAsync(url, reqData);
  69. if (reTransReq.IsSuccessStatusCode)
  70. {
  71. var strResponse = await reTransReq.Content.ReadAsStringAsync();
  72. var strResponse1 = System.Web.HttpUtility.UrlDecode(strResponse, System.Text.Encoding.UTF8);
  73. var trans = JsonConvert.DeserializeObject<dynamic>(strResponse1);
  74. string errorCode = trans["errorCode"].ToString();
  75. if (errorCode == "0")
  76. {
  77. result.Code = 0;
  78. var translation = JsonConvert.DeserializeObject<List<string>>(trans["translation"].ToString());
  79. result.Msg = string.Format(@"成功!");
  80. result.Data = translation[0];
  81. }
  82. else
  83. {
  84. result.Msg = string.Format(@"有道翻译API [Error:{0}]", errorCode);
  85. }
  86. }
  87. else
  88. {
  89. result.Msg = "接口请求失败!";
  90. }
  91. return result;
  92. }
  93. #region SHA256加密
  94. /// <summary>
  95. /// SHA256加密
  96. /// </summary>
  97. /// <param name="data"></param>
  98. /// <returns></returns>
  99. public static string SHA256EncryptString(string data)
  100. {
  101. byte[] bytes = Encoding.UTF8.GetBytes(data);
  102. byte[] hash = SHA256Managed.Create().ComputeHash(bytes);
  103. StringBuilder builder = new StringBuilder();
  104. for (int i = 0; i < hash.Length; i++)
  105. {
  106. builder.Append(hash[i].ToString("x2"));
  107. }
  108. return builder.ToString();
  109. }
  110. /// <summary>
  111. /// SHA256加密
  112. /// </summary>
  113. /// <param name="StrIn">待加密字符串</param>
  114. /// <returns>加密数组</returns>
  115. public static Byte[] SHA256EncryptByte(string StrIn)
  116. {
  117. var sha256 = new SHA256Managed();
  118. var Asc = new ASCIIEncoding();
  119. var tmpByte = Asc.GetBytes(StrIn);
  120. var EncryptBytes = sha256.ComputeHash(tmpByte);
  121. sha256.Clear();
  122. return EncryptBytes;
  123. }
  124. #endregion
  125. #region UTC时间戳
  126. /// <summary>
  127. /// 获取utc时间
  128. /// </summary>
  129. /// <param name="type">true 秒 flase 毫秒</param>
  130. /// <returns></returns>
  131. public static long GetUTCTime(bool type)
  132. {
  133. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  134. return type ? Convert.ToInt64(ts.TotalSeconds) : Convert.ToInt64(ts.TotalMilliseconds);
  135. }
  136. /// <summary>
  137. /// 将当前时间戳转换至Datetime
  138. /// </summary>
  139. /// <param name="timeStamp"></param>
  140. /// <returns></returns>
  141. public static DateTime ConvertUTCToDateTime(long timeStamp)
  142. {
  143. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
  144. DateTime dt = startTime.AddSeconds(timeStamp);
  145. return dt;
  146. }
  147. /// <summary>
  148. /// 把datetime转utc时间戳
  149. /// </summary>
  150. /// <param name="time"></param>
  151. /// <returns></returns>
  152. public static int ConvertDateTimeToUTC(DateTime time)
  153. {
  154. double intResult = 0;
  155. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  156. intResult = (time - startTime).TotalSeconds;
  157. return (int)intResult;
  158. }
  159. #endregion
  160. }
  161. }