Ver Fonte

对接盛大接口

zhuyiyi há 7 meses atrás
pai
commit
ef560a4210

+ 313 - 0
SiteCore/taoObj/CallbackCrypto.cs

@@ -0,0 +1,313 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SiteCore.taoObj
+{
+    using System.Diagnostics.CodeAnalysis;
+    using System.Security.Cryptography;
+    using System.Text;
+
+    namespace WebApi
+    {
+        public class CallbackCrypto
+        {
+            private readonly byte[] _aesKey;
+            private readonly string _clientId;
+
+            //随机字符串字节长度
+            private static readonly int RANDOM_LENGTH = 16;
+
+            /// <summary>
+            /// 构造函数
+            /// </summary>
+            /// <param name="encodingAesKey">开放平台上,开发者设置的EncodingAESKey</param>
+            /// <param name="clientId">开放平台上,应用的clientId</param>
+            /// <exception cref="CallbackCryptoException"></exception>
+            public CallbackCrypto(string encodingAesKey, string clientId)
+            {
+                if (encodingAesKey == null)
+                {
+                    throw new Exception("加密密钥不能为空");
+                }
+
+                _clientId = clientId;
+                _aesKey = Convert.FromBase64String(encodingAesKey);
+            }
+
+            /// <summary>
+            /// 将和开放平台同步的消息体加密,返回加密Map
+            /// </summary>
+            /// <param name="plaintext">传递的消息体明文</param>
+            /// <returns></returns>
+            public Dictionary<string, string> GetEncryptedMap(string plaintext)
+            {
+                return GetEncryptedMap(plaintext, DateTime.Now.Millisecond);
+            }
+
+            /// <summary>
+            /// 将和开放平台同步的消息体加密,返回加密Map
+            /// </summary>
+            /// <param name="plaintext">传递的消息体明文</param>
+            /// <param name="timestamp">时间戳</param>
+            /// <returns></returns>
+            /// <exception cref="CallbackCryptoException"></exception>
+            public Dictionary<string, string> GetEncryptedMap(string plaintext, long timestamp)
+            {
+                if (null == plaintext)
+                {
+                    throw new Exception("加密明文字符串不能为空");
+                }
+
+                var nonce = Utils.GetRandomStr(RANDOM_LENGTH);
+                string encrypt = Encrypt(nonce, plaintext);
+                string signature = GetSignature(timestamp.ToString(), nonce, encrypt);
+
+                return new Dictionary<string, string>()
+                {
+                    ["signature"] = signature,
+                    ["encrypt"] = encrypt,
+                    ["timestamp"] = timestamp.ToString(),
+                    ["nonce"] = nonce
+                };
+            }
+
+            /// <summary>
+            /// 密文解密
+            /// </summary>
+            /// <param name="msgSignature">签名串</param>
+            /// <param name="timestamp">时间戳</param>
+            /// <param name="nonce">随机串</param>
+            /// <param name="encryptMsg">密文</param>
+            /// <returns>解密后的原文</returns>
+            /// <exception cref="CallbackCryptoException"></exception>
+            public string GetDecryptMsg(string msgSignature, string timestamp, string nonce, string encryptMsg)
+            {
+                //校验签名
+                string signature = GetSignature(timestamp, nonce, encryptMsg);
+                if (!signature.Equals(msgSignature))
+                {
+                    throw new Exception("签名不匹配");
+                }
+
+                // 解密
+                return Decrypt(encryptMsg);
+            }
+
+            /// <summary>
+            /// 对明文加密
+            /// </summary>
+            /// <param name="nonce">随机串</param>
+            /// <param name="plaintext">需要加密的明文</param>
+            /// <returns>加密后base64编码的字符串</returns>
+            /// <exception cref="CallbackCryptoException"></exception>
+            private string Encrypt(string nonce, string plaintext)
+            {
+
+                byte[] randomBytes = Encoding.UTF8.GetBytes(nonce);
+                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plaintext);
+                byte[] lengthByte = Utils.Int2Bytes(plainTextBytes.Length);
+                byte[] clientIdBytes = Encoding.UTF8.GetBytes(_clientId);
+
+                var bytestmp = new List<byte>();
+                bytestmp.AddRange(randomBytes);
+                bytestmp.AddRange(lengthByte);
+                bytestmp.AddRange(plainTextBytes);
+                bytestmp.AddRange(clientIdBytes);
+
+                byte[] padBytes = PKCS7Padding.GetPaddingBytes(bytestmp.Count);
+                bytestmp.AddRange(padBytes);
+                byte[] unencrypted = bytestmp.ToArray();
+
+                using (Aes aesAlg = Aes.Create())
+                {
+                    aesAlg.Mode = CipherMode.CBC;
+                    aesAlg.Padding = PaddingMode.Zeros;
+                    aesAlg.Key = _aesKey;
+                    aesAlg.IV = _aesKey.ToList().Take(16).ToArray();
+
+                    // Create an encryptor to perform the stream transform.
+                    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
+
+                    byte[] encrypted = encryptor.TransformFinalBlock(unencrypted, 0, unencrypted.Length);
+                    return Convert.ToBase64String(encrypted, 0, encrypted.Length);
+                }
+            }
+
+            /// <summary>
+            /// 对密文进行解密
+            /// </summary>
+            /// <param name="text">需要解密的密文</param>
+            /// <returns>解密得到的明文</returns>
+            /// <exception cref="CallbackCryptoException"></exception>
+            private string Decrypt(string text)
+            {
+                byte[] originalArr;
+
+                byte[] toEncryptArray = Convert.FromBase64String(text);
+
+                using (Aes aesAlg = Aes.Create())
+                {
+                    aesAlg.Mode = CipherMode.CBC;
+                    aesAlg.Padding = PaddingMode.Zeros;
+                    aesAlg.Key = _aesKey;
+                    aesAlg.IV = _aesKey.ToList().Take(16).ToArray();
+
+                    // Create a decryptor to perform the stream transform.
+                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
+
+                    // Create the streams used for decryption.
+                    originalArr = decryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
+                }
+
+
+                string plaintext;
+                string msgClientId;
+
+                // 去除补位字符
+                byte[] bytes = PKCS7Padding.RemovePaddingBytes(originalArr);
+
+                int plainTextLegth = Utils.Bytes2int(bytes.Skip(RANDOM_LENGTH).Take(4).ToArray());
+
+                plaintext = Encoding.UTF8.GetString(bytes.Skip(RANDOM_LENGTH + 4).Take(plainTextLegth).ToArray());
+                msgClientId = Encoding.UTF8.GetString(bytes.Skip(RANDOM_LENGTH + 4 + plainTextLegth).ToArray());
+
+
+                return !msgClientId.Equals(_clientId)
+                    ? throw new Exception("计算解密文字clientId不匹配")
+                    : plaintext;
+            }
+
+            /// <summary>
+            /// 生成数字签名
+            /// </summary>
+            /// <param name="timestamp">时间戳</param>
+            /// <param name="nonce">随机串</param>
+            /// <param name="encrypt">加密文本</param>
+            /// <returns></returns>
+            /// <exception cref="CallbackCryptoException"></exception>
+            public string GetSignature(string timestamp, string nonce, string encrypt)
+            {
+                string[] array = new string[] { _clientId, timestamp, nonce, encrypt };
+                Array.Sort(array, StringComparer.Ordinal);
+                SHA1 sHA1 = SHA1.Create();
+                byte[] digest = sHA1.ComputeHash(Encoding.ASCII.GetBytes(string.Join(string.Empty, array)));
+
+                StringBuilder hexstr = new StringBuilder();
+                for (int i = 0; i < digest.Length; i++)
+                {
+                    hexstr.Append(((int)digest[i]).ToString("x2"));
+                }
+
+                return hexstr.ToString();
+            }
+        }
+
+        /// <summary>
+        /// 加解密工具类
+        /// </summary>
+        public class Utils
+        {
+            public static string GetRandomStr(int count)
+            {
+                string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+                Random random = new Random();
+                StringBuilder sb = new StringBuilder();
+
+                for (int i = 0; i < count; i++)
+                {
+                    int number = random.Next(chars.Length);
+                    sb.Append(chars[number]);
+                }
+
+                return sb.ToString();
+            }
+
+            /// <summary>
+            /// int转byte数组,高位在前
+            /// </summary>
+            public static byte[] Int2Bytes(int number)
+            {
+                return new byte[]
+                {
+                (byte) (number >> 24 & 0xFF),
+                (byte) (number >> 16 & 0xFF),
+                (byte) (number >> 8 & 0xFF),
+                (byte) (number & 0xFF)
+                };
+            }
+
+            /// <summary>
+            /// 高位在前bytes数组转int
+            /// </summary>
+            public static int Bytes2int(byte[] byteArr)
+            {
+                int count = 0;
+                for (int i = 0; i < 4; ++i)
+                {
+                    count <<= 8;
+                    count |= byteArr[i] & 255;
+                }
+
+                return count;
+            }
+        }
+
+        /// <summary>
+        /// PKCS7算法的加密填充
+        /// </summary>
+        public class PKCS7Padding
+        {
+            private static readonly int BLOCK_SIZE = 32;
+
+            /// <summary>
+            /// 填充mode字节
+            /// </summary>
+            /// <param name="count"></param>
+            public static byte[] GetPaddingBytes(int count)
+            {
+                int amountToPad = BLOCK_SIZE - count % BLOCK_SIZE;
+                if (amountToPad == 0)
+                {
+                    amountToPad = BLOCK_SIZE;
+                }
+
+                char padChr = Chr(amountToPad);
+                string tmp = string.Empty;
+                for (int index = 0; index < amountToPad; index++)
+                {
+                    tmp += padChr;
+                }
+
+                return Encoding.UTF8.GetBytes(tmp);
+            }
+
+            /// <summary>
+            /// 移除mode填充字节
+            /// </summary>
+            /// <param name="decrypted"></param>
+            public static byte[] RemovePaddingBytes(byte[] decrypted)
+            {
+                int pad = decrypted[decrypted.Length - 1];
+                if (pad < 1 || pad > BLOCK_SIZE)
+                {
+                    pad = 0;
+                }
+
+                var output = new byte[decrypted.Length - pad];
+                Array.Copy(decrypted, output, decrypted.Length - pad);
+
+                return output;
+            }
+
+            private static char Chr(int a)
+            {
+                byte target = (byte)(a & 0xFF);
+                return (char)target;
+            }
+        }
+    }
+
+}

