Common.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. 
  2. namespace OASystem.API.OAMethodLib
  3. {
  4. public static class Common
  5. {
  6. public static string GetSignContent(Dictionary<string, string> sortedParams)
  7. {
  8. //字典排序,并用&进行拼接,例如,b=a,a=b,拼接后变成a=b&b=a
  9. StringBuilder content = new StringBuilder();
  10. //利用linq进行字典升序的排序
  11. var dicSort = from objDic in sortedParams orderby objDic.Key select objDic;
  12. foreach (KeyValuePair<string, string> kvp in dicSort)
  13. {
  14. string key = kvp.Key;
  15. string value = kvp.Value;
  16. if (null != key && null != value)
  17. {
  18. content.Append(key + "=" + value + "&");
  19. }
  20. }
  21. if (content.Length != 0)
  22. {
  23. content.Remove(content.Length - 1, 1);
  24. }
  25. return content.ToString();
  26. }
  27. public static string GetSign(Dictionary<string, string> sortedParams)
  28. {
  29. //排序拼接参数
  30. string signContent = GetSignContent(sortedParams);
  31. //加签
  32. string sign = GmUtil.generateSmSign(signContent);
  33. return sign;
  34. }
  35. public static bool VerifySign(Dictionary<string, string> sortedParams)
  36. {
  37. //获取返回的sign
  38. string returnSign = sortedParams["sign"];
  39. //删除返回的sign
  40. sortedParams.Remove("sign");
  41. //排序拼接参数
  42. string signContent = GetSignContent(sortedParams);
  43. //验签
  44. bool flag = GmUtil.verifySmSign(signContent, returnSign);
  45. return flag;
  46. }
  47. public static Dictionary<string, string> PostForEntity(string url, string param, Dictionary<string, string> dic = null)
  48. {
  49. HttpWebRequest request;//仅作展示,这个方法用于发送网络请求可能有性能问题
  50. request = (HttpWebRequest)WebRequest.Create(url);
  51. // 以POST的方式提交
  52. request.Method = "POST";
  53. // 以json的方式提交
  54. request.ContentType = "application/json;charset=UTF-8";
  55. // 请求头部
  56. if (dic != null && dic.Count != 0)
  57. {
  58. foreach (var item in dic)
  59. {
  60. request.Headers.Add(item.Key, item.Value);
  61. }
  62. }
  63. byte[] payload;
  64. // 请求参数
  65. payload = Encoding.UTF8.GetBytes(param);
  66. request.ContentLength = payload.Length;
  67. string strValue = "";
  68. try
  69. {
  70. Stream writer = request.GetRequestStream();
  71. writer.Write(payload, 0, payload.Length);
  72. writer.Close();
  73. HttpWebResponse response;
  74. response = (HttpWebResponse)request.GetResponse();
  75. Stream s;
  76. s = response.GetResponseStream();
  77. string StrDate = "";
  78. StreamReader Reader = new StreamReader(s, Encoding.UTF8);
  79. while ((StrDate = Reader.ReadLine()) != null)
  80. {
  81. strValue += StrDate;
  82. }
  83. }
  84. catch (Exception e)
  85. {
  86. Console.WriteLine("post请求报错:" + e.Message);
  87. return null;
  88. }
  89. //JavaScriptSerializer jss = new JavaScriptSerializer();
  90. return JsonConvert.DeserializeObject<Dictionary<string, string>>(strValue);
  91. }
  92. /// <summary>
  93. /// 返回网络时间 --北京时间
  94. /// </summary>
  95. /// <returns></returns>
  96. public static DateTime GetBeijingTime()
  97. {
  98. WebRequest request = null;
  99. WebResponse response = null;
  100. WebHeaderCollection headerCollection = null;
  101. string datetime = string.Empty;
  102. try
  103. {
  104. request = WebRequest.Create("https://www.baidu.com");
  105. request.Timeout = 3000;
  106. request.Credentials = CredentialCache.DefaultCredentials;
  107. response = request.GetResponse();
  108. headerCollection = response.Headers;
  109. foreach (var h in headerCollection.AllKeys)
  110. {
  111. if (h == "Date")
  112. {
  113. datetime = headerCollection[h];
  114. break;
  115. }
  116. }
  117. return Convert.ToDateTime(datetime);
  118. }
  119. catch (Exception)
  120. {
  121. return DateTime.Now;
  122. }
  123. finally
  124. {
  125. if (request != null)
  126. {
  127. request.Abort();
  128. }
  129. if (response != null)
  130. {
  131. response.Close();
  132. }
  133. if (headerCollection != null)
  134. {
  135. headerCollection.Clear();
  136. }
  137. }
  138. }
  139. #region Http请求封装
  140. public static Dictionary<string, string> GetHeader(Dictionary<string, string> sortedParams)
  141. {
  142. //long timestamp = ConvertDateTime(System.DateTime.Now) / 10000000;
  143. long timestamp = ConvertDateTime(GetBeijingTime()) / 10000000;
  144. // 组apiSign加密Map
  145. Dictionary<string, string> apiSign = new Dictionary<string, string>();
  146. apiSign.Add("appid", BaseConfig.APPID);
  147. apiSign.Add("secret", BaseConfig.APP_SECRET);
  148. apiSign.Add("sign", sortedParams["sign"]);
  149. apiSign.Add("timestamp", "" + timestamp);
  150. // MD5加密
  151. string MD5Content = GetSignContent(apiSign);
  152. string apiSignString = GetMD5(MD5Content, "UTF-8");
  153. // 组request头部Map
  154. Dictionary<string, string> apiHeader = new Dictionary<string, string>();
  155. apiHeader.Add("appid", BaseConfig.APPID);
  156. apiHeader.Add("timestamp", "" + timestamp);
  157. apiHeader.Add("apisign", apiSignString);
  158. return apiHeader;
  159. }
  160. private static long ConvertDateTime(DateTime time)
  161. {
  162. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
  163. return time.Ticks - startTime.Ticks;
  164. }
  165. public static string GetMD5(string data, string charset)
  166. {
  167. //MD5加密,同样的字符串在每次加密后的字符串是一样的
  168. byte[] bData = Encoding.GetEncoding(charset).GetBytes(data);
  169. MD5CryptoServiceProvider myMD5 = new MD5CryptoServiceProvider();
  170. bData = myMD5.ComputeHash(bData);
  171. StringBuilder sBuilder = new StringBuilder();
  172. for (int i = 0; i < bData.Length; i++)
  173. {
  174. //十六进制转成小写的英文字符
  175. sBuilder.Append(bData[i].ToString("x2"));
  176. }
  177. return sBuilder.ToString();
  178. }
  179. #endregion
  180. #region 二维码图片处理
  181. /// <summary>
  182. /// 调用此函数后使此两种图片合并,类似相册,有个
  183. /// 背景图,中间贴自己的目标图片
  184. /// </summary>
  185. /// <param name="imgBack">粘贴的源图片</param>
  186. /// <param name="destImg">粘贴的目标图片</param>
  187. public static Image CombinImage(Image imgBack, string destImg)
  188. {
  189. Image img = Image.FromFile(destImg); //照片图片
  190. if (img.Height != 65 || img.Width != 65)
  191. {
  192. img = KiResizeImage(img, 65, 65, 0);
  193. }
  194. Graphics g = Graphics.FromImage(imgBack);
  195. g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
  196. //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框
  197. //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
  198. g.DrawImage(img, imgBack.Width / 2 - img.Width / 2, imgBack.Width / 2 - img.Width / 2, img.Width, img.Height);
  199. GC.Collect();
  200. return imgBack;
  201. }
  202. /// <summary>
  203. /// Resize图片
  204. /// </summary>
  205. /// <param name="bmp">原始Bitmap</param>
  206. /// <param name="newW">新的宽度</param>
  207. /// <param name="newH">新的高度</param>
  208. /// <param name="Mode">保留着,暂时未用</param>
  209. /// <returns>处理以后的图片</returns>
  210. public static Image KiResizeImage(Image bmp, int newW, int newH, int Mode)
  211. {
  212. try
  213. {
  214. Image b = new Bitmap(newW, newH);
  215. Graphics g = Graphics.FromImage(b);
  216. // 插值算法的质量
  217. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  218. g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
  219. g.Dispose();
  220. return b;
  221. }
  222. catch
  223. {
  224. return null;
  225. }
  226. }
  227. //public bool IsReusable
  228. //{
  229. // get
  230. // {
  231. // return false;
  232. // }
  233. //}
  234. #endregion
  235. #region 通知参数处理
  236. public static Dictionary<string, string> str2Map(string str)
  237. {
  238. Dictionary<string, string> result = new Dictionary<string, string>();
  239. string[] results = str.Split('&');
  240. if (results != null && results.Length > 0)
  241. {
  242. for (int var = 0; var < results.Length; ++var)
  243. {
  244. string pair = results[var];
  245. string[] kv = pair.Split('=');
  246. if (kv != null && kv.Length == 2)
  247. {
  248. result.Add(kv[0], kv[1]);
  249. }
  250. }
  251. }
  252. return result;
  253. }
  254. public static string decode(string str)
  255. {
  256. string result = null;
  257. if (str != null)
  258. {
  259. result = Uri.UnescapeDataString(str);
  260. }
  261. return result;
  262. }
  263. public static string NotifySign(string requestJsonStr)
  264. {
  265. return "";
  266. }
  267. #endregion
  268. }
  269. }