TestHaoDaHelper.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. using System.Net.Mime;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using Library;
  8. using System.Net;
  9. using System.IO;
  10. using Aop.Api.Util;
  11. using LitJson;
  12. namespace MySystem
  13. {
  14. public class TestHaoDaHelper
  15. {
  16. public readonly static TestHaoDaHelper Instance = new TestHaoDaHelper();
  17. private TestHaoDaHelper()
  18. {
  19. }
  20. #region 盒易付
  21. //测试环境
  22. // string BoxRequestUrl = "https://openapi-test.iboxpay.com";
  23. // string BoxAppId = "AT7317781468267548672";
  24. // string BoxAppSecret = "OfWuHQdhQfnE8NaF4xdtgk4B9CYqnbri";
  25. // string BoxPublicKey = "";
  26. // string BrhCode = "001040";
  27. //生产环境
  28. string BoxRequestUrl = "https://openapi.iboxpay.com";
  29. string BoxAppId = "AP7175619323825451008";
  30. string BoxAppSecret = "hUfR53gdjyfiZTBR5bILanMqRD1dXD7y";
  31. string BoxPublicKey = "";
  32. public static string BrhCode = "030145";
  33. /// <summary>
  34. /// 商户修改银行卡
  35. /// </summary>
  36. /// <param name="request"></param>
  37. /// <returns></returns>
  38. public string ChangeMerchantCard(ChangeMerchantCard request)
  39. {
  40. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "好哒商户修改银行卡");
  41. string req = Newtonsoft.Json.JsonConvert.SerializeObject(request);
  42. LogHelper.Instance.WriteLog(req, "好哒商户修改银行卡");
  43. Dictionary<string, string> headdic = GetHeader(req);
  44. string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
  45. LogHelper.Instance.WriteLog("请求头\n" + head, "好哒商户修改银行卡");
  46. LogHelper.Instance.WriteLog("请求参数\n" + req, "好哒商户修改银行卡");
  47. LogHelper.Instance.WriteLog("请求地址:" + BoxRequestUrl + "/api/inst/mcht/update_acct", "好哒商户修改银行卡");
  48. string result = PostWebRequest(BoxRequestUrl + "/api/inst/mcht/update_acct", req, headdic);
  49. LogHelper.Instance.WriteLog("返回\n" + result + "\n\n", "好哒商户修改银行卡");
  50. return result;
  51. }
  52. /// <summary>
  53. /// 查询修改银行卡任务审核状态
  54. /// </summary>
  55. /// <param name="mchtNo">收款商户号</param>
  56. /// <param name="taskId">任务id</param>
  57. /// <returns></returns>
  58. public string QueryChangeCardStatus(string mchtNo, string taskId)
  59. {
  60. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "好哒查询修改银行卡任务审核状态");
  61. Dictionary<string, object> reqdic = new Dictionary<string, object>();
  62. reqdic.Add("mchtNo", mchtNo);
  63. reqdic.Add("taskId", taskId);
  64. string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
  65. LogHelper.Instance.WriteLog(req, "好哒查询修改银行卡任务审核状态");
  66. Dictionary<string, string> headdic = GetHeader(req);
  67. string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
  68. LogHelper.Instance.WriteLog("请求头\n" + head, "好哒查询修改银行卡任务审核状态");
  69. LogHelper.Instance.WriteLog("请求参数\n" + req, "好哒查询修改银行卡任务审核状态");
  70. LogHelper.Instance.WriteLog("请求地址:" + BoxRequestUrl + "/api/inst/mcht/query_acct_task", "好哒查询修改银行卡任务审核状态");
  71. string result = PostWebRequest(BoxRequestUrl + "/api/inst/mcht/query_acct_task", req, headdic);
  72. LogHelper.Instance.WriteLog("返回\n" + result + "\n\n", "好哒查询修改银行卡任务审核状态");
  73. return result;
  74. }
  75. /// <summary>
  76. /// 订单分账申请
  77. /// </summary>
  78. /// <param name="request"></param>
  79. /// <returns></returns>
  80. ///
  81. public string OrderDivideAccounts22()
  82. {
  83. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "好哒订单分账申请");
  84. Dictionary<string, object> reqdic = new Dictionary<string, object>();
  85. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  86. Dictionary<string, object> lists = new Dictionary<string, object>();
  87. lists = new Dictionary<string, object>();
  88. reqdic.Add("applyNo", "FZ202309070001");
  89. reqdic.Add("mchtNo", "1475762");
  90. reqdic.Add("orderNo", "G2230907C01986946066");
  91. lists.Add("acctNo", "230817000000000278");
  92. lists.Add("acctType", "1");
  93. lists.Add("amount", "100");
  94. list.Add(lists);
  95. lists = new Dictionary<string, object>();
  96. lists.Add("acctNo", "030510106621391");
  97. lists.Add("acctType", "0");
  98. lists.Add("amount", "9862");
  99. list.Add(lists);
  100. reqdic.Add("detail", list);
  101. string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
  102. LogHelper.Instance.WriteLog(req, "好哒订单分账申请");
  103. Dictionary<string, string> headdic = GetHeader(req);
  104. string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
  105. LogHelper.Instance.WriteLog("请求头\n" + head, "好哒订单分账申请");
  106. LogHelper.Instance.WriteLog("请求参数\n" + req, "好哒订单分账申请");
  107. LogHelper.Instance.WriteLog("请求地址:" + BoxRequestUrl + "/api/v3/hzg/part/order/apply", "好哒订单分账申请");
  108. string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/order/apply", req, headdic);
  109. LogHelper.Instance.WriteLog("返回\n" + result + "\n\n", "好哒订单分账申请");
  110. return result;
  111. }
  112. /// <summary>
  113. /// 分账交易详情查询
  114. /// </summary>
  115. /// <param name="mchtNo">慧掌柜商户号</param>
  116. /// <param name="orderNo">交易订单号 </param>
  117. /// <returns></returns>
  118. public string QueryOrderDivideAccountsss()
  119. {
  120. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "好哒分账交易详情查询");
  121. Dictionary<string, object> reqdic = new Dictionary<string, object>();
  122. reqdic.Add("mchtNo", "1475762"); // 慧掌柜商户号
  123. reqdic.Add("orderNo", "G2230907C01986946066"); // 交易订单号
  124. string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
  125. LogHelper.Instance.WriteLog(req, "好哒分账交易详情查询");
  126. Dictionary<string, string> headdic = GetHeader(req);
  127. string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
  128. LogHelper.Instance.WriteLog("请求头\n" + head, "好哒分账交易详情查询");
  129. LogHelper.Instance.WriteLog("请求参数\n" + req, "好哒分账交易详情查询");
  130. LogHelper.Instance.WriteLog("请求地址:" + BoxRequestUrl + "/api/v3/hzg/part/trade/clear/get", "好哒分账交易详情查询");
  131. string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/trade/clear/get", req, headdic);
  132. LogHelper.Instance.WriteLog("返回\n" + result + "\n\n", "好哒分账交易详情查询");
  133. return result;
  134. }
  135. /// <summary>
  136. /// 聚合支付退款接口
  137. /// </summary>
  138. /// <param name="mchtNo">盒子的商户编号</param>
  139. /// <param name="storeNo">盒子的门店编号</param>
  140. /// <param name="outRefundNo">商户退款订单号</param>
  141. /// <param name="outOrderNo">商户支付订单号</param>
  142. /// <param name="refundAmount">退款金额,单位:分</param>
  143. /// <returns></returns>
  144. public string AggregatedPayRefundsss()
  145. {
  146. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "好哒聚合支付退款");
  147. Dictionary<string, object> reqdic = new Dictionary<string, object>();
  148. reqdic.Add("mchtNo", "1475762"); // 盒子的商户编号
  149. reqdic.Add("storeNo", "21604555"); // 盒子的门店编号
  150. reqdic.Add("outRefundNo", "9335533180636825300395666888"); //32 商户退款订单号
  151. reqdic.Add("outOrderNo", "2023090715460060997601022"); // 商户支付订单号
  152. reqdic.Add("refundAmount", "502"); //10 退款金额,单位:分
  153. reqdic.Add("refundReason", "门店消费补贴"); //退款原因(仅微信交易且退款金额大于1元时在退款消息中展示)
  154. string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
  155. LogHelper.Instance.WriteLog(req, "好哒聚合支付退款");
  156. Dictionary<string, string> headdic = GetHeader(req);
  157. string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
  158. LogHelper.Instance.WriteLog("请求头\n" + head, "好哒聚合支付退款");
  159. LogHelper.Instance.WriteLog("请求参数\n" + req, "好哒聚合支付退款");
  160. LogHelper.Instance.WriteLog("请求地址:" + BoxRequestUrl + "/api/hzg/v2/unitedtrade/refund", "好哒聚合支付退款");
  161. string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/unitedtrade/refund", req, headdic);
  162. LogHelper.Instance.WriteLog("返回\n" + result + "\n\n", "好哒聚合支付退款");
  163. return result;
  164. }
  165. public Dictionary<string, string> GetHeader(string req)
  166. {
  167. Dictionary<string, string> headdic = new Dictionary<string, string>();
  168. string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  169. // headdic.Add("appid", BoxAppId);//开发者id
  170. // headdic.Add("appsecret", BoxAppSecret);//开发者密码
  171. headdic.Add("X-Up-AppId", BoxAppId);
  172. headdic.Add("X-Timestamp", timestamp);
  173. headdic.Add("X-Sign-Type", "SHA-256");
  174. headdic.Add("X-Sign", SHA256Sign(timestamp + BoxAppSecret + req));
  175. return headdic;
  176. }
  177. public string SHA256Sign(string toSignStr)
  178. {
  179. byte[] toSignByte = Encoding.UTF8.GetBytes(toSignStr);
  180. SHA256 sha256 = SHA256.Create();
  181. byte[] signByte = sha256.ComputeHash(toSignByte);
  182. string sign = Convert.ToBase64String(signByte);
  183. return sign;
  184. }
  185. public bool VerifySign(string toSignStr, string signStr)
  186. {
  187. byte[] toSignByte = Encoding.Default.GetBytes(toSignStr);
  188. byte[] signByte = Convert.FromBase64String(signStr);
  189. var toKey = Convert.FromBase64String(BoxPublicKey);
  190. var rsaroot = RSA.Create();
  191. rsaroot.ImportSubjectPublicKeyInfo(toKey, out _);
  192. var publicKeyParameters = rsaroot.ExportParameters(false);
  193. using (var rsa = RSA.Create())
  194. {
  195. rsa.ImportParameters(publicKeyParameters);
  196. var sha256 = SHA256.Create();
  197. var hash = sha256.ComputeHash(toSignByte);
  198. return rsa.VerifyHash(hash, signByte, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
  199. }
  200. }
  201. public string SignData(string toSignStr)
  202. {
  203. byte[] toSignByte = Encoding.UTF8.GetBytes(toSignStr);
  204. var toKey = Convert.FromBase64String(BoxPublicKey);
  205. var rsaroot = RSA.Create();
  206. rsaroot.ImportSubjectPublicKeyInfo(toKey, out _);
  207. var publicKeyParameters = rsaroot.ExportParameters(false);
  208. using (var rsa = RSA.Create())
  209. {
  210. rsa.ImportParameters(publicKeyParameters);
  211. var sha256 = SHA256.Create();
  212. var hash = sha256.ComputeHash(toSignByte);
  213. byte[] endByte = rsa.SignData(toSignByte, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
  214. return Convert.ToBase64String(endByte);
  215. }
  216. }
  217. private string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> headers)
  218. {
  219. string ret = string.Empty;
  220. try
  221. {
  222. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "请求好哒API日志");
  223. LogHelper.Instance.WriteLog(postUrl, "请求好哒API日志");
  224. LogHelper.Instance.WriteLog(paramData, "请求好哒API日志");
  225. byte[] postData = System.Text.Encoding.UTF8.GetBytes(paramData);
  226. // 设置提交的相关参数
  227. System.Net.HttpWebRequest request = System.Net.WebRequest.Create(postUrl) as System.Net.HttpWebRequest;
  228. System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
  229. request.Method = "POST";
  230. request.KeepAlive = false;
  231. request.AllowAutoRedirect = true;
  232. request.ContentType = "application/json";
  233. foreach (string key in headers.Keys)
  234. {
  235. request.Headers.Add(key, headers[key]);
  236. }
  237. request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
  238. request.ContentLength = postData.Length;
  239. // 提交请求数据
  240. System.IO.Stream outputStream = request.GetRequestStream();
  241. outputStream.Write(postData, 0, postData.Length);
  242. outputStream.Close();
  243. System.Net.HttpWebResponse response;
  244. System.IO.Stream responseStream;
  245. System.IO.StreamReader reader;
  246. string srcString;
  247. response = request.GetResponse() as System.Net.HttpWebResponse;
  248. responseStream = response.GetResponseStream();
  249. reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
  250. srcString = reader.ReadToEnd();
  251. ret = srcString; //返回值赋值
  252. reader.Close();
  253. LogHelper.Instance.WriteLog(srcString, "请求好哒API日志");
  254. }
  255. catch (System.Net.WebException ex)
  256. {
  257. System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)ex.Response;
  258. System.IO.Stream myResponseStream = response.GetResponseStream();
  259. //获取响应内容
  260. System.IO.StreamReader myStreamReader = new System.IO.StreamReader(myResponseStream);
  261. ret = myStreamReader.ReadToEnd();
  262. myResponseStream.Close();
  263. }
  264. catch (Exception ex)
  265. {
  266. ret = "fail";
  267. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "请求好哒API异常");
  268. }
  269. return ret;
  270. }
  271. /// <summary>
  272. /// 获取文件令牌接口
  273. /// </summary>
  274. /// <param name="fileName">文件名</param>
  275. /// <param name="action">操作类型 0 上传图片</param>
  276. /// <returns></returns>
  277. public string GetToken(string fileName, string action)
  278. {
  279. LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "好哒获取文件令牌接口");
  280. Dictionary<string, object> reqdic = new Dictionary<string, object>();
  281. reqdic.Add("fileName", fileName); // 文件名
  282. reqdic.Add("action", action); // 操作类型 0 上传图片
  283. string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
  284. LogHelper.Instance.WriteLog(req, "好哒获取文件令牌接口");
  285. Dictionary<string, string> headdic = GetHeader(req);
  286. string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
  287. LogHelper.Instance.WriteLog("请求头\n" + head, "好哒获取文件令牌接口");
  288. LogHelper.Instance.WriteLog("请求参数\n" + req, "好哒获取文件令牌接口");
  289. LogHelper.Instance.WriteLog("请求地址:" + BoxRequestUrl + "/api/auth/v1/get_file_token", "好哒获取文件令牌接口");
  290. string result = PostWebRequest(BoxRequestUrl + "/api/auth/v1/get_file_token", req, headdic);
  291. LogHelper.Instance.WriteLog("返回\n" + result + "\n\n", "好哒获取文件令牌接口");
  292. return result;
  293. }
  294. /// <summary>
  295. /// 执行带文件上传的HTTP POST请求。
  296. /// </summary>
  297. /// <param name="url">请求地址</param>
  298. /// <param name="textParams">请求文本参数</param>
  299. /// <param name="fileParams">请求文件参数</param>
  300. /// <param name="charset">编码字符集</param>
  301. /// <returns>HTTP响应</returns>
  302. public string DoPost(string url, string token, IDictionary<string, string> textParams, IDictionary<string, FileItem> fileParams, string charset = "utf-8")
  303. {
  304. // 如果没有文件参数,则走普通POST请求
  305. if (fileParams == null || fileParams.Count == 0)
  306. {
  307. return "";
  308. }
  309. string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
  310. HttpWebRequest req = GetWebRequest(url, "POST");
  311. req.Headers.Add("X-File-Token", token);
  312. req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary;
  313. Stream reqStream = req.GetRequestStream();
  314. byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
  315. byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n");
  316. // 组装文本请求参数
  317. string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
  318. IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
  319. while (textEnum.MoveNext())
  320. {
  321. string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
  322. byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
  323. reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
  324. reqStream.Write(itemBytes, 0, itemBytes.Length);
  325. }
  326. // 组装文件请求参数
  327. string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
  328. IEnumerator<KeyValuePair<string, FileItem>> fileEnum = fileParams.GetEnumerator();
  329. while (fileEnum.MoveNext())
  330. {
  331. string key = fileEnum.Current.Key;
  332. FileItem fileItem = fileEnum.Current.Value;
  333. string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType());
  334. byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(fileEntry);
  335. reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
  336. reqStream.Write(itemBytes, 0, itemBytes.Length);
  337. byte[] fileBytes = fileItem.GetContent();
  338. reqStream.Write(fileBytes, 0, fileBytes.Length);
  339. }
  340. reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  341. reqStream.Close();
  342. HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
  343. Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
  344. return GetResponseAsString(rsp, encoding);
  345. }
  346. public HttpWebRequest GetWebRequest(string url, string method)
  347. {
  348. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  349. req.ServicePoint.Expect100Continue = false;
  350. req.Method = method;
  351. req.KeepAlive = true;
  352. req.Timeout = 100000;
  353. return req;
  354. }
  355. /// <summary>
  356. /// 把响应流转换为文本。
  357. /// </summary>
  358. /// <param name="rsp">响应流对象</param>
  359. /// <param name="encoding">编码方式</param>
  360. /// <returns>响应文本</returns>
  361. public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
  362. {
  363. StringBuilder result = new StringBuilder();
  364. Stream stream = null;
  365. StreamReader reader = null;
  366. try
  367. {
  368. // 以字符流的方式读取HTTP响应
  369. stream = rsp.GetResponseStream();
  370. reader = new StreamReader(stream, encoding);
  371. // 按字符读取并写入字符串缓冲
  372. int ch = -1;
  373. while ((ch = reader.Read()) > -1)
  374. {
  375. // 过滤结束符
  376. char c = (char)ch;
  377. if (c != '\0')
  378. {
  379. result.Append(c);
  380. }
  381. }
  382. }
  383. finally
  384. {
  385. // 释放资源
  386. if (reader != null) reader.Close();
  387. if (stream != null) stream.Close();
  388. if (rsp != null) rsp.Close();
  389. }
  390. return result.ToString();
  391. }
  392. /// <summary>
  393. /// 获取好哒开放平台文件名
  394. /// </summary>
  395. /// <param name="token">上传图片凭证token</param>
  396. /// <param name="value">图片路径</param>
  397. /// <returns></returns>
  398. public string ReturnFileName(string token, string value)
  399. {
  400. Dictionary<string, string> file = new Dictionary<string, string>();
  401. file.Add("fileName", value.Substring(value.LastIndexOf("/")).Trim('/'));
  402. if (string.IsNullOrEmpty(value.Split(',')[0]))
  403. {
  404. return "";
  405. }
  406. FileItem item = new FileItem(function.getPath(value.Split(',')[0]));
  407. Dictionary<string, FileItem> files = new Dictionary<string, FileItem>();
  408. files.Add("file", item);
  409. var upLoadInfo = JsonMapper.ToObject(HaoDaHelper.Instance.DoPost(BoxRequestUrl + "/api/file/v1/upload_file", token, file, files, "utf-8"));
  410. if (upLoadInfo["code"].ToString() == "1")
  411. {
  412. return upLoadInfo["data"]["fileName"].ToString();
  413. }
  414. else
  415. {
  416. return "false";
  417. }
  418. }
  419. #endregion
  420. }
  421. }