Common.cs 11 KB

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