NetUtils.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. using System;
  2. using Newtonsoft.Json;
  3. using System.Net;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Text;
  7. using Newtonsoft.Json.Linq;
  8. namespace BasePaySdk
  9. {
  10. /// <summary>
  11. /// 网络通信类
  12. /// </summary>
  13. public class NetUtils
  14. {
  15. public const string POST = "post";
  16. public const string GET = "get";
  17. /// <summary>
  18. /// 发送报文请求
  19. /// </summary>
  20. ///
  21. /// <param name="postParams">报文参数集合</param>
  22. /// <param name="filePath">上传文件路径</param>
  23. /// <param name="fileParam">上传文件参数名</param>
  24. /// <param name="funcCode">接口功能编码</param>
  25. /// <param name="method">http请求方法</param>
  26. /// <param name="merConfig">商户配置信息</param>
  27. ///
  28. /// <returns>返回报文</returns>
  29. ///
  30. public static Dictionary<string, Object> requestBasePayWithFuncCode(Dictionary<string, object> postParams, string filePath, string fileParam, string funcCode, string method, MerConfig merConfig)
  31. {
  32. if (null == merConfig || merConfig.RsaPrivateKey == null)
  33. {
  34. throw new Exception("privateKey 不能为空");
  35. }
  36. string requireUrl = fetchRequestUrl(funcCode);
  37. HttpWebRequest request = null;
  38. if (method.Equals(GET))
  39. {
  40. request = CreateGetRequest(postParams, requireUrl, merConfig);
  41. }
  42. else if (null != filePath)
  43. {
  44. request = CreateUploadRequest(postParams, filePath,fileParam, requireUrl, merConfig);
  45. }
  46. else
  47. {
  48. request = CreatePostRequest(postParams, requireUrl, merConfig);
  49. }
  50. Dictionary<string, Object> responseJson = null;
  51. string responseText = null;
  52. object responseSign = null;
  53. String rsaPublicKey = merConfig.RsaPublicKey;
  54. if(string.IsNullOrEmpty( rsaPublicKey )) {
  55. rsaPublicKey = BasePay.HUIFU_DEFAULT_PUBLIC_KEY;
  56. }
  57. try
  58. {
  59. HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
  60. using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
  61. {
  62. responseText = streamReader.ReadToEnd();
  63. CoreUtils.Log("response:" + responseText);
  64. if (responseText != null && responseText.Contains("html")) {
  65. // 页面版本支付,需要将页面直接返回给
  66. responseJson = new Dictionary<string, object>();
  67. responseJson.Add("data", responseText);
  68. return responseJson;
  69. }
  70. Dictionary<string, object> response = (Dictionary<string, object>)JsonConvert.DeserializeObject<Dictionary<string, object>>(responseText);
  71. Dictionary<string, object> data = (Dictionary<string, object>)JsonConvert.DeserializeObject<Dictionary<string, object>>(response["data"].ToString());
  72. object respCode = null;
  73. data.TryGetValue("resp_code", out respCode);
  74. object respDesc = null;
  75. data.TryGetValue("resp_desc", out respDesc);
  76. string strRespCode = (string) respCode;
  77. string strRespDesc = (string) respDesc;
  78. // 判断接口调用是否成功
  79. //if (!"10000".Equals(strRespCode)) {
  80. // CoreUtils.Log("接口调用失败,失败原因:" + strRespDesc);
  81. // throw new Exception("接口调用失败,失败原因:" + strRespDesc);
  82. //}
  83. CoreUtils.Log("response data....." + data);
  84. responseSign = null;
  85. response.TryGetValue("sign", out responseSign);
  86. string strData = JsonConvert.SerializeObject(response["data"]);
  87. string strSign = (string) responseSign;
  88. if (!string.IsNullOrEmpty(strSign))
  89. {
  90. if (!RsaUtils.verfySign(rsaPublicKey, strSign, strData))
  91. {
  92. throw new Exception("public key veryfy singnature failed");
  93. }
  94. }
  95. responseJson = data;
  96. }
  97. }
  98. catch (WebException e)
  99. {
  100. responseJson = new Dictionary<string, object>();
  101. responseJson.Add("resp_code","99999999");
  102. responseJson.Add("resp_desc", e.Message);
  103. }
  104. return responseJson;
  105. }
  106. /// <summary>
  107. /// 发送上传文件请求
  108. /// </summary>
  109. ///
  110. /// <param name="postParams">报文参数集合</param>
  111. /// <param name="filePath">上传文件路径</param>
  112. /// <param name="fileParam">上传文件参数名</param>
  113. /// <param name="funcCode">接口功能编码</param>
  114. /// <param name="method">http请求方法</param>
  115. /// <param name="merConfig">商户配置信息</param>
  116. ///
  117. /// <returns>返回报文</returns>
  118. ///
  119. public static Dictionary<string, Object> requestBasePayForFileUpload(Dictionary<string, object> postParams, string filePath, string fileParam, string funcCode, string method, MerConfig merConfig)
  120. {
  121. return requestBasePayWithFuncCode(postParams, filePath, fileParam, funcCode, method, merConfig);
  122. }
  123. /// <summary>
  124. /// 发送报文请求
  125. /// </summary>
  126. ///
  127. /// <param name="postParams">报文参数集合</param>
  128. /// <param name="funcCode">接口功能编码</param>
  129. /// <param name="method">http请求方法</param>
  130. /// <param name="merConfig">商户配置信息</param>
  131. ///
  132. /// <returns>返回报文</returns>
  133. ///
  134. public static Dictionary<string, Object> requestBasePay(Dictionary<string, object> postParams, string funcCode, string method, MerConfig merConfig)
  135. {
  136. return requestBasePayWithFuncCode(postParams, null, null, funcCode, method, merConfig);
  137. }
  138. /// <summary>
  139. /// 跟据功能编码获取实际请求地址
  140. /// </summary>
  141. ///
  142. /// <param name="funcCode">接口功能编码</param>
  143. ///
  144. /// <returns>返回接口实际请求地址</returns>
  145. ///
  146. private static String fetchRequestUrl(String funcCode) {
  147. String baseUrl = BasePay.BASE_URL;
  148. if (!BasePay.prodMode) {
  149. baseUrl = BasePay.BASE_URL_MOCK;
  150. }
  151. if (!baseUrl.EndsWith("/")) {
  152. baseUrl = baseUrl + "/";
  153. }
  154. String interfaceUrl = funcCode.Replace(".", "/");
  155. String requestUrl = baseUrl + interfaceUrl;
  156. return requestUrl;
  157. }
  158. //设置get请求参数
  159. // get post 以及post 上传文件的接口,url地址以及签名方式有差别
  160. private static HttpWebRequest CreateGetRequest(Dictionary<string, object> postParams, string requireUrl, MerConfig merConfig)
  161. {
  162. string json_params = CoreUtils.getOrignalString(postParams);
  163. string json_string = requireUrl + json_params;
  164. //参数中会有中文,签名前需url encode
  165. json_string = Uri.UnescapeDataString(json_string);
  166. string signStr = RsaUtils.sign(merConfig.RsaPrivateKey, json_string);
  167. requireUrl = requireUrl + "?" + json_params;
  168. CoreUtils.Log("requireUrl:" + requireUrl);
  169. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requireUrl);
  170. ServicePoint currentServicePoint = request.ServicePoint;
  171. currentServicePoint.ConnectionLimit = 1000;
  172. WebHeaderCollection header = request.Headers;
  173. header.Set("sdk_version", "C#SDK_"+BasePay.sdk_version);
  174. header.Set("format", "JSON");
  175. header.Set("charset", "UTF-8");
  176. header.Set("version", "1.0.0");
  177. header.Set("product_id", merConfig.ProductId);
  178. request.Method = "get";
  179. request.ContentType = "text/html;charset=UTF-8";
  180. return request;
  181. }
  182. //设置不带文件的post请求参数
  183. private static HttpWebRequest CreatePostRequest(Dictionary<string, object> postParams, string requireUrl, MerConfig merConfig)
  184. {
  185. string json_params = JsonConvert.SerializeObject(postParams, Formatting.None);
  186. JObject jo = (JObject)JsonConvert.DeserializeObject(json_params);
  187. Dictionary<string, object> body = new Dictionary<string, object>();
  188. body.Add("sys_id", merConfig.SysId);
  189. //body.Add("sign_type", "RSA2");
  190. body.Add("data", jo);
  191. body.Add("product_id",merConfig.ProductId);
  192. String sortedData = JsonUtils.sort4JsonString(json_params);
  193. string signStr = RsaUtils.sign(merConfig.RsaPrivateKey, sortedData);
  194. body.Add("sign", signStr);
  195. String jsonBody = JsonConvert.SerializeObject(body, Formatting.None);
  196. CoreUtils.Log("request data:" + json_params);
  197. CoreUtils.Log("request sign:" + signStr);
  198. CoreUtils.Log("request body:" + jsonBody);
  199. //参数中会有中文,签名前需url encode
  200. // json_string = Uri.UnescapeDataString(json_string);
  201. HttpWebRequest request = request = (HttpWebRequest)WebRequest.Create(requireUrl);
  202. ServicePoint currentServicePoint = request.ServicePoint;
  203. currentServicePoint.ConnectionLimit = 1000;
  204. WebHeaderCollection header = request.Headers;
  205. header.Set("sdk_version", "C#SDK_" + BasePay.sdk_version);
  206. header.Set("format", "JSON");
  207. header.Set("charset", "UTF-8");
  208. header.Set("version", "1.0.0");
  209. // header.Set("product_id", merConfig.ProductId);
  210. request.Method = "post";
  211. request.ContentType = "application/json";
  212. byte[] byteData = Encoding.UTF8.GetBytes(jsonBody);
  213. int length = byteData.Length;
  214. request.ContentLength = length;
  215. Stream writer = request.GetRequestStream();
  216. writer.Write(byteData, 0, length);
  217. writer.Close();
  218. return request;
  219. }
  220. //设置文件上传request
  221. private static HttpWebRequest CreateUploadRequest(Dictionary<string, object> postParams, string filePath, string fileParam, string requireUrl, MerConfig merConfig)
  222. {
  223. HttpWebRequest request = request = (HttpWebRequest)WebRequest.Create(requireUrl);
  224. ServicePoint currentServicePoint = request.ServicePoint;
  225. currentServicePoint.ConnectionLimit = 1000;
  226. string json_params = JsonConvert.SerializeObject(postParams, Formatting.None);
  227. string signStr = RsaUtils.sign(merConfig.RsaPrivateKey, json_params);
  228. Dictionary<string, object> body = new Dictionary<string, object>();
  229. body.Add("sys_id", merConfig.SysId);
  230. body.Add("sign_type", "RSA2");
  231. body.Add("data", json_params);
  232. body.Add("sign", signStr);
  233. WebHeaderCollection header = request.Headers;
  234. header.Set("sdk_version", "C#SDK_" + BasePay.sdk_version);
  235. header.Set("format", "JSON");
  236. header.Set("charset", "UTF-8");
  237. header.Set("version", "1.0.0");
  238. header.Set("product_id", merConfig.ProductId);
  239. request.Method = "post";
  240. //文件信息
  241. byte[] UpdateFile = CoreUtils.File2Bytes(filePath);//转换为二进制
  242. if (UpdateFile.Length == 0)
  243. {
  244. throw new Exception("file content cannot be null");
  245. }
  246. string Boundary = "--WebKitFormBoundary39B5a5e2FWoGbphs";
  247. //构造POST请求体
  248. StringBuilder PostContent = new StringBuilder("");
  249. //组成普通参数信息
  250. foreach (KeyValuePair<string, object> item in body)
  251. {
  252. PostContent.Append("--" + Boundary + "\r\n")
  253. .Append("Content-Disposition: form-data; name=\"" + item.Key + "\"" + "\r\n\r\n" + (string)item.Value + "\r\n");
  254. }
  255. byte[] PostContentByte = Encoding.UTF8.GetBytes(PostContent.ToString());
  256. //文件信息
  257. StringBuilder FileContent = new StringBuilder();
  258. FileContent.Append("--" + Boundary + "\r\n")
  259. .Append("Content-Disposition:form-data; name=\""+ fileParam + "\";filename=\""+ Path.GetFileName(filePath) +"\"" + "\r\n\r\n");
  260. byte[] FileContentByte = Encoding.UTF8.GetBytes(FileContent.ToString());
  261. request.ContentType = "multipart/form-data;boundary=" + Boundary;
  262. byte[] ContentEnd = Encoding.UTF8.GetBytes("\r\n--" + Boundary + "--\r\n");//请求体末尾,后面会用到
  263. //定义请求流
  264. Stream myRequestStream = request.GetRequestStream();
  265. myRequestStream.Write(PostContentByte, 0, PostContentByte.Length);//写入参数
  266. myRequestStream.Write(FileContentByte, 0, FileContentByte.Length);//写入文件信息
  267. myRequestStream.Write(UpdateFile, 0, UpdateFile.Length);//文件写入请求流中
  268. myRequestStream.Write(ContentEnd, 0, ContentEnd.Length);//写入结尾
  269. myRequestStream.Close();
  270. return request;
  271. }
  272. }
  273. }