+ 23 - 0
SiteCore/taoObj/ShengdaTokenBean.cs

@@ -0,0 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SiteCore.taoObj
+{
+    public class ShengdaTokenBean
+    {
+        public int errCode { get; set; }
+        public string errMsg { get; set; }
+        public TokenBean data { get; set; }
+
+    }
+    public class TokenBean
+    {
+        public string access_token { get; set; }
+        public string token_type { get; set; }
+        public int expires_in { get; set; }
+    }
+
+}

+ 391 - 0
SiteCore/taobao/apiShengda.cs

@@ -0,0 +1,391 @@
+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;
+
+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<string> headers = new List<string>();
+            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<ShengdaTokenBean>(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<JObject>(decryptMsg);
+            string eventType, orderSn, expressCompany, expressName, expressNo;
+            try
+            {
+                eventType = item["eventType"].ToString();
+                orderSn = item["body"]["orderSN"].ToString();
+                Debug.WriteLine("订单号:" + orderSn);
+                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);
+                    }
+                    StringBuilder sb = new StringBuilder();
+
+                    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) //已发货的不处理直接返回面单
+                        {
+                            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));
+                    }
+                    SqlHelper.ExecuteNonQuery(sb.ToString());
+                }
+
+            }
+
+
+            catch (Exception ex)
+            {
+                XLog.SaveLog(0, "盛大数据解析错误:" + msgSignature);
+            }
+
+        }
+
+        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;
+        }
+
+    }
+}

