apiShengda.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using BizCom;
  2. using Microsoft.SqlServer.Server;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5. using NHibernate.Cache;
  6. using SiteCore.Handler;
  7. using SiteCore.taoObj;
  8. using SiteCore.taoObj.WebApi;
  9. using SQLData;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Collections.Specialized;
  13. using System.Data;
  14. using System.Diagnostics;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Net;
  18. using System.Net.Http.Headers;
  19. using System.Net.Http;
  20. using System.Reflection;
  21. using System.Security.Cryptography.Xml;
  22. using System.Security.Policy;
  23. using System.Text;
  24. using System.Threading.Tasks;
  25. using System.Web;
  26. using static SiteCore.taoObj.Api_trade_info;
  27. using System.Text.RegularExpressions;
  28. using NPOI.OpenXmlFormats.Shared;
  29. namespace SiteCore.Handler
  30. {
  31. public class apiShengda : BaseHandler, IHttpHandler
  32. {
  33. public void ProcessRequest(HttpContext context)
  34. {
  35. if (UrlParmsCheck("t"))
  36. {
  37. String tname = GetString("t");
  38. MethodInfo method;
  39. Type type = this.GetType();
  40. method = type.GetMethod(tname);
  41. con = context;
  42. if (method == null)
  43. {
  44. conError("找不到对应方法,服务器返回错误");
  45. return;
  46. }
  47. successFlag = false;
  48. context.Response.ContentType = "application/json";
  49. context.Response.Headers.Set("Access-Control-Allow-Origin", "*");
  50. try
  51. {
  52. method.Invoke(this, null);
  53. }
  54. catch (Exception ex)
  55. {
  56. conError("处理接口错误,服务器返回错误");
  57. }
  58. finally
  59. {
  60. //AfterInvoke(methodName);
  61. }
  62. //if (!successFlag) returnErrorMsg("服务器返回错误");
  63. }
  64. }
  65. static string pUrl = "https://open.sd2000.com/";
  66. static string appId = "3a1c4f356fa162581b6d0590284afbd3";
  67. static string appSercies = "e06KAvT6ugHpQd5zjHukfMJBH0dxfA74gWk9o1lsLqOMTYExFVvWuTh0twMQvNBF";
  68. static string EncodingAESKey = "FQevRbA1TWi19UMc7+ownw==";
  69. /*static string appId = "3a1ab376af58ec4e918b4c506480efdf";
  70. static string appSercies = "h2kqXPalWb17Zl6TRkFEJrecxJg0Y8kiob6jhzWoCilQ943Wp6iunr3GdUgUSPR2";
  71. static string EncodingAESKey = "F2yZXfKXFRMqRrWDaD8pGw==";*/
  72. /*static string appId = "3a1a27fd3e4ad50701dabf830697e9ea";
  73. static string appSercies = "MqgrQWjcFGCAPaHRP72Rg4HyNwt9WIU85zIGvK1KErOFV5oylJdHYToTr9iT76KF";
  74. static string EncodingAESKey = "cig3Ax4wI9I1H9SlvCgPUQ==";*/
  75. public void apiGetToken()
  76. {
  77. ReturnSuccess(JsonConvert.SerializeObject(getToken()));
  78. return;
  79. }
  80. public static string getToken()
  81. {
  82. //return "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYXBpIl0sInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJleHAiOjE3MzU5NjU0ODAsImF1dGhvcml0aWVzIjpbIm9wZW5hcGkiXSwianRpIjoiYjY4NTRhZjctZjNmMy00OTU0LTk4ZmUtZDRlZTE4ZDllNzQyIiwiY2xpZW50X2lkIjoieGNsaWVudCJ9.E6U0NVMZPcUypl4P7L5718J1X8UxSJg9R7vZX_oMkuEJ-yelNXuYwu7-eAi1JTgIJ0GuuviQu-KEAH-W7sHb7t-JJJc-wLPMsLKmpwQDG2EpiRK5hW5ZmyUgL8rPuTUawKVP5k8SGrN60sVyXA2zKm4ztEQ39EGudXnam1Lld2w";
  83. string token = "";
  84. if (RedisHelper.HasKey("shengda_token"))
  85. {
  86. token = RedisHelper.StringGet("shengda_token").ToString();
  87. {
  88. return token;
  89. }
  90. }
  91. string post_url = pUrl + "api/auth/token";
  92. WebClient wc = new WebClient();
  93. wc.Encoding = Encoding.GetEncoding("utf-8");
  94. List<string> headers = new List<string>();
  95. headers.Add("appid=" + appId);
  96. headers.Add("secret=" + appSercies);
  97. post_url += "?" + string.Join("&", headers);
  98. NameValueCollection PostVars = new NameValueCollection();
  99. string remoteInfo = "";
  100. try
  101. {
  102. remoteInfo = wc.DownloadString(post_url);
  103. ShengdaTokenBean shengdaTokenBean = JsonConvert.DeserializeObject<ShengdaTokenBean>(remoteInfo);
  104. token = shengdaTokenBean.data.access_token;
  105. TimeSpan timeSpan = TimeSpan.FromSeconds(shengdaTokenBean.data.expires_in - 5);
  106. RedisHelper.StringSet("shengda_token", token, timeSpan);
  107. }
  108. catch (Exception ex)
  109. {
  110. Debug.WriteLine(ex.Message);
  111. }
  112. return token;
  113. }
  114. public static string orderSnGet(string orderSN)
  115. {
  116. string ctid = string.Empty;
  117. if (string.IsNullOrEmpty(orderSN))
  118. {
  119. return ctid;
  120. }
  121. string postUrl = pUrl + "api/app/order?orderSN=" + orderSN;
  122. try
  123. {
  124. string result = httpContent(postUrl, "", HttpMethod.Get);
  125. XLog.SaveLog(0, "盛大回调查询订单" + result);
  126. var item = JsonConvert.DeserializeAnonymousType(result, new { data = new { name = "" } });
  127. string file_name = "";
  128. if (item != null)
  129. {
  130. file_name = item.data.name;
  131. }
  132. if (string.IsNullOrEmpty(file_name))
  133. {
  134. return ctid;
  135. }
  136. string namePattern = @"《(.*?)》";
  137. Regex nameReg = new Regex(namePattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
  138. MatchCollection nameMatches = nameReg.Matches(file_name);//设定要查找的字符串
  139. if (nameMatches.Count > 0)
  140. {
  141. foreach (Match match in nameMatches)
  142. {
  143. file_name = file_name.Replace(match.Value, "");
  144. }
  145. }
  146. file_name = file_name.Replace("(", "(");
  147. file_name = file_name.Replace(")", ")");
  148. ctid = MidStrEx(file_name, "(", ")").Trim();
  149. }
  150. catch (Exception ex)
  151. {
  152. XLog.SaveLog(0, "盛大回调查询订单出错" + ex.Message);
  153. }
  154. return ctid;
  155. }
  156. public static string MidStrEx(string sourse, string startstr, string endstr)
  157. {
  158. string result = string.Empty;
  159. int startindex, endindex;
  160. try
  161. {
  162. startindex = sourse.IndexOf(startstr);
  163. if (startindex == -1)
  164. return result;
  165. string tmpstr = sourse.Substring(startindex + startstr.Length);
  166. endindex = tmpstr.IndexOf(endstr);
  167. if (endindex == -1)
  168. return result;
  169. result = tmpstr.Remove(endindex);
  170. }
  171. catch (Exception ex)
  172. {
  173. Console.WriteLine("MidStrEx Err:" + ex.Message);
  174. }
  175. return result;
  176. }
  177. public void orderCallBack()
  178. {
  179. string msgSignature = GetString("signature");
  180. string timeStamp = GetString("timestamp");
  181. string nonce = GetString("nonce");
  182. string encrypt = "";
  183. try
  184. {
  185. using (var reader = new StreamReader(HttpContext.Current.Request.GetBufferedInputStream(), Encoding.UTF8))
  186. {
  187. var content = reader.ReadToEnd();
  188. var item = JsonConvert.DeserializeAnonymousType(content, new { encrypt = "" });
  189. encrypt = item.encrypt;
  190. }
  191. string sql = string.Format("insert into CE_ErpShengdaRequestData(signature,timestamp,nonce,encrypt,createtime) values('{0}','{1}','{2}','{3}',getdate()) ;" +
  192. "insert into CE_ErpShengdaRequestDataBack(signature,timestamp,nonce,encrypt,createtime,type) values('{0}','{1}','{2}','{3}',getdate(),'1') ;",
  193. msgSignature, timeStamp, nonce, encrypt);
  194. XLog.ExecuteNonQuery(sql);
  195. }
  196. catch (Exception ex)
  197. {
  198. XLog.SaveLog(0, "盛大回调出错" + ex.Message);
  199. }
  200. HttpContext.Current.Response.Write("success");
  201. return;
  202. }
  203. public static void dealData(string msgSignature, string timeStamp, string nonce, string encrypt)
  204. {
  205. CallbackCrypto callbackCrypto = new CallbackCrypto(EncodingAESKey, appId);
  206. string decryptMsg = callbackCrypto.GetDecryptMsg(msgSignature, timeStamp, nonce, encrypt);
  207. JObject item = JsonConvert.DeserializeObject<JObject>(decryptMsg);
  208. string eventType, orderSn, expressCompany, expressName, expressNo;
  209. int status = 0;
  210. StringBuilder sb = new StringBuilder();
  211. try
  212. {
  213. status = Convert.ToInt16(item["body"]["status"]);
  214. if (status != 4)
  215. {
  216. return;
  217. }
  218. eventType = item["eventType"].ToString();
  219. orderSn = item["body"]["orderSN"].ToString();
  220. expressCompany = item["body"]["extra"]["expressCompany"].ToString();
  221. expressName = item["body"]["extra"]["expressName"].ToString();
  222. expressNo = item["body"]["extra"]["expressNo"].ToString();
  223. string ctid = orderSnGet(orderSn);
  224. if (!string.IsNullOrEmpty(ctid))
  225. {
  226. CeErpTradeCell entity = CeErpTradeCell.GetByCode(ctid);
  227. if (entity == null)
  228. {
  229. entity = CeErpTradeCell.GetByCtid(ctid);
  230. }
  231. if (entity != null && entity.SupplierId == 7)
  232. {
  233. sb.AppendLine(string.Format("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid = '{0}' ;", entity.ctid, (int)OrderState.下单完成, 0, "盛大接口发货:" + expressCompany + "-" + expressNo));
  234. CeErpTrade mainEn = CeErpTrade.Get(entity.tid);
  235. string apires = "";
  236. string supplierName = commonHelper.getSupplierNameById(entity.SupplierId);
  237. //物流编号
  238. string cpCode = "";
  239. if ("ZTO".Equals(expressName) && expressCompany.IndexOf("中通") > -1)
  240. {
  241. cpCode = "ZTO-SD";
  242. }
  243. if ("PADTF".Equals(expressName) && expressCompany.IndexOf("") > -1)
  244. {
  245. cpCode = "PADTF-SD";
  246. }
  247. if ("YTO".Equals(expressName) && expressCompany.IndexOf("圆通") > -1)
  248. {
  249. cpCode = "YTO-SD";
  250. }
  251. if ("SF".Equals(expressName))
  252. {
  253. cpCode = "SF-SD";
  254. }
  255. if (ctid.IndexOf("N") != -1)
  256. {
  257. apires = "发货成功";
  258. }
  259. else
  260. {
  261. apires = apiHelper.API_LogisticsOnlineSend(mainEn.tid, mainEn.posCode, cpCode, expressNo, entity.ctid);
  262. }
  263. string userName = "盛大接口";
  264. if (mainEn != null && entity.OrderState <= 6 && apires.IndexOf("发货成功") != -1)
  265. {
  266. try
  267. {
  268. entity.OutSid = expressNo;
  269. entity.OrderState = 7;
  270. entity.IsUrgency = false;
  271. entity.LastBillCpCode = "";
  272. entity.LastBillWaybillCode = "";
  273. entity.FinishDeliveryTime = DateTime.Now;
  274. entity.IsReturn = 0;
  275. entity.MemoOpt = 0;
  276. entity.UpdateTime = DateTime.Now;
  277. entity.Update();
  278. commonHelper.aftersaleSend(entity.ctid, cpCode, expressNo);
  279. //还要插入快递信息到 快递信息表
  280. CeErpExpressInfo exinfo = new CeErpExpressInfo();
  281. exinfo.tid = entity.ctid;
  282. exinfo.out_sid = expressNo;
  283. exinfo.company_code = cpCode;
  284. exinfo.company_name = expressCompany;
  285. exinfo.supplierUserName = supplierName;
  286. exinfo.deliveryType = "发货成功";
  287. exinfo.print_time = DateTime.Now;
  288. exinfo.printUser = userName;
  289. exinfo.postData = "";
  290. exinfo.Create();
  291. commonHelper.UpdateRelationOrder(entity.ctid);
  292. CeErpSukuraData.createInfo(ctid, 4);
  293. commonHelper.insertToBuchaForDelivery(mainEn.tid, mainEn.posCode, cpCode, expressNo);
  294. }
  295. catch (Exception ex)
  296. {
  297. XLog.SaveLog(0, "盛大接口发货成功后更新数据失败," + ex.Message);
  298. }
  299. }
  300. else if (mainEn.status == "SHIPPED" || mainEn.status == "PART_SHIPPED" || entity.OrderState >= 7) //已发货的不处理直接返回面单
  301. {
  302. if (string.IsNullOrEmpty(entity.OutSid) || entity.OutSid.IndexOf(expressNo) == -1)
  303. {
  304. entity.OutSid = (entity.OutSid + "," + expressNo);
  305. if (entity.OrderState == 6)
  306. {
  307. entity.OrderState = 7;
  308. }
  309. entity.UpdateTime = DateTime.Now;
  310. entity.FinishDeliveryTime = DateTime.Now;
  311. entity.Update();
  312. CeErpExpressInfo exinfo = new CeErpExpressInfo();
  313. exinfo.tid = entity.ctid;
  314. exinfo.out_sid = expressNo;
  315. exinfo.company_code = cpCode;
  316. exinfo.company_name = expressCompany;
  317. exinfo.supplierUserName = supplierName;
  318. exinfo.deliveryType = "发货成功";
  319. exinfo.print_time = DateTime.Now;
  320. exinfo.printUser = userName;
  321. exinfo.postData = "";
  322. exinfo.Create();
  323. commonHelper.UpdateRelationOrder(entity.ctid);
  324. CeErpSukuraData.createInfo(entity.ctid, 4);
  325. }
  326. }
  327. else
  328. {
  329. entity.UpdateTime = DateTime.Now;
  330. entity.LastBillCpCode = cpCode;
  331. entity.LastBillWaybillCode = expressNo;
  332. entity.Update();
  333. sb.AppendLine(string.Format("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid = '{0}' ;", entity.ctid, (int)OrderState.下单完成, 0, "盛大接口发货失败:" + expressCompany + "-" + expressNo + "。发货失败:" + apires));
  334. }
  335. }
  336. else
  337. {
  338. sb.AppendLine(string.Format("update [dbo].[CE_ErpShengdaRequestDataBack] set message = '查不到对应订单:{0}' where signature='{1}' and timestamp='{2}';", ctid, msgSignature, timeStamp));
  339. }
  340. }
  341. }
  342. catch (Exception ex)
  343. {
  344. sb.AppendLine(string.Format("update [dbo].[CE_ErpShengdaRequestDataBack] set message = '数据解析错误:{0}' where signature='{1}' and timestamp='{2}';", ex.Message, msgSignature, timeStamp));
  345. XLog.SaveLog(0, "盛大数据解析错误:" + msgSignature);
  346. }
  347. if (sb.Length > 0)
  348. {
  349. SqlHelper.ExecuteNonQuery(sb.ToString());
  350. }
  351. }
  352. static HttpClient client = new HttpClient();
  353. private static string httpContent(string post_url, string content, HttpMethod method)
  354. {
  355. string token = getToken();
  356. var request = new HttpRequestMessage
  357. {
  358. Method = HttpMethod.Get,
  359. RequestUri = new Uri(post_url),
  360. Headers =
  361. {
  362. { "Authorization", "Bearer " + token },
  363. { "ContentType", "application/json" },
  364. },
  365. };
  366. var task = Task.Run(() =>
  367. {
  368. try
  369. {
  370. var response = client.SendAsync(request).Result;
  371. response.EnsureSuccessStatusCode();
  372. return response.Content.ReadAsStringAsync().Result;
  373. }
  374. catch (Exception e)
  375. {
  376. return "";
  377. }
  378. });
  379. return task.Result;
  380. }
  381. }
  382. }