/****************************************************************************** * 文件名称: InvokeHelper.cs * 文件说明: 调用助手,调用方法的封装 * 当前版本: V1.0 * 创建日期: 2022-04-12 * * 2020-04-12: 增加 businessDLLInvoke 方法 * 2020-04-12: 增加 writeLog 方法 * 2020-04-14: 增加 businessDLLInvoke(重载) 方法 * 2020-04-14: 增加 irisServiceInvoke 方法 * 2022-05-16: 增加 invokeInsuService 方法 * 2022-05-16: 增加 invokeHISService 方法 ******************************************************************************/ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using PTMedicalInsurance.Variables; using PTMedicalInsurance.Common; namespace PTMedicalInsurance.Helper { class InvokeHelper { private string serviceURL; private string authorization; /// /// 封装业务DLL的调用,返回整型,带两ref出参 /// /// /// /// /// /// public int businessDLLInvoke(string methodName, string inParam, ref string outParam,ref string ErrorMessage) { try { DllInvoke dllInvoke = new DllInvoke(); string path = GlobalVariables.currentDirectory + "\\" + GlobalVariables.businessDllName; string[] str = new string[1]; str[0] = inParam; object o2 = DllInvoke.ManagedInvoke(path, GlobalVariables.businessDllNameSpace, "InsuBusiness", methodName, str); if (o2.ToString() == "") { ErrorMessage = "返回数据为空"; return -1; } JObject joRtn = JObject.Parse(o2.ToString()); if (joRtn["errorCode"].ToString() != "0") { ErrorMessage = joRtn["errorMessage"].ToString(); return -1; } else { outParam = o2.ToString(); return 0; } } catch (Exception ex) { ErrorMessage = "调用异常:" + ex.ToString(); return -1; } finally { writeLog(methodName,inParam,outParam); } } /// /// 封装业务DLL的调用,返回JSON对象 /// /// /// /// public JObject businessDLLInvoke(string methodName, string inParam) { string outParam = string.Empty; string path = ""; JObject joRtn = new JObject(); try { DllInvoke dllInvoke = new DllInvoke(); path = GlobalVariables.currentDirectory + "\\" + GlobalVariables.businessDllName; string[] str = new string[1]; str[0] = inParam; object o2 = DllInvoke.ManagedInvoke(path, GlobalVariables.businessDllNameSpace, "InsuBusiness", methodName, str); outParam = o2.ToString(); joRtn = JObject.Parse(outParam); return joRtn; } catch (Exception ex) { outParam = "businessDLLInvoke:原出参(" + outParam + ")\r\n ,异常:" + ex.Message; return JsonHelper.getIrisExceptionJson(-1, "businessDLLInvoke:" ,outParam); } finally { writeLog(methodName + "(" + path + ")", inParam, outParam); } } /// /// 调用壳DLL /// /// /// /// public JObject invokeShellDll(string methodName, string inParam) { string outParam = string.Empty; string path = ""; JObject joRtn = new JObject(); try { DllInvoke dllInvoke = new DllInvoke(); path = GlobalVariables.currentDirectory + "\\" + "PTMedInsuInterface.dll"; string[] str = new string[1]; str[0] = inParam; object o2 = DllInvoke.ManagedInvoke(path, "PTMedInsuInterface", "InsuBusiness", methodName, str); outParam = o2.ToString(); joRtn = JObject.Parse(outParam); return joRtn; } catch (Exception ex) { outParam = "invokeShellDll:原出参(" + outParam + ")\r\n ,异常:" + ex.Message; return JsonHelper.getIrisExceptionJson(-1, "invokeShellDll:", outParam); } finally { writeLog(methodName + "(" + path + ")", inParam, outParam); } } /// /// iris服务调用的封装 /// /// /// public JObject irisServiceInvoke(string data,string serviceName) { string rtn = "", url = ""; JObject joRtn = new JObject(); try { //先根据用户请求的uri构造请求地址 url = string.Format("{0}/{1}", GlobalVariables.irisServiceIP, GlobalVariables.irisServiceURL); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; //创建Web访问对象 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); //把用户传过来的数据转成“UTF-8”的字节流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); //添加头部信息 myRequest.Method = "POST"; myRequest.ContentLength = buf.Length; myRequest.ContentType = "application/json"; myRequest.Headers.Add("Authorization", GlobalVariables.irisServiceAuthorization); myRequest.MaximumAutomaticRedirections = 1; myRequest.AllowAutoRedirect = true; //发送请求 Stream stream = myRequest.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); //获取接口返回值 //通过Web访问对象获取响应内容 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //string rtn = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法 rtn = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); joRtn = JObject.Parse(rtn); return joRtn; } catch (Exception ex) { joRtn = JsonHelper.getIrisExceptionJson(-1, serviceName,rtn + "\r\n" + ex.Message); rtn = joRtn.ToString(); return joRtn; } finally { writeLog(serviceName+ url , data, rtn); } } /// /// iris服务调用的封装 /// /// /// public JObject invokeHISService(string data, string serviceDesc) { string rtn = "", url = ""; JObject joRtn = new JObject(); try { //先根据用户请求的uri构造请求地址 url = string.Format("{0}/{1}", GlobalVariables.hisIrisServiceIP, GlobalVariables.hisIrisServiceURL); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; //创建Web访问对象 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); //把用户传过来的数据转成“UTF-8”的字节流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); //添加头部信息 myRequest.Method = "POST"; myRequest.ContentLength = buf.Length; myRequest.ContentType = "application/json"; myRequest.Headers.Add("Authorization", GlobalVariables.hisIrisServiceAuthorization); myRequest.MaximumAutomaticRedirections = 1; myRequest.AllowAutoRedirect = true; //发送请求 Stream stream = myRequest.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); //获取接口返回值 //通过Web访问对象获取响应内容 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //string rtn = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法 rtn = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); joRtn = JObject.Parse(rtn); return joRtn; } catch (Exception ex) { joRtn = JsonHelper.getIrisExceptionJson(-1, serviceDesc, ex.Message); rtn = JsonConvert.SerializeObject(joRtn); return joRtn; } finally { GlobalVariables.writeLog(serviceDesc + "(" + url + ")", data, rtn); } } /// /// iris服务调用的封装 /// /// /// public JObject invokeInsuService(string data, string serviceDesc) { string rtn = "", url = ""; JObject joRtn = new JObject(); try { //先根据用户请求的uri构造请求地址 url = string.Format("{0}/{1}", GlobalVariables.insuIrisServiceIP, GlobalVariables.insuIrisServiceURL); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; //创建Web访问对象 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); //把用户传过来的数据转成“UTF-8”的字节流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); //添加头部信息 myRequest.Method = "POST"; myRequest.ContentLength = buf.Length; myRequest.ContentType = "application/json"; myRequest.Headers.Add("Authorization", GlobalVariables.insuIrisServiceAuthorization); myRequest.MaximumAutomaticRedirections = 1; myRequest.AllowAutoRedirect = true; //发送请求 Stream stream = myRequest.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); //获取接口返回值 //通过Web访问对象获取响应内容 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //string rtn = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法 rtn = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); joRtn = JObject.Parse(rtn); return joRtn; } catch (Exception ex) { joRtn = JsonHelper.getIrisExceptionJson(-1, serviceDesc, ex.Message); rtn = JsonConvert.SerializeObject(joRtn); return joRtn; } finally { GlobalVariables.writeLog(serviceDesc + "(" + url + ")", data, rtn); } } /// /// 一次交易的完整日志记录,用*****分割每次交易,简洁明了。 /// /// /// /// private void writeLog(string tradeName, string inParam, string outParam) { string logDir = GlobalVariables.currentDirectory + "\\Log", logName = DateTime.Now.ToString("yyyy-MM-dd") + "_Demo.Log"; string statrTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff"); if (!Directory.Exists(logDir)) { //创建文件夹 DirectoryInfo dirInfo = Directory.CreateDirectory(logDir); } if (!File.Exists(logDir + "\\" + logName)) { FileStream fs1 = File.Create(logDir + "\\" + logName); fs1.Close(); } FileStream fs = new FileStream(logDir + "\\" + logName, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); string content = "****************************交易开始(" + statrTime + ")****************************" + "\r\n"; content = content + "交易名称:" + tradeName + "\r\n"; content = content + "交易入参:" + inParam + "\r\n"; content = content + "交易出参:" + outParam + "\r\n"; content = content + "****************************交易结束(" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + ")****************************" + "\r\n"; sw.WriteLine(content); sw.Close(); fs.Close(); } /***************************************************************下载目录接口用*****************************************************************************/ /// /// iris服务调用的封装 /// /// /// public JObject invokeIrisService(string data, string serviceDesc) { string rtn = "", url = ""; JObject joRtn = new JObject(); try { //先根据用户请求的uri构造请求地址 url = serviceURL; ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; //创建Web访问对象 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); //把用户传过来的数据转成“UTF-8”的字节流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); //添加头部信息 myRequest.Method = "POST"; myRequest.ContentLength = buf.Length; myRequest.ContentType = "application/json"; myRequest.Headers.Add("Authorization", authorization); myRequest.MaximumAutomaticRedirections = 1; myRequest.AllowAutoRedirect = true; //发送请求 Stream stream = myRequest.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); //获取接口返回值 //通过Web访问对象获取响应内容 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //string rtn = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法 rtn = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); joRtn = JObject.Parse(rtn); return joRtn; } catch (Exception ex) { joRtn = JsonHelper.setExceptionJson(-1, serviceDesc, ex.Message); rtn = JsonConvert.SerializeObject(joRtn); return joRtn; } } /// /// HIS服务调用的封装 /// /// /// public JObject invokeHISService_T(string data, string serviceDesc) { JObject joRtn = new JObject(); try { //先根据用户请求的uri构造请求地址 serviceURL = string.Format("{0}/{1}", Global.hisConfig.ip, Global.hisConfig.url); authorization = Global.hisConfig.authorization; joRtn = invokeIrisService(data, serviceDesc); return joRtn; } catch (Exception ex) { joRtn = JsonHelper.setExceptionJson(-1, serviceDesc, ex.Message); return joRtn; } finally { Global.writeLog_Iris(serviceDesc + "(" + serviceURL + ")" + "Authorization:" + (authorization), JsonHelper.Compress(data), JsonHelper.Compress(joRtn)); } } /// /// 医保平台服务调用的封装 /// /// /// public JObject invokeInsuService_T(string data, string serviceDesc) { string rtn = ""; JObject joRtn = new JObject(); try { //先根据用户请求的uri构造请求地址 serviceURL = string.Format("{0}/{1}", Global.insuConfig.ip, Global.insuConfig.url); authorization = Global.insuConfig.authorization; joRtn = invokeIrisService(data, serviceDesc); rtn = JsonConvert.SerializeObject(joRtn); return joRtn; } catch (Exception ex) { joRtn = JsonHelper.setExceptionJson(-1, serviceDesc, ex.Message); rtn = JsonConvert.SerializeObject(joRtn); return joRtn; } finally { Global.writeLog_Iris(serviceDesc + "(" + serviceURL + ")" + "Authorization:" + (authorization), JsonHelper.Compress(data), rtn); } } private JObject invokeCenterService(string data) { string postContent = ""; JObject joRtn = new JObject(); try { //创建一个HTTP请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL); //Post请求方式 request.Method = "POST"; //内容类型 request.ContentType = "application/json"; String stamp = TimeStamp.get13().ToString(); string apiName = Global.curEvt.URL.Substring(Global.curEvt.URL.Length - 12); //南昌增加头部信息 string sTemp = "_api_access_key=" + Global.inf.AK + "&_api_name=" + apiName + "&_api_timestamp=" + stamp + "&_api_version=" + "1.0.0"; string signature = Encrypt.ToBase64hmac(sTemp, Global.inf.SK); //Global.writeLog(sTemp); //Global.writeLog(Global.inf.SK); //Global.writeLog(signature); request.Headers.Add("_api_version", "1.0.0"); request.Headers.Add("_api_timestamp", stamp); request.Headers.Add("_api_name", apiName); request.Headers.Add("_api_signature", signature); request.Headers.Add("_api_access_key", Global.inf.AK); //设置参数,并进行URL编码 string paraUrlCoded = data;//System.Web.HttpUtility.UrlEncode(jsonParas); byte[] payload; //将Json字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); //设置请求的ContentLength request.ContentLength = payload.Length; //发送请求,获得请求流 Stream writer; writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象 //将请求参数写入流 writer.Write(payload, 0, payload.Length); writer.Close();//关闭请求流 // String strValue = "";//strValue为http响应所返回的字符流 HttpWebResponse response; try { //获得响应流 response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = ex.Response as HttpWebResponse; return JsonHelper.setExceptionJson(-99, "centerServeiceInvok中获得响应流异常", ex.Message); } Stream s = response.GetResponseStream(); StreamReader sRead = new StreamReader(s); postContent = sRead.ReadToEnd(); sRead.Close(); joRtn = JObject.Parse(postContent);//返回Json数据 return joRtn; } catch (Exception ex) { postContent = "调用中心服务异常" + ex.Message; joRtn.Add("infcode", -1); joRtn.Add("err_msg", "invokeCenterService(1):" + ex.Message); return joRtn; } } public JObject invokeCenterService(string funNO, JObject data) { JObject joRtn = new JObject(); String outPar = ""; try { Global.curEvt.URL = Global.inf.centerURL + "/hsa-fsi-" + funNO; joRtn = invokeCenterService(data.ToString()); outPar = JsonHelper.Compress(joRtn); return joRtn; } catch (Exception ex) { joRtn.Add("infcode", -1); joRtn.Add("err_msg", "invokeCenterService(2):" + ex.Message); outPar = JsonHelper.Compress(joRtn); return joRtn; } finally { Global.writeLog(funNO + "(" + Global.curEvt.URL + ")", JsonHelper.Compress(data), joRtn.ToString()); this.saveCenterLog(JsonHelper.Compress(data), outPar); } } public JObject invokeCenterService(string funNO, string data) { JObject joRtn = new JObject(); String outPar = ""; try { Global.curEvt.URL = Global.inf.centerURL + "/hsa-fsi-" + funNO; joRtn = invokeCenterService(data); outPar = JsonHelper.Compress(joRtn); return joRtn; } catch (Exception ex) { joRtn.Add("infcode", -1); joRtn.Add("err_msg", "invokeCenterService(3):" + ex.Message); outPar = JsonHelper.Compress(joRtn); return joRtn; } finally { Global.writeLog(funNO + "(" + Global.curEvt.URL + ")", JsonHelper.Compress(data), outPar); this.saveCenterLog(data, outPar); } } public JObject DownloadCenterFile(string data) { string error = string.Empty; int errorCode = 0; string sRtn = ""; try { JObject jsonInParam = JObject.Parse(data); string fileName = (string)jsonInParam["input"]["fsDownloadIn"]["filename"]; string filePath = System.Environment.CurrentDirectory + "\\Download\\" + fileName; //如果不存在目录,则创建目录 if (!Directory.Exists(System.Environment.CurrentDirectory + "\\Download")) { //创建文件夹 DirectoryInfo dirInfo = Directory.CreateDirectory(System.Environment.CurrentDirectory + "\\Download"); } if (File.Exists(filePath)) { File.Delete(filePath); } FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); //创建一个HTTP请求 Global.curEvt.URL = Global.inf.centerURL + "/hsa-fsi-9102"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL); //Post请求方式 request.Method = "POST"; //内容类型 request.ContentType = "application/json"; String stamp = TimeStamp.get13().ToString(); string apiName = Global.curEvt.URL.Substring(Global.curEvt.URL.Length - 12); //南昌增加头部信息 string sTemp = "_api_access_key=" + Global.inf.AK + "&_api_name=" + apiName + "&_api_timestamp=" + stamp + "&_api_version=" + "1.0.0"; string signature = Encrypt.ToBase64hmac(sTemp, Global.inf.SK); //Global.writeLog(sTemp); //Global.writeLog(Global.inf.SK); //Global.writeLog(signature); request.Headers.Add("_api_version", "1.0.0"); request.Headers.Add("_api_timestamp", stamp); request.Headers.Add("_api_name", apiName); request.Headers.Add("_api_signature", signature); request.Headers.Add("_api_access_key", Global.inf.AK); //设置参数,并进行URL编码 string paraUrlCoded = data;//System.Web.HttpUtility.UrlEncode(jsonParas); byte[] payload; //将Json字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); //设置请求的ContentLength request.ContentLength = payload.Length; Stream writer; try { writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象 } catch (Exception) { writer = null; errorCode = -100; error = "连接服务器失败!"; } //将请求参数写入流 writer.Write(payload, 0, payload.Length); writer.Close();//关闭请求流 // String strValue = "";//strValue为http响应所返回的字符流 //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 byte[] bArr = new byte[1024]; int iTotalSize = 0; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { iTotalSize += size; fs.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } fs.Close(); responseStream.Close(); dynamic joReturn = new JObject(); joReturn.errorCode = errorCode; joReturn.error = error; joReturn.filePath = filePath; sRtn = joReturn.ToString(); return joReturn; } catch (Exception ex) { errorCode = -100; error = ex.Message; dynamic joReturn = new JObject(); joReturn.errorCode = errorCode; joReturn.error = error; sRtn = joReturn.ToString(); return joReturn; } finally { Global.writeLog("DownloadCenterFile" + "(" + Global.curEvt.URL + ")", data, sRtn); } } /// /// 保存中心交易日志到数据库 /// /// /// private void saveCenterLog(string inParam, string outParam) { dynamic joIris = new JObject(); string sRtn = ""; try { //解析postContent,插入医保交易日志表 JObject joIn = new JObject(JObject.Parse(inParam)); JObject joOut = new JObject(JObject.Parse(outParam)); JArray jaParams = new JArray(); JObject joParam = new JObject(); joParam.Add("inParam", JObject.FromObject(joIn)); joParam.Add("outParam", JObject.FromObject(joOut)); joParam.Add("HospitalDr", Global.inf.hospitalDr); joParam.Add("InterfaceDr", Global.inf.interfaceDr); joParam.Add("updateUserID", Global.user.ID); joParam.Add("psn_no", Global.pat.psn_no); jaParams.Add(joParam); joIris.code = "09010021"; joIris.Add("params", jaParams); //InvokeHelper invoker = new InvokeHelper(); sRtn = invokeInsuService(joIris.ToString(), "保存日志到数据库").ToString(); } catch (Exception ex) { sRtn = JsonHelper.setExceptionJson(-100, "保存日志异常", ex.Message).ToString(); } } } }