You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

250 lines
10 KiB

2 years ago
  1. using EasyBL.WebApi.Common;
  2. using EasyBL.WebApi.Message;
  3. using EasyBL.WebApi.Models;
  4. using Entity.Sugar;
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Text;
  12. using System.Web;
  13. namespace EasyBL.WebApi.Helper
  14. {
  15. public class WebApiHelper
  16. {
  17. /// <summary>
  18. /// Post请求
  19. /// </summary>
  20. /// <param name="url"></param>
  21. /// <param name="data"></param>
  22. /// <param name="orgId">todo: describe orgId parameter on Post</param>
  23. /// <param name="userId">todo: describe userId parameter on Post</param>
  24. /// <param name="passWd">todo: describe passWd parameter on Post</param>
  25. /// <typeparam name="T"></typeparam>
  26. /// <returns></returns>
  27. public static T Post<T>(string url, string data, string orgId, string userId, string passWd)
  28. {
  29. var bytes = Encoding.UTF8.GetBytes(data);
  30. var request = (HttpWebRequest)WebRequest.Create(url);
  31. var timeStamp = GetTimeStamp();
  32. var nonce = GetRandom();
  33. //加入头信息
  34. request.Headers.Add("orgid", orgId); //当前请求組織Id
  35. request.Headers.Add("userid", userId); //当前请求用户StaffId
  36. request.Headers.Add("passwd", passWd); //当前请求用户StaffId
  37. request.Headers.Add("timestamp", timeStamp); //发起请求时的时间戳(单位:毫秒)
  38. request.Headers.Add(nameof(nonce), nonce); //发起请求时的时间戳(单位:毫秒)
  39. request.Headers.Add("signature", GetSignature(timeStamp, nonce, orgId, userId, passWd)); //当前请求内容的数字签名
  40. //写数据
  41. request.Method = "POST";
  42. request.ContentLength = bytes.Length;
  43. request.ContentType = "application/x-www-form-urlencoded";
  44. request.Headers.Set("Pragma", "no-cache");
  45. request.Headers.Set("Content-Encoding", "gzip,deflate");
  46. request.AutomaticDecompression = DecompressionMethods.Deflate;
  47. var reqstream = request.GetRequestStream();
  48. reqstream.Write(bytes, 0, bytes.Length);
  49. //读数据
  50. request.Timeout = 300000;
  51. var response = (HttpWebResponse)request.GetResponse();
  52. var streamReceive = response.GetResponseStream();
  53. using (var streamReader = new StreamReader(streamReceive, Encoding.UTF8))
  54. {
  55. var strResult = streamReader.ReadToEnd();
  56. //关闭流
  57. reqstream.Close();
  58. streamReader.Close();
  59. streamReceive.Close();
  60. request.Abort();
  61. response.Close();
  62. return JsonConvert.DeserializeObject<T>(strResult);
  63. }
  64. }
  65. /// <summary>
  66. /// Get请求
  67. /// </summary>
  68. /// <param name="webApi"></param>
  69. /// <param name="queryStr"></param>
  70. /// <param name="query">todo: describe query parameter on Get</param>
  71. /// <param name="orgId">todo: describe orgId parameter on Get</param>
  72. /// <param name="userId">todo: describe userId parameter on Get</param>
  73. /// <param name="passWd">todo: describe passWd parameter on Get</param>
  74. /// <param name="sign">todo: describe sign parameter on Get</param>
  75. /// <typeparam name="T"></typeparam>
  76. /// <returns></returns>
  77. public static T Get<T>(string webApi, string queryStr, string orgId, string userId, string passWd, bool sign = true)
  78. {
  79. var request = (HttpWebRequest)WebRequest.Create(webApi + "?" + queryStr);
  80. var timeStamp = GetTimeStamp();
  81. var nonce = GetRandom();
  82. //加入头信息
  83. request.Headers.Add("orgid", orgId); //当前请求組織Id
  84. request.Headers.Add("userid", userId); //当前请求用户Id
  85. request.Headers.Add("passwd", passWd); //当前请求用户密碼
  86. request.Headers.Add("timestamp", timeStamp); //发起请求时的时间戳(单位:毫秒)
  87. request.Headers.Add(nameof(nonce), nonce); //发起请求时的时间戳(单位:毫秒)
  88. if (sign)
  89. request.Headers.Add("signature", GetSignature(timeStamp, nonce, orgId, userId, passWd)); //当前请求内容的数字签名
  90. request.Method = "GET";
  91. request.ContentType = "application/json";
  92. request.Timeout = 90000;
  93. request.Headers.Set("Pragma", "no-cache");
  94. request.Headers.Set("Content-Encoding", "gzip,deflate");
  95. request.AutomaticDecompression = DecompressionMethods.Deflate;
  96. var response = (HttpWebResponse)request.GetResponse();
  97. var streamReceive = response.GetResponseStream();
  98. using (var streamReader = new StreamReader(streamReceive, Encoding.UTF8))
  99. {
  100. var strResult = streamReader.ReadToEnd();
  101. streamReader.Close();
  102. streamReceive.Close();
  103. request.Abort();
  104. response.Close();
  105. return JsonConvert.DeserializeObject<T>(strResult);
  106. }
  107. }
  108. /// <summary>
  109. /// Base64編碼參數
  110. /// </summary>
  111. /// <param name="rm">todo: describe rm parameter on Base64</param>
  112. /// <returns></returns>
  113. public static string Base64(RequestMessage rm)
  114. {
  115. var pm = HttpUtility.UrlEncode(JsonConvert.SerializeObject(rm));
  116. var bytes = ASCIIEncoding.ASCII.GetBytes(pm);
  117. return "=" + Convert.ToBase64String(bytes);
  118. }
  119. /// <summary>
  120. /// 获取token
  121. /// </summary>
  122. /// <param name="orgId"></param>
  123. /// <param name="userId"></param>
  124. /// <param name="passWd"></param>
  125. /// <returns></returns>
  126. public static TokenResult GetSignToken(string orgId, string userId, string passWd)
  127. {
  128. var tokenApi = WebSettingsConfig.TokenApi;
  129. var parames = new Dictionary<string, string>
  130. {
  131. { nameof(orgId), orgId },
  132. { nameof(userId), userId },
  133. { "pasWd", passWd }
  134. };
  135. var parameters = GetQueryString(parames);
  136. var token = WebApiHelper.Get<TokenResult>(tokenApi, parameters.Item2, orgId, userId, passWd, false);
  137. return token;
  138. }
  139. /// <summary>
  140. /// 计算签名
  141. /// </summary>
  142. /// <param name="timeStamp"></param>
  143. /// <param name="nonce"></param>
  144. /// <param name="orgId"></param>
  145. /// <param name="userId"></param>
  146. /// <param name="passWd">todo: describe passWd parameter on GetSignature</param>
  147. /// <returns></returns>
  148. private static string GetSignature(string timeStamp, string nonce, string orgId, string userId, string passWd)
  149. {
  150. TicketAuth token = null;
  151. var resultMsg = GetSignToken(orgId, userId, passWd);
  152. if (resultMsg != null)
  153. {
  154. if (resultMsg.StatusCode == (int)StatusCodeEnum.Success)
  155. {
  156. token = resultMsg.Result;
  157. }
  158. else
  159. {
  160. throw new Exception(resultMsg.Data.ToString());
  161. }
  162. }
  163. else
  164. {
  165. throw new Exception("token为null,組織帳號:" + orgId + "帳號:" + userId + "密碼:" + passWd);
  166. }
  167. var hash = System.Security.Cryptography.MD5.Create();
  168. //拼接签名数据
  169. var signStr = token.Token + timeStamp + nonce;
  170. //将字符串中字符按升序排序
  171. var sortStr = string.Concat(signStr.OrderBy(c => c));
  172. var bytes = Encoding.UTF8.GetBytes(sortStr);
  173. //使用MD5加密
  174. var md5Val = hash.ComputeHash(bytes);
  175. //把二进制转化为大写的十六进制
  176. var result = new StringBuilder();
  177. foreach (var c in md5Val)
  178. {
  179. result.Append(c.ToString("X2"));
  180. }
  181. return result.ToString().ToUpper();
  182. }
  183. /// <summary>
  184. /// 获取时间戳
  185. /// </summary>
  186. /// <returns></returns>
  187. public static string GetTimeStamp()
  188. {
  189. var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  190. return Convert.ToInt64(ts.TotalMilliseconds).ToString();
  191. }
  192. /// <summary>
  193. /// 获取随机数
  194. /// </summary>
  195. /// <returns></returns>
  196. public static string GetRandom()
  197. {
  198. var rd = new Random(DateTime.Now.Millisecond);
  199. var i = rd.Next(0, int.MaxValue);
  200. return i.ToString();
  201. }
  202. /// <summary>
  203. /// 拼接get参数
  204. /// </summary>
  205. /// <param name="parames"></param>
  206. /// <returns></returns>
  207. public static Tuple<string, string> GetQueryString(Dictionary<string, string> parames)
  208. {
  209. // 第一步:把字典按Key的字母顺序排序
  210. IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parames);
  211. var dem = sortedParams.GetEnumerator();
  212. // 第二步:把所有参数名和参数值串在一起
  213. var query = new StringBuilder(""); //签名字符串
  214. var queryStr = new StringBuilder(""); //url参数
  215. if (parames == null || parames.Count == 0)
  216. return new Tuple<string, string>("", "");
  217. while (dem.MoveNext())
  218. {
  219. var key = dem.Current.Key;
  220. var value = dem.Current.Value;
  221. if (!string.IsNullOrEmpty(key))
  222. {
  223. query.Append(key).Append(value);
  224. queryStr.Append("&").Append(key).Append("=").Append(value);
  225. }
  226. }
  227. return new Tuple<string, string>(query.ToString(), queryStr.ToString().Substring(1, queryStr.Length - 1));
  228. }
  229. }
  230. }