InvokeRestCenter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using Newtonsoft.Json.Linq;
  2. using PTMedicalInsurance.Common;
  3. using PTMedicalInsurance.Variables;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13. namespace PTMedicalInsurance.Helper
  14. {
  15. class InvokeRestCenter : IInvokeCenter
  16. {
  17. private static string GetRandomString(int length)
  18. {
  19. const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  20. //const string chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
  21. var random = new Random();
  22. return new string(Enumerable.Repeat(chars, length)
  23. .Select(s => s[random.Next(s.Length)]).ToArray());
  24. }
  25. private static long GetCurrentUnixSeconds()
  26. {
  27. DateTimeOffset utcNow = DateTimeOffset.UtcNow.AddHours(8);
  28. return (long)(utcNow.ToUniversalTime().DateTime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalSeconds;
  29. }
  30. private static string GetSHA256Str(string input)
  31. {
  32. using (SHA256 sha256Hash = SHA256.Create())
  33. {
  34. byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
  35. StringBuilder builder = new StringBuilder();
  36. foreach (byte b in bytes)
  37. {
  38. builder.Append(b.ToString("x2"));
  39. }
  40. return builder.ToString();
  41. }
  42. }
  43. public int Business(string inputData, ref string outputData, ref string pErrMsg)
  44. {
  45. outputData = "";
  46. pErrMsg = "";
  47. JObject joRtn = new JObject();
  48. try
  49. {
  50. if (Global.curEvt.funNo.Contains("CFYLJG"))
  51. {
  52. //Global.curEvt.URL = "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/" + Global.curEvt.funNo;
  53. //电子处方测试
  54. Global.inf.apiSecretKey = "4poYlzt2jteX1pT3tijh7BqyWH4Lp0zN";
  55. Global.inf.passid = "sztest_hosp";
  56. Global.curEvt.URL = "http://hosp-sz.gd.hsip.gov.cn/ebus/sztest_hosp/poc/hsa/hgs/" + Global.curEvt.funNo;
  57. }
  58. //创建一个HTTP请求
  59. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL);
  60. //Post请求方式
  61. request.Method = "POST";
  62. string nonce = Guid.NewGuid().ToString(); //非重复的随机字符串(十分钟内不能重复)
  63. string timestamp = TimeStamp.get10().ToString(); //当前时间戳(秒)
  64. //测试
  65. //string secretKey = "RhaDw4H0RUbWYyTxmRKM1eSeN0qyGLds";
  66. //string passid = "test_hosp";
  67. //正式
  68. //string secretKey = "4G9PvAy1xEkvgZJGZ0cNOacQZZYe2Bkg";
  69. //string passid = "dg_sc_yjyy";
  70. string secretKey = Global.inf.apiSecretKey;
  71. string passid = Global.inf.passid;
  72. //内容类型
  73. request.ContentType = "application/json";
  74. //签名
  75. string sTemp = timestamp + secretKey + nonce + timestamp;
  76. //Sha256 加密生成的签名 x-tif-signature = sha256(x-tif-timestamp + secretKey+ x-tif-nonce + xtif-timestamp)
  77. string signature = Encrypt.SHA256EncryptStr(sTemp);
  78. nonce = GetRandomString(32); // 随机数
  79. //timestamp = GetCurrentUnixSeconds().ToString();
  80. signature = GetSHA256Str($"{timestamp}{secretKey}{nonce}{timestamp}"); // 签名
  81. //Global.writeLog($"nonce:{nonce}\ntimestamp:{timestamp}\nsecretKey:{secretKey}\npassid:{passid}\nsignature:{signature}");
  82. //增加头部信息
  83. request.Headers.Add("x-tif-paasid", passid);
  84. request.Headers.Add("x-tif-timestamp", timestamp);
  85. request.Headers.Add("x-tif-signature", signature);
  86. request.Headers.Add("x-tif-nonce", nonce);
  87. //设置参数,并进行URL编码
  88. string paraUrlCoded = inputData;//System.Web.HttpUtility.UrlEncode(jsonParas);
  89. byte[] payload;
  90. //将Json字符串转化为字节
  91. payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
  92. //设置请求的ContentLength
  93. request.ContentLength = payload.Length;
  94. //发送请求,获得请求流
  95. Stream writer;
  96. writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
  97. //将请求参数写入流
  98. writer.Write(payload, 0, payload.Length);
  99. writer.Close();//关闭请求流
  100. HttpWebResponse response = null;
  101. try
  102. {
  103. //获得响应流
  104. response = (HttpWebResponse)request.GetResponse();
  105. }
  106. catch (WebException ex)
  107. {
  108. HttpWebResponse res = (HttpWebResponse)ex.Response;
  109. Stream myResponseStream = res.GetResponseStream();
  110. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
  111. string retString = myStreamReader.ReadToEnd();
  112. outputData = JsonHelper.setExceptionJson(-99, "异常返回", retString).ToString();
  113. return -1;
  114. }
  115. outputData = getResponseData(response);
  116. joRtn = JObject.Parse(outputData);//返回Json数据
  117. return 0;
  118. }
  119. catch (Exception ex)
  120. {
  121. joRtn.Add("infcode", -1);
  122. joRtn.Add("err_msg", "调用中心服务异常invokeCenterService(1):" + ex.Message);
  123. outputData = JsonHelper.toJsonString(joRtn);
  124. return -1;
  125. }
  126. }
  127. public int BusinessExt(string inputData, ref string outputData, ref string pErrMsg)
  128. {
  129. return this.Business(inputData, ref outputData, ref pErrMsg);
  130. }
  131. public int DownloadFile(string inputData, ref string outputData)
  132. {
  133. outputData = "";
  134. string error = string.Empty; int errorCode = 0;
  135. try
  136. {
  137. JObject jsonInParam = JObject.Parse(inputData);
  138. // 去除外wrapper层便于通用
  139. Utils.removeWrapper(jsonInParam);
  140. string fileName = (string)jsonInParam["input"]["fsDownloadIn"]["filename"];
  141. string filePath = Global.curEvt.path + "\\Download\\" + fileName;
  142. //如果不存在目录,则创建目录
  143. if (!Directory.Exists(Global.curEvt.path + "\\Download"))
  144. {
  145. //创建文件夹
  146. DirectoryInfo dirInfo = Directory.CreateDirectory(Global.curEvt.path + "\\Download");
  147. }
  148. if (File.Exists(filePath))
  149. {
  150. File.Delete(filePath);
  151. }
  152. FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
  153. //创建一个HTTP请求
  154. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL);
  155. //Post请求方式
  156. request.Method = "POST";
  157. string nonce = Guid.NewGuid().ToString(); //非重复的随机字符串(十分钟内不能重复)
  158. string timestamp = TimeStamp.get10().ToString(); //当前时间戳(秒)
  159. //测试
  160. //string secretKey = "RhaDw4H0RUbWYyTxmRKM1eSeN0qyGLds";
  161. //string passid = "test_hosp";
  162. //正式
  163. //string secretKey = "4G9PvAy1xEkvgZJGZ0cNOacQZZYe2Bkg";
  164. //string passid = "dg_sc_yjyy";
  165. string secretKey = Global.inf.apiSecretKey;
  166. string passid = Global.inf.passid;
  167. //内容类型
  168. request.ContentType = "application/json";
  169. //签名
  170. string sTemp = timestamp + secretKey + nonce + timestamp;
  171. //Sha256 加密生成的签名 x-tif-signature = sha256(x-tif-timestamp + secretKey+ x-tif-nonce + xtif-timestamp)
  172. string signature = Encrypt.SHA256EncryptStr(sTemp);
  173. Global.writeLog($"nonce:{nonce}\ntimestamp:{timestamp}\nsecretKey:{secretKey}\npassid:{passid}\nsignature:{signature}");
  174. //增加头部信息
  175. request.Headers.Add("x-tif-paasid", passid);
  176. request.Headers.Add("x-tif-timestamp", timestamp);
  177. request.Headers.Add("x-tif-signature", signature);
  178. request.Headers.Add("x-tif-nonce", nonce);
  179. //设置参数,并进行URL编码
  180. string paraUrlCoded = JsonHelper.toJsonString(jsonInParam);
  181. byte[] payload;
  182. //将Json字符串转化为字节
  183. payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
  184. //设置请求的ContentLength
  185. request.ContentLength = payload.Length;
  186. Stream writer;
  187. try
  188. {
  189. writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
  190. }
  191. catch (Exception)
  192. {
  193. writer = null;
  194. errorCode = -100;
  195. error = "连接服务器失败!";
  196. }
  197. //将请求参数写入流
  198. writer.Write(payload, 0, payload.Length);
  199. writer.Close();//关闭请求流
  200. // String strValue = "";//strValue为http响应所返回的字符流
  201. //发送请求并获取相应回应数据
  202. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  203. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  204. Stream responseStream = response.GetResponseStream();
  205. //创建本地文件写入流
  206. byte[] bArr = new byte[102400];
  207. int iTotalSize = 0;
  208. int size = responseStream.Read(bArr, 0, (int)bArr.Length);
  209. while (size > 0)
  210. {
  211. iTotalSize += size;
  212. fs.Write(bArr, 0, size);
  213. size = responseStream.Read(bArr, 0, (int)bArr.Length);
  214. }
  215. fs.Close();
  216. responseStream.Close();
  217. dynamic joReturn = new JObject();
  218. joReturn.errorCode = errorCode;
  219. joReturn.errorMessage = error;
  220. joReturn.filePath = filePath;
  221. outputData = joReturn.ToString();
  222. }
  223. catch (Exception ex)
  224. {
  225. errorCode = -100;
  226. error = ex.Message;
  227. dynamic joReturn = new JObject();
  228. joReturn.errorCode = errorCode;
  229. joReturn.errorMessage = error;
  230. outputData = joReturn.ToString();
  231. return -1;
  232. }
  233. finally
  234. {
  235. Global.writeLog("DownloadCenterFile" + "(" + Global.curEvt.URL + ")", inputData, outputData);
  236. }
  237. return 0;
  238. }
  239. public int Init(ref string pErrMsg)
  240. {
  241. return 0;
  242. }
  243. public int UploadFile(string inputData, ref string outputData, ref string pErrMsg)
  244. {
  245. throw new NotImplementedException();
  246. }
  247. private string getResponseData(HttpWebResponse response)
  248. {
  249. string data = "";
  250. if (response != null)
  251. {
  252. Stream s = response.GetResponseStream();
  253. StreamReader sRead = new StreamReader(s,Encoding.GetEncoding("UTF-8"));
  254. data = sRead.ReadToEnd();
  255. sRead.Close();
  256. response.Close();
  257. }
  258. return data;
  259. }
  260. }
  261. }