apiShengda.cs 17 KB

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