+ 1 - 1
SiteCore/taobao/designHelper.cs

@@ -453,7 +453,7 @@ namespace SiteCore.Handler
                 remoteInfo = Encoding.GetEncoding("utf-8").GetString(ret);
                 if ("orderRemarks".Equals(vo.actionName))
                 {
-                    XLog.SaveLog(0, "API_WorkCore:" + remoteInfo + vo.actionName);
+                    XLog.SaveLog(0, "API_WorkCore:" + vo.orderNumber + "—" + remoteInfo + vo.actionName);
                 }
             }
             catch (Exception ex)

+ 1 - 1
SiteCore/taobao/preSalesHelper.cs

@@ -800,7 +800,7 @@ namespace SiteCore.Handler
                     return;
                 }
                 CeErpTradeCell ceErpTradeCell = null;
-                if (string.IsNullOrEmpty(ctid))
+                if (!string.IsNullOrEmpty(ctid))
                 {
                     ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
                     if (ceErpTradeCell == null)

+ 69 - 0
ecomServer/MainForm.cs

@@ -136,14 +136,17 @@ namespace ErpServer
         int tb_err = 0;
         int bu_err = 0;
         int pre_err = 0;
+        int sd_err = 0;
         int refund_tb_err = 0;
         int refund_bu_err = 0;
         HttpHelper http = null;
         TimerCallback syncTaoBaoBack = null;
         TimerCallback syncPreBack = null;
+        TimerCallback syncSdBack = null;
         TimerCallback syncRefundTB = null;
         System.Threading.Timer disTimer = null;
         System.Threading.Timer preTimer = null;
+        System.Threading.Timer sdTimer = null;
         System.Threading.Timer refundDisTimer = null;
         string paidanSync = "";
         string dinggaolvSync = "";
@@ -185,7 +188,11 @@ namespace ErpServer
                 disTimer = new System.Threading.Timer(syncTaoBaoBack, null, 3000, 3000);
                 syncPreBack = new TimerCallback(syncPreCall);
                 preTimer = new System.Threading.Timer(syncPreBack, null, 3000, 3000);
+                syncSdBack = new TimerCallback(syncSdCall);
+                sdTimer = new System.Threading.Timer(syncSdBack, null, 3000, 3000);
+
             }
+
             //****售后退款推送同步****/
             string refundTBSync = INI.GetIniValue("Config", "refundTbSync", iniFile);
             if (refundTBSync == "1")
@@ -626,6 +633,68 @@ namespace ErpServer
                 preIsGet = false;
             }
         }
+        bool sdIsGet = false;
+        private void syncSdCall(object obj)
+        {
+            if (sdIsGet) return;
+            sdIsGet = true;
+            string sql = "select top 200 * from CE_ErpShengdaRequestData order by id asc";
+            DataTable dt = SqlHelper.ExecuteDataset(sql).Tables[0];
+
+            try
+            {
+                if (dt != null && dt.Rows.Count > 0)
+                {
+                    List<string> idLst = new List<string>();
+                    helper.writeLog(dt.Rows[0]["id"].ToString());
+                    foreach (DataRow dr in dt.Rows)
+                    {
+                        idLst.Add(dr["id"].ToString());
+                        while (true)
+                        {
+                            if (sd_err >= 15)
+                            {
+                                Environment.Exit(0);
+                                return;
+                            }
+                            try
+                            {
+                                apiShengda.dealData(dr["signature"].ToString(), dr["timestamp"].ToString(), dr["nonce"].ToString(), dr["encrypt"].ToString());
+                                sd_err = 0;
+                                break;
+                            }
+                            catch (Exception ex)
+                            {
+                                if (ex.Message.IndexOf("死锁") != -1)
+                                {
+                                    sd_err++;
+                                    helper.writeLog("盛大同步死锁了,继续执行");
+                                    Thread.Sleep(1000);
+                                }
+                                else
+                                {
+                                    XLog.SaveLog(0, dr["message"].ToString() + "------" + ex.Message);
+                                    break;
+                                }
+                            }
+                        }
+                    }
+                    if (idLst.Count > 0)
+                    {
+                        SqlHelper.ExecuteNonQuery("delete from CE_ErpShengdaRequestData where id in (" + string.Join(",", idLst) + ") ;");
+                        helper.writeLog("盛大同步完成" + idLst.Count);
+                    }
+                }
+            }
+            catch (Exception e)
+            {
+
+            }
+            finally
+            {
+                sdIsGet = false;
+            }
+        }
 
         bool refundisGet = false;
         int refund_tbt_count = 0;