using BizCom; using Microsoft.SqlServer.Server; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NHibernate.Cache; using SiteCore.Handler; using SiteCore.taoObj; using SiteCore.taoObj.WebApi; using SQLData; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Net.Http; using System.Reflection; using System.Security.Cryptography.Xml; using System.Security.Policy; using System.Text; using System.Threading.Tasks; using System.Web; using static SiteCore.taoObj.Api_trade_info; using System.Text.RegularExpressions; using NPOI.OpenXmlFormats.Shared; namespace SiteCore.Handler { public class apiShengda : BaseHandler, IHttpHandler { public void ProcessRequest(HttpContext context) { if (UrlParmsCheck("t")) { String tname = GetString("t"); MethodInfo method; Type type = this.GetType(); method = type.GetMethod(tname); con = context; if (method == null) { conError("找不到对应方法,服务器返回错误"); return; } successFlag = false; context.Response.ContentType = "application/json"; context.Response.Headers.Set("Access-Control-Allow-Origin", "*"); try { method.Invoke(this, null); } catch (Exception ex) { conError("处理接口错误,服务器返回错误"); } finally { //AfterInvoke(methodName); } //if (!successFlag) returnErrorMsg("服务器返回错误"); } } static string pUrl = "https://open.sd2000.com/"; static string appId = "3a1ab376af58ec4e918b4c506480efdf"; static string appSercies = "h2kqXPalWb17Zl6TRkFEJrecxJg0Y8kiob6jhzWoCilQ943Wp6iunr3GdUgUSPR2"; static string EncodingAESKey = "F2yZXfKXFRMqRrWDaD8pGw=="; /*static string appId = "3a1a27fd3e4ad50701dabf830697e9ea"; static string appSercies = "MqgrQWjcFGCAPaHRP72Rg4HyNwt9WIU85zIGvK1KErOFV5oylJdHYToTr9iT76KF"; static string EncodingAESKey = "cig3Ax4wI9I1H9SlvCgPUQ==";*/ public static string getToken() { //return "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYXBpIl0sInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJleHAiOjE3MzU5NjU0ODAsImF1dGhvcml0aWVzIjpbIm9wZW5hcGkiXSwianRpIjoiYjY4NTRhZjctZjNmMy00OTU0LTk4ZmUtZDRlZTE4ZDllNzQyIiwiY2xpZW50X2lkIjoieGNsaWVudCJ9.E6U0NVMZPcUypl4P7L5718J1X8UxSJg9R7vZX_oMkuEJ-yelNXuYwu7-eAi1JTgIJ0GuuviQu-KEAH-W7sHb7t-JJJc-wLPMsLKmpwQDG2EpiRK5hW5ZmyUgL8rPuTUawKVP5k8SGrN60sVyXA2zKm4ztEQ39EGudXnam1Lld2w"; string token = ""; if (RedisHelper.HasKey("shengda_token")) { token = RedisHelper.StringGet("shengda_token").ToString(); { return token; } } string post_url = pUrl + "api/auth/token"; WebClient wc = new WebClient(); wc.Encoding = Encoding.GetEncoding("utf-8"); List headers = new List(); headers.Add("appid=" + appId); headers.Add("secret=" + appSercies); post_url += "?" + string.Join("&", headers); NameValueCollection PostVars = new NameValueCollection(); string remoteInfo = ""; try { remoteInfo = wc.DownloadString(post_url); ShengdaTokenBean shengdaTokenBean = JsonConvert.DeserializeObject(remoteInfo); token = shengdaTokenBean.data.access_token; TimeSpan timeSpan = TimeSpan.FromSeconds(shengdaTokenBean.data.expires_in - 5); RedisHelper.StringSet("shengda_token", token, timeSpan); } catch (Exception ex) { Debug.WriteLine(ex.Message); } return token; } public static string orderSnGet(string orderSN) { string ctid = string.Empty; if (string.IsNullOrEmpty(orderSN)) { return ctid; } string postUrl = pUrl + "api/app/order?orderSN=" + orderSN; try { string result = httpContent(postUrl, "", HttpMethod.Get); var item = JsonConvert.DeserializeAnonymousType(result, new { data = new { name = "" } }); string file_name = ""; if (item != null) { file_name = item.data.name; } if (string.IsNullOrEmpty(file_name)) { return ctid; } string namePattern = @"《(.*?)》"; Regex nameReg = new Regex(namePattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时 MatchCollection nameMatches = nameReg.Matches(file_name);//设定要查找的字符串 if (nameMatches.Count > 0) { foreach (Match match in nameMatches) { file_name = file_name.Replace(match.Value, ""); } } file_name = file_name.Replace("(", "("); file_name = file_name.Replace(")", ")"); ctid = MidStrEx(file_name, "(", ")").Trim(); } catch (Exception ex) { } return ctid; } public static string MidStrEx(string sourse, string startstr, string endstr) { string result = string.Empty; int startindex, endindex; try { startindex = sourse.IndexOf(startstr); if (startindex == -1) return result; string tmpstr = sourse.Substring(startindex + startstr.Length); endindex = tmpstr.IndexOf(endstr); if (endindex == -1) return result; result = tmpstr.Remove(endindex); } catch (Exception ex) { Console.WriteLine("MidStrEx Err:" + ex.Message); } return result; } public void orderCallBack() { string msgSignature = GetString("signature"); string timeStamp = GetString("timestamp"); string nonce = GetString("nonce"); string encrypt = ""; try { using (var reader = new StreamReader(HttpContext.Current.Request.GetBufferedInputStream(), Encoding.UTF8)) { var content = reader.ReadToEnd(); var item = JsonConvert.DeserializeAnonymousType(content, new { encrypt = "" }); encrypt = item.encrypt; } string sql = string.Format("insert into CE_ErpShengdaRequestData(signature,timestamp,nonce,encrypt,createtime) values('{0}','{1}','{2}','{3}',getdate()) ;" + "insert into CE_ErpShengdaRequestDataBack(signature,timestamp,nonce,encrypt,createtime,type) values('{0}','{1}','{2}','{3}',getdate(),'1') ;", msgSignature, timeStamp, nonce, encrypt); XLog.ExecuteNonQuery(sql); } catch (Exception ex) { XLog.SaveLog(0, "盛大回调出错" + ex.Message); } HttpContext.Current.Response.Write("success"); return; } public static void dealData(string msgSignature, string timeStamp, string nonce, string encrypt) { CallbackCrypto callbackCrypto = new CallbackCrypto(EncodingAESKey, appId); string decryptMsg = callbackCrypto.GetDecryptMsg(msgSignature, timeStamp, nonce, encrypt); JObject item = JsonConvert.DeserializeObject(decryptMsg); string eventType, orderSn, expressCompany, expressName, expressNo; int status = 0; StringBuilder sb = new StringBuilder(); try { status = Convert.ToInt16(item["body"]["status"]); if (status != 4) { return; } eventType = item["eventType"].ToString(); orderSn = item["body"]["orderSN"].ToString(); expressCompany = item["body"]["extra"]["expressCompany"].ToString(); expressName = item["body"]["extra"]["expressName"].ToString(); expressNo = item["body"]["extra"]["expressNo"].ToString(); string ctid = orderSnGet(orderSn); if (!string.IsNullOrEmpty(ctid)) { CeErpTradeCell entity = CeErpTradeCell.GetByCode(ctid); if (entity == null) { entity = CeErpTradeCell.GetByCtid(ctid); } if (entity != null && entity.SupplierId == 7) { 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)); CeErpTrade mainEn = CeErpTrade.Get(entity.tid); string apires = ""; string supplierName = commonHelper.getSupplierNameById(entity.SupplierId); //物流编号 string cpCode = ""; if ("ZTO".Equals(expressName) && expressCompany.IndexOf("中通") > -1) { cpCode = "ZTO-SD"; } if ("PADTF".Equals(expressName) && expressCompany.IndexOf("") > -1) { cpCode = "PADTF-SD"; } if ("YTO".Equals(expressName) && expressCompany.IndexOf("圆通") > -1) { cpCode = "YTO-SD"; } if ("SF".Equals(expressName) && expressCompany.IndexOf("到付") > -1) { cpCode = "SF-SD"; } if (ctid.IndexOf("N") != -1) { apires = "发货成功"; } else { apires = apiHelper.API_LogisticsOnlineSend(mainEn.tid, mainEn.posCode, cpCode, expressNo); } string userName = "盛大接口"; if (mainEn != null && entity.OrderState <= 6 && apires.IndexOf("发货成功") != -1) { try { entity.OutSid = expressNo; entity.OrderState = 7; entity.IsUrgency = false; entity.LastBillCpCode = ""; entity.LastBillWaybillCode = ""; entity.FinishDeliveryTime = DateTime.Now; entity.IsReturn = 0; entity.MemoOpt = 0; entity.UpdateTime = DateTime.Now; entity.Update(); commonHelper.aftersaleSend(entity.ctid, cpCode, expressNo); //还要插入快递信息到 快递信息表 CeErpExpressInfo exinfo = new CeErpExpressInfo(); exinfo.tid = entity.ctid; exinfo.out_sid = expressNo; exinfo.company_code = cpCode; exinfo.company_name = expressCompany; exinfo.supplierUserName = supplierName; exinfo.deliveryType = "发货成功"; exinfo.print_time = DateTime.Now; exinfo.printUser = userName; exinfo.postData = ""; exinfo.Create(); commonHelper.UpdateRelationOrder(entity.ctid); CeErpSukuraData.createInfo(ctid, 4); commonHelper.insertToBuchaForDelivery(mainEn.tid, mainEn.posCode, cpCode, expressNo); } catch (Exception ex) { XLog.SaveLog(0, "盛大接口发货成功后更新数据失败," + ex.Message); } } else if (mainEn.status == "SHIPPED" || mainEn.status == "PART_SHIPPED" || entity.OrderState >= 7) //已发货的不处理直接返回面单 { if (string.IsNullOrEmpty(entity.OutSid) || entity.OutSid.IndexOf(expressNo) == -1) { entity.OutSid = (entity.OutSid + "," + expressNo); if (entity.OrderState == 6) { entity.OrderState = 7; } entity.UpdateTime = DateTime.Now; entity.FinishDeliveryTime = DateTime.Now; entity.Update(); CeErpExpressInfo exinfo = new CeErpExpressInfo(); exinfo.tid = entity.ctid; exinfo.out_sid = expressNo; exinfo.company_code = cpCode; exinfo.company_name = expressCompany; exinfo.supplierUserName = supplierName; exinfo.deliveryType = "发货成功"; exinfo.print_time = DateTime.Now; exinfo.printUser = userName; exinfo.postData = ""; exinfo.Create(); commonHelper.UpdateRelationOrder(entity.ctid); CeErpSukuraData.createInfo(entity.ctid, 4); } } else { entity.UpdateTime = DateTime.Now; entity.LastBillCpCode = cpCode; entity.LastBillWaybillCode = expressNo; entity.Update(); 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)); } } else { sb.AppendLine(string.Format("update [dbo].[CE_ErpShengdaRequestDataBack] set message = '查不到对应订单:{0}' where signature='{1}' and timestamp='{2}';", ctid, msgSignature, timeStamp)); } } } catch (Exception ex) { sb.AppendLine(string.Format("update [dbo].[CE_ErpShengdaRequestDataBack] set message = '数据解析错误:{0}' where signature='{1}' and timestamp='{2}';", ex.Message, msgSignature, timeStamp)); XLog.SaveLog(0, "盛大数据解析错误:" + msgSignature); } SqlHelper.ExecuteNonQuery(sb.ToString()); } static HttpClient client = new HttpClient(); private static string httpContent(string post_url, string content, HttpMethod method) { string token = getToken(); var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(post_url), Headers = { { "Authorization", "Bearer " + token }, { "ContentType", "application/json" }, }, }; var task = Task.Run(() => { try { var response = client.SendAsync(request).Result; response.EnsureSuccessStatusCode(); return response.Content.ReadAsStringAsync().Result; } catch (Exception e) { return ""; } }); return task.Result; } } }