/******************************************************************************
* 文件名称: InvokeHelper.cs
* 文件说明: 调用助手,调用方法的封装
* 当前版本: V1.0
* 创建日期: 2022-04-12
*
* 2020-04-12: 增加 businessDLLInvoke 方法
* 2020-04-12: 增加 writeLog 方法
* 2020-04-14: 增加 businessDLLInvoke(重载) 方法
* 2020-04-14: 增加 irisServiceInvoke 方法
******************************************************************************/
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.Helper;
using Newtonsoft.Json;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Variables;
using System.Runtime.InteropServices;
//using chsinterfaceyn;
using System.Reflection;
using PTMedicalInsurance.Forms;
using FastReport.Cloud.OAuth;
using Fizzler;
using System.Security.Policy;
using System.IO.Pipes;
using FastReport.Utils;
using System.Web;
using PTMedicalInsurance.APIGATEWAY_SDK;
namespace PTMedicalInsurance.Helper
{
class InvokeHelper
{
private string serviceURL;
private string authorization;
//广西南宁基线版医保接口调用COM
//string progID1 = "YinHai.XJ.Actual.Interface.New";
//System.Type YinHaiComType;
//object YinHaiComInstance;
public void Call(string infno, string input, out string output)
{
try
{
Type YinHaiComType = System.Type.GetTypeFromProgID("YinHai.XJ.Actual.Interface.New");
if (YinHaiComType != null)
{
//创建实例,不能再次创建,否则会提示没有初始化
object YinHaiComInstance = System.Activator.CreateInstance(YinHaiComType);
if (YinHaiComInstance != null)
{
Global.writeLog("实例创建成功,准备调用Call服务");
}
else
{
output = "实例不存在!";
Global.writeLog("实例不存在");
return;
}
//GlobalVariables.writeLog("入参infno:" + infno);
//GlobalVariables.writeLog("入参input:" + input);
//设置需要设置的参数值
object[] ParamArray = new object[3];
ParamArray[0] = infno;
ParamArray[1] = input;
ParamArray[2] = "";
ParameterModifier[] ParamMods = new ParameterModifier[1];
ParamMods[0] = new ParameterModifier(3); // 初始化为接口参数的个数
//ParamMods[0][0] = false;
//ParamMods[0][1] = false;
ParamMods[0][2] = true;
YinHaiComType.InvokeMember("gxyb_call", // 接口函数名
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
YinHaiComInstance, // 调用的COM组件
ParamArray, // 参数数组
ParamMods, // 指定返回参数的ParameterModifier数组
null,
null);
output = ParamArray[2].ToString();
Global.writeLog("Com输出:" + output);
}
else
{
output = "COM加载失败!";
Global.writeLog("COM加载失败!");
}
}
catch (Exception ex)
{
output = ex.Message;
Global.writeLog("COM加载失败!" + output);
}
}
///
/// 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(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));
}
}
//获取Token
public string GetToken(string url,int ifbd )
{
string rtn = "";
JObject joRtn = new JObject();
url = url + "/auth/oauth/token";
CardReader_JIL Cardreader= new CardReader_JIL();
string ClID = "";
string OutBar = "";
//byte[] b = System.Text.Encoding.Default.GetBytes("90CC2C7FAA93A77C:22010402");
// string Authorza= "Basic " + Convert.ToBase64String(b);
string Authorza = "";
if (ifbd == 1)
{
Authorza = @"Basic OTBDQzJDN0ZBQTkzQTc3QzoyMjAxMDQwMg==";//本地
}
else
{
Authorza = @"Basic QTU4RTcwRjg3MTZDOEM4QzoyMjAxMDQwMg==";//省直异地
}
if (Global.inf.interfaceDr == 34)
{
Authorza = @"Basic QjczOEY5Mjc2MDVFMTkxMjoxMTExMTE=";//本地
}
//if (Global.pat.insuplc_admdvs.Substring(0, 4) != "2201")
//{
// Authorza = "QTU4RTcwRjg3MTZDOEM4QzoyMjAxMDQwMg==";
//}
Cardreader.getCid(out OutBar);
ClID = OutBar;
string data = "";
if (ifbd == 1)
{
data = "username=ccxyb00004&password=111111&grant_type=password&scope=server";
}
else
{
data = "username=50004&password=111111&grant_type=password&scope=server";
}
if (Global.inf.interfaceDr == 34)
{
data = "username=cctest1&password=111111&grant_type=password&scope=server";
}
//if (Global.pat.insuplc_admdvs.Substring(0, 4) != "2201")
//{
//
//}
// MessageBox.Show("data:"+data + "/Authorza:"+ Authorza+ "/url:"+ url);
joRtn =invokeTokenService(data, Authorza, url);
//MessageBox.Show("获取Token返回:" + joRtn.ToString());
rtn = JsonHelper.getDestValue(joRtn, "access_token");
return rtn;
}
//长春获取Token服务增加头部信息
private JObject invokeTokenService(string data, string auto, string url)
{
string postContent = "";
JObject joRtn = new JObject();
try
{
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//Post请求方式
request.Method = "POST";
request.Headers.Add("Authorization", auto);
/*
//昆明增加头部信息
string nonce = Guid.NewGuid().ToString(); //非重复的随机字符串(十分钟内不能重复)
string timestamp = TimeStamp.get13().ToString(); //当前时间戳(秒)
string BusinessID = Global.inf.BusinessID; //服务商ID
string InsuHosID = Global.inf.hospitalNO; //医疗机构ID
string CreditID = Global.inf.CreditID; //服务商统一社会信用代码
string sTemp = timestamp + BusinessID + nonce;
//Sha256 加密生成的签名 signature = sha256(hsf_timestamp + infosyssign + hsf_nonce)
string signature = Encrypt.SHA256EncryptStr(sTemp);
request.Headers.Add("hsf_signature", signature);
request.Headers.Add("hsf_timestamp", timestamp);
request.Headers.Add("hsf_nonce", nonce);
request.Headers.Add("fixmedins_code", InsuHosID);
request.Headers.Add("infosyscode", CreditID);
*/
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//设置参数,并进行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 = "获取Token异常" + ex.Message;
joRtn.Add("infcode", -1);
joRtn.Add("err_msg", "invokeTokenService(1):" + ex.Message);
return joRtn;
}
finally
{
Global.writeLog($"获取Token({url})", $"data:{data},auth:{auto}", joRtn.ToString());
}
}
///
/// 医保平台服务调用的封装
///
///
///
public JObject invokeInsuService(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);
// //if (serviceDesc == "插入签到信息")
// //{
// // MessageBox.Show("插入签到信息入参:" + data +"|返回值:"+ rtn.ToString()+"|"+ Global.insuConfig.url);
// //}
// 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);
//}
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);
}
}
///
/// 医保中心Post服务调用封装
///
///
///
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";
/*
//昆明增加头部信息
string nonce = Guid.NewGuid().ToString(); //非重复的随机字符串(十分钟内不能重复)
string timestamp = TimeStamp.get13().ToString(); //当前时间戳(秒)
string BusinessID = Global.inf.BusinessID; //服务商ID
string InsuHosID = Global.inf.hospitalNO; //医疗机构ID
string CreditID = Global.inf.CreditID; //服务商统一社会信用代码
string sTemp = timestamp + BusinessID + nonce;
//Sha256 加密生成的签名 signature = sha256(hsf_timestamp + infosyssign + hsf_nonce)
string signature = Encrypt.SHA256EncryptStr(sTemp);
request.Headers.Add("hsf_signature", signature);
request.Headers.Add("hsf_timestamp", timestamp);
request.Headers.Add("hsf_nonce", nonce);
request.Headers.Add("fixmedins_code", InsuHosID);
request.Headers.Add("infosyscode", CreditID);
*/
//长春增加头部信息
string headstr = "";
//if (Global.pat.insuplc_admdvs.Substring(0,4) =="2201")
//{
// headstr = @"bearer " + Global.curEvt.token;//市医保token
// MessageBox.Show("参保地:"+ Global.pat.insuplc_admdvs + ",已赋值市医保token!!!");
//}
//else
//{
// headstr = @"bearer " + Global.curEvt.ydtoken;
// MessageBox.Show("参保地:" + Global.pat.insuplc_admdvs + ",已赋值省医保token!!!");
//}
headstr = @"Bearer " + Global.curEvt.token;//市医保token
//string headstr = @"bearer " + Global.curEvt.token;
//string headstr = @"Bearer cHJpbnRlcmZhY2U6cFIyMEBP";
request.Headers.Add("Authorization", headstr);
//MessageBox.Show("头部信息" + headstr);
//内容类型
request.ContentType = "application/json";
Global.writeLog("header", "", request.Headers.ToString());
//设置参数,并进行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;
}
}
///
/// 医保中心Post服务调用封装9101上传
///
///
///
private JObject invokeSCCenterService(string data)
{
string postContent = "";
JObject joRtn = new JObject();
try
{
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ddjk.jlhs.gov.cn:20215/mbs/fsi/api/fileupload");
//Post请求方式
request.Method = "POST";
/*
//昆明增加头部信息
string nonce = Guid.NewGuid().ToString(); //非重复的随机字符串(十分钟内不能重复)
string timestamp = TimeStamp.get13().ToString(); //当前时间戳(秒)
string BusinessID = Global.inf.BusinessID; //服务商ID
string InsuHosID = Global.inf.hospitalNO; //医疗机构ID
string CreditID = Global.inf.CreditID; //服务商统一社会信用代码
string sTemp = timestamp + BusinessID + nonce;
//Sha256 加密生成的签名 signature = sha256(hsf_timestamp + infosyssign + hsf_nonce)
string signature = Encrypt.SHA256EncryptStr(sTemp);
request.Headers.Add("hsf_signature", signature);
request.Headers.Add("hsf_timestamp", timestamp);
request.Headers.Add("hsf_nonce", nonce);
request.Headers.Add("fixmedins_code", InsuHosID);
request.Headers.Add("infosyscode", CreditID);
*/
//长春增加头部信息
string headstr = "";
//if (Global.pat.insuplc_admdvs.Substring(0,4) =="2201")
//{
// headstr = @"bearer " + Global.curEvt.token;//市医保token
// MessageBox.Show("参保地:"+ Global.pat.insuplc_admdvs + ",已赋值市医保token!!!");
//}
//else
//{
// headstr = @"bearer " + Global.curEvt.ydtoken;
// MessageBox.Show("参保地:" + Global.pat.insuplc_admdvs + ",已赋值省医保token!!!");
//}
headstr = @"bearer " + Global.curEvt.token;//市医保token
//string headstr = @"bearer " + Global.curEvt.token;
//string headstr = @"Bearer cHJpbnRlcmZhY2U6cFIyMEBP";
request.Headers.Add("Authorization", headstr);
//MessageBox.Show("头部信息" + headstr);
//内容类型
request.ContentType = "application/json";
//设置参数,并进行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;
}
}
///
/// 这个是调用业务服务的invokeCenterService
///
///
///
///
public JObject invokeCenterService(string funNO, JObject data)
{
JObject joRtn = new JObject();
string outPar = "";
string input = "";
try
{
Global.curEvt.URL = Global.inf.centerURL;
input = JsonHelper.setCenterInpar(funNO, data.ToString());
joRtn = invokeCenterService(data.ToString());
outPar = JsonHelper.Compress(joRtn);
return joRtn;
}
catch (Exception ex)
{
if (joRtn["infcode"] == null)
{ joRtn.Add("infcode", -1); }
if (joRtn["err_msg"] == null)
{ 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);
this.saveCenterLog(JsonHelper.Compress(data), outPar, JsonHelper.Compress(data), outPar);
}
}
///
/// 这个是下载目录用的invokeCenterService
///
///
///
///
public JObject invokeCenterService(string funNO, string data)
{
JObject joRtn = new JObject();
int iInt = 0;
String outPar = "";
string input = "";
try
{
Global.curEvt.URL = Global.inf.centerURL ;
// Global.curEvt.URL="http://ddjk.jlhs.gov.cn:20215/mbs/fmi/fsi/api/callFsiService/callService";
//MessageBox.Show("调用前url:"+ Global.curEvt.URL);
//input = JsonHelper.setCenterInpar(funNO, data.ToString());
joRtn = invokeCenterService(data);
outPar = JsonHelper.Compress(joRtn);
return joRtn;
}
catch (Exception ex)
{
if (joRtn["infcode"] == null)
{ joRtn.Add("infcode", -1); }
if (joRtn["err_msg"] == null)
{ 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);
this.saveCenterLog(JsonHelper.Compress(data), outPar, JsonHelper.Compress(data), outPar);
}
}
//长春上传专用
public JObject UploadCenterService(string funNO, string data)
{
JObject joRtn = new JObject();
int iInt = 0;
String outPar = "";
string input = "";
try
{
// Global.curEvt.URL = Global.inf.centerURL;
// Global.curEvt.URL="http://ddjk.jlhs.gov.cn:20215/mbs/fmi/fsi/api/callFsiService/callService";
//MessageBox.Show("调用前url:"+ Global.curEvt.URL);
//input = JsonHelper.setCenterInpar(funNO, data.ToString());
joRtn = invokeSCCenterService(data);
outPar = JsonHelper.Compress(joRtn);
return joRtn;
}
catch (Exception ex)
{
if (joRtn["infcode"] == null)
{ joRtn.Add("infcode", -1); }
if (joRtn["err_msg"] == null)
{ 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);
this.saveCenterLog(JsonHelper.Compress(data), outPar, JsonHelper.Compress(data), outPar);
}
}
///
/// 医保目录txt文件下载
///
///
///
public JObject DownloadCenterFileByAPI(string data)
{
string error = string.Empty; int errorCode = 0;
string sRtn = "";
string durl = "http://ddjk.jlhs.gov.cn:20215/mbs/fsi/api/fileupload";//长春上传下载地址专用
try
{
JObject jsonInParam = JObject.Parse(data);
string fileName = (string)jsonInParam["input"]["fsDownloadIn"]["filename"];
string filePath = Global.curEvt.path + "\\Download\\" + fileName;
//MessageBox.Show("9102下载文件入参:"+jsonInParam.ToString());
//如果不存在目录,则创建目录
if (!Directory.Exists(Global.curEvt.path + "\\Download"))
{
//创建文件夹
DirectoryInfo dirInfo = Directory.CreateDirectory(Global.curEvt.path + "\\Download");
}
if (File.Exists(filePath))
{
MessageBox.Show("文件存在");
File.Delete(filePath);
}
FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
//创建一个HTTP请求
//Global.curEvt.URL = Global.inf.centerURL + "/hsa-fsi-9102";
//正常下载
// Global.curEvt.URL = Global.inf.centerURL;
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL);
//MessageBox.Show("9102下载"+ durl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(durl);
//长春增加头部信息
string headstr = @"bearer " + Global.curEvt.token;
//string headstr = @"Bearer cHJpbnRlcmZhY2U6cFIyMEBP";
request.Headers.Add("Authorization", headstr);
// MessageBox.Show("头部信息" + headstr);
//Post请求方式
request.Method = "POST";
string timestamp = TimeStamp.get13().ToString(); //当前时间戳(秒)
string nonce = Guid.NewGuid().ToString(); //非重复的随机字符串(十分钟内不能重复)
string InsuHosID = Global.inf.hospitalNO; //医疗机构ID
string CreditID = Global.inf.CreditID; //服务商统一社会信用代码
string BusinessID = Global.inf.BusinessID; //服务商ID
//内容类型
request.ContentType = "application/json";
request.Accept = "text/html,application/xhtml+xml, */*";
/*
//昆明增加头部信息
string sTemp = timestamp + BusinessID + nonce;
//Sha256 加密生成的签名 signature = sha256(hsf_timestamp + infosyssign + hsf_nonce)
string signature = Encrypt.SHA256EncryptStr(sTemp);
request.Headers.Add("hsf_signature", signature);
request.Headers.Add("hsf_timestamp", timestamp);
request.Headers.Add("hsf_nonce", nonce);
request.Headers.Add("fixmedins_code", InsuHosID);
request.Headers.Add("infosyscode", CreditID);
*/
//设置参数,并进行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);
//MessageBox.Show("文件大小:" + size.ToString());
while (size > 0)
{
iTotalSize += size;
fs.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
//byte[] array = Encoding.UTF8.GetBytes(responseStream.ToString());
//16进制完整写入
//byte[] bArr = new byte[responseStream.Length];
//for (int i = 0; i < responseStream.Length / 2; i = i + 2)
//{
// bArr[i]= Convert.ToByte(responseStream.ToString().Substring(i * 2, 2), 16);
//}
//fs.Write(bArr, 0, bArr.Length);
fs.Close();
responseStream.Close();
dynamic joReturn = new JObject();
joReturn.errorCode = errorCode;
joReturn.errorMessage = 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.errorMessage = error;
sRtn = joReturn.ToString();
return joReturn;
}
finally
{
//Global.writeLog("DownloadCenterFile" +"(" + Global.curEvt.URL + ")", data, sRtn);
Global.writeLog("DownloadCenterFile" + "(" + durl + ")", 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();
}
}*/
///
/// 保存中心交易日志到数据库
///
///
///
private void saveCenterLog(string inParam, string outParam, string inParamPlain, string outParamPlain)
{
dynamic joIris = new JObject();
string sRtn = "";
try
{
//解析postContent,插入医保交易日志表
JObject joIn = new JObject(JObject.Parse(inParam));
JObject joOut = new JObject(JObject.Parse(outParam));
JObject joInPlain = new JObject(JObject.Parse(inParamPlain));
JObject joOutPlain = new JObject(JObject.Parse(outParamPlain));
JArray jaParams = new JArray();
JObject joParam = new JObject();
joParam.Add("inParam", JObject.FromObject(joIn));
joParam.Add("outParam", JObject.FromObject(joOut));
joParam.Add("inParamPlain", JObject.FromObject(joInPlain));
joParam.Add("outParamPlain", JObject.FromObject(joOutPlain));
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();
Global.writeLog_Iris("保存日志异常:" + sRtn.ToString());
}
}
/**********************************************************调用DLL方式**************************************************************/
#region 移动支付
//加载中心动态库
private void LoadCenterURL(bool reload)
{
IniFile ini = new IniFile(Global.curEvt.path + @"\CenterServiceURL.ini");
Global.inf.uploadURL = tools.getDestPosStrBySpliter(Global.inf.centerURL2, 1);
Global.inf.downURL = tools.getDestPosStrBySpliter(Global.inf.centerURL2, 2);
Global.inf.ecURL = tools.getDestPosStrBySpliter(Global.inf.centerURL2, 3);
if (reload)
{
Global.inf.mobilePayURL = ini.ReadValue("CENTER", "mobilePay");
Global.inf.presCenterURL = ini.ReadValue("CENTER", "prescription");
// 移动支付
if (string.IsNullOrEmpty(Global.inf.mobilePayURL))
{
Global.inf.mobilePayURL = Global.curEvt.URL;
}
// 电子处方
if (string.IsNullOrEmpty(Global.inf.presCenterURL))
{
Global.inf.presCenterURL = Global.curEvt.URL ;
}
}
}
///
/// 移动
///
///
///
///
///
public JObject invokeMPService(string funNO, string data)
{
return invokeMPService(funNO, JObject.Parse(data));
}
public JObject invokeMPService(string funNO, JObject joInput)
{
JObject joRtn = new JObject();
String outPar = "";
try
{
LoadCenterURL(true);
string url = "";
switch (funNO)
{
case "6201":
url = "/org/local/api/hos/uldFeeInfo";
break;
case "6202":
url = "/org/local/api/hos/pay_order";
break;
case "6203":
url = "/org/local/api/hos/refund_Order";
break;
case "6301":
url = "/org/local/api/hos/query_order_info";
break;
case "6401":
url = "/org/local/api/hos/revoke_order";
break;
default:
break;
}
EncryptHelper encrypt = new EncryptHelper();
string data = JsonHelper.setMPCenterInpar(funNO, joInput);
// 移动支付地址
Global.curEvt.URL = Global.inf.mobilePayURL + url;
try
{
joRtn = invokeCenterService(data);
Global.writeLog(funNO + "【密文出参】:\r\n" + joRtn.ToString());
string encData = JsonHelper.getDestValue(joRtn, "encData");
string signData = JsonHelper.getDestValue(joRtn, "signData");
if (!string.IsNullOrEmpty(encData) && !string.IsNullOrEmpty(signData))
{
joRtn.Remove("encData");
joRtn.Remove("signData");
joRtn.Remove("data");
//解密
string decData = encrypt.decrypt(encData);
// 验签
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
FloatParseHandling = FloatParseHandling.Decimal
};
joRtn.Add("data", JToken.FromObject(JsonConvert.DeserializeObject(decData)));
bool rtn = encrypt.verify(joRtn, signData);
if (rtn)
{
Global.writeLog("验签通过!");
}
else
{
Global.writeLog("验签失败,请核查!");
}
if (!string.IsNullOrEmpty(decData))
{
Global.writeLog(funNO + "【明文出参】:\r\n" + decData);
joRtn = JObject.Parse(decData);
joRtn.Add("success", "True");
}
}
return joRtn;
}
finally
{
this.saveCenterLog(JsonHelper.Compress(data), joRtn.ToString(), JsonHelper.Compress(data), joRtn.ToString());
}
}
catch (Exception ex)
{
if (joRtn["infcode"] == null)
{ joRtn.Add("infcode", -1); }
if (joRtn["err_msg"] == null)
{ joRtn.Add("err_msg", "invokeCenterService(3):" + ex.Message); }
outPar = JsonHelper.Compress(joRtn);
return joRtn;
}
finally
{
Global.writeLog(funNO + "(" + Global.curEvt.URL + ")", joInput.ToString(), joRtn.ToString());
this.saveCenterLog(joInput.ToString(), joRtn.ToString(), joInput.ToString(), joRtn.ToString());
}
}
#endregion
#region 处方流转
///
/// 医保电子处方流转调用服务
///
///
///
private JObject invokeCenterServicePresCir(string data)
{
string postContent = "";
JObject joRtn = new JObject();
try
{
//内容类型
Signer signer = new Signer();
signer.Key = Global.inf.privateKey; //应用编码
signer.Secret = Global.inf.Secret; //secretKey 私钥
string timestamp = TimeStamp.get13().ToString(); //当前时间戳(秒)
string nonce = Guid.NewGuid().ToString(); //非重复的随机字符串(十分钟内不能重复)
HttpRequest Resquest = new HttpRequest("POST", new Uri(Global.curEvt.URL));
Resquest.headers.Add("charset", "UTF-8");
//Resquest.headers.Add("x-hw-id", signer.Key);
//Resquest.headers.Add("x-tif-timestamp", timestamp);
//Resquest.headers.Add("x-tif-passid", signer.Key);
//Resquest.headers.Add("x-tif-nonce", nonce);
Resquest.body = data;
string RtnStr;
HttpWebRequest req = signer.Sign(Resquest);
req.ContentType = "application/json;charset=utf8";
req.Timeout = 5 * 10000;
try
{
var writer = new StreamWriter(req.GetRequestStream());
writer.Write(Resquest.body);
writer.Flush();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream());
RtnStr = reader.ReadToEnd();
joRtn = JObject.Parse(RtnStr);//返回Json数据
return joRtn;
}
catch (WebException e)
{
HttpWebResponse resp = (HttpWebResponse)e.Response;
if (resp != null)
{
return JsonHelper.setExceptionJson(-99, "centerServeiceInvok中获得响应流异常(a)", new StreamReader(resp.GetResponseStream()).ReadToEnd() + "异常内容:" + e.Message);
}
else
{
RtnStr = "异常:" + e.Message;
return JsonHelper.setExceptionJson(-99, "centerServeiceInvok中获得响应流异常(b)", e.Message);
}
}
}
catch (Exception ex)
{
postContent = "调用中心服务异常" + ex.Message;
joRtn.Add("infcode", -1);
joRtn.Add("err_msg", "invokeCenterService(Exception_Last):" + ex.Message);
return joRtn;
}
}
///
///
///
///
public JObject invokeCenterServicePresCir(string funNO, string data)
{
JObject joRtn = new JObject();
string outPar = "";
try
{
if (funNO == "7101")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/uploadChk";
}
else if (funNO == "7102")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/rxFixmedinsSign";
}
else if (funNO == "7103")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/rxFileUpld";
}
else if (funNO == "7104")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/rxUndo";
}
else if (funNO == "7105")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/hospRxDetlQuery";
}
else if (funNO == "7106")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/rxChkInfoQuery";
}
else if (funNO == "7107")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/rxSetlInfoQuery";
}
else if (funNO == "7108")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/rxChkInfoCallback";
}
else if (funNO == "7109")
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/rxSetlInfoCallback";
}
else if (funNO == "7112") //电子处方药品目录查询
{
Global.curEvt.URL = Global.inf.presCenterURL + "/fixmedins/circDrugQuery";
}
else
{
Global.curEvt.URL = Global.inf.centerURL;
}
//Global.curEvt.URL = Global.inf.centerURL;
joRtn = invokeCenterServicePresCir(data);
outPar = JsonHelper.Compress(joRtn);
return joRtn;
}
catch (Exception ex)
{
if (joRtn["infcode"] == null)
{ joRtn.Add("infcode", -1); }
if (joRtn["err_msg"] == null)
{ joRtn.Add("err_msg", "invokeCenterServicePresCir(3):" + 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, JsonHelper.Compress(data), outPar);
}
}
#endregion
}
}