using BizCom; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NHibernate.Type; using SiteCore.taoObj; using SQLData; using System; using System.Collections.Generic; using System.Data; using System.Security.Cryptography; using System.Text; using System.Web; using static SiteCore.taoObj.api_userId_response; namespace SiteCore { public class apiHelper { //正式appkey static string appid = "221114"; static string appSecret = "gc5y5of12pz2idvqx2lh4jo6bj5fn0ud"; //测试appkey //static string appid = "221111"; //static string appSecret = "xdxkow01r5uvvpn53tojwuer5laba8zb"; //static string main_url = "http://open_3rd.dev.diansan.com/open/oms/router"; static string main_url = "http://open_3rd.product.diansan.com/open/oms/router"; static string printPage_redirectUrl = "http://d3.diansan.com/d3/open/print/express/index.html"; static HttpHelper tb_http = new HttpHelper(); private static object obj = new object(); #region private private static string SignTopRequest(IDictionary parameters, string jsonPara, string secret, string signMethod, bool notBody = false) { IDictionary sortedParams = new SortedDictionary(parameters, StringComparer.Ordinal); IEnumerator> dem = sortedParams.GetEnumerator(); string str_query = ""; if (signMethod == "md5") { //query.Append(secret); str_query += secret; } while (dem.MoveNext()) { string key = dem.Current.Key; string value = dem.Current.Value; if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) { str_query += key; str_query += value; } } if (notBody == false) { str_query += jsonPara; } byte[] bytes; str_query += secret; MD5 md5 = MD5.Create(); bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(str_query)); StringBuilder result = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { result.Append(bytes[i].ToString("X2")); } return result.ToString(); } private static string Md5(string s) { using (var md5 = MD5.Create()) { var result = md5.ComputeHash(Encoding.Default.GetBytes(s)); var strResult = BitConverter.ToString(result); return strResult.Replace("-", "").ToUpper(); } } public static int DateTimeToUnixTime(DateTime dateTime) { return (int)(dateTime - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds; } #endregion public static string Base_Request(string jsonParams, string methodStr) { int sc = DateTimeToUnixTime(DateTime.Now); Dictionary postParamList = new Dictionary(); postParamList.Add("appKey", appid); postParamList.Add("timestamp", sc.ToString()); postParamList.Add("method", methodStr); //postParamList.Add("_test", "true"); //json参数 List postLst = new List(); string ro_json = jsonParams; string signStr = SignTopRequest(postParamList, ro_json, appSecret, "md5"); postParamList.Add("sign", signStr); //post参数 //postLst.Add("requestObjectJson=" + HttpUtility.UrlEncode(ro_json)); postLst.Add("method=" + methodStr); postLst.Add("appKey=" + appid); postLst.Add("timestamp=" + sc); //postLst.Add("_test=true"); postLst.Add("sign=" + signStr); //postLst.Add("requestObjectJson=" + HttpUtility.UrlEncode(ro_json)); string pUrl = main_url + "?" + string.Join("&", postLst.ToArray()); HttpItem item = new HttpItem() { URL = pUrl, Method = "POST", ContentType = "application/json;charset=UTF-8", Postdata = ro_json }; item.PostEncoding = Encoding.UTF8; HttpResult hResult = null; lock (obj) { hResult = tb_http.GetHtml(item); } return hResult.Html; } public static string Base_Request_SF(string jsonParams, string methodStr) { int sc = DateTimeToUnixTime(DateTime.Now); Dictionary postParamList = new Dictionary(); postParamList.Add("appKey", appid); postParamList.Add("timestamp", sc.ToString()); postParamList.Add("method", methodStr); //postParamList.Add("_test", "true"); List postLst = new List(); string ro_json = jsonParams; string signStr = SignTopRequest(postParamList, ro_json, appSecret, "md5", true); postParamList.Add("sign", signStr); postLst.Add("method=" + methodStr); postLst.Add("appKey=" + appid); postLst.Add("timestamp=" + sc); //postLst.Add("_test=true"); postLst.Add("sign=" + signStr); string pUrl = "http://d3.diansan.com/app-web/open/router/rest.json" + "?" + string.Join("&", postLst.ToArray()); HttpItem item = new HttpItem() { URL = pUrl, Method = "POST", ContentType = "application/json;charset=UTF-8", Postdata = ro_json }; item.PostEncoding = Encoding.UTF8; HttpResult hResult = tb_http.GetHtml(item); return hResult.Html; } public static string API_TradeFullinfoGet(string tid, string sTime = "", string eTime = "") { //json参数 List postLst = new List(); object jsonPara = null; if (tid.Length > 0) { var res_obj = new { refOid = tid, timeType = 2 }; jsonPara = res_obj; } else { var res_obj = new { startTime = sTime, endTime = eTime, timeType = 2 }; jsonPara = res_obj; } string ro_json = JsonConvert.SerializeObject(jsonPara); string res = Base_Request(ro_json, "ds.omni.erp.third.order.query"); return res; //return html; } public static string API_TradeMemoUpdate(string atid, string pCode, string aflag, string amemo) { var res_obj = new { refOid = atid, flag = aflag, memo = amemo, posCode = pCode }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.omni.erp.third.order.memo.update"); return res; } public static string API_LogisticsOnlineSend(string orderid, string pCode, string comCode, string out_Sid, string ctid) { List postLst = new List(); DataTable dt_item = DbHelper.DbConn.ExecuteDataset(string.Format("SELECT oid, sku_id, num FROM [dbo].[CE_ErpTradeOrder] WHERE tid = '{0}'", orderid)).Tables[0]; var res_obj = new { refOid = orderid, posCode = pCode, packages = new[] { new{ outSid = out_Sid, companyCode = comCode, lines = dt_item.AsEnumerable().Select(row => new { refOlId = row["oid"], refSkuId = row["sku_id"], num = row["num"] }) } } }; string ro_json = JsonConvert.SerializeObject(res_obj); string sql = string.Format("SELECT tid FROM [dbo].[CE_ErpTradeCell] WHERE tid = '{0}' and OrderState > 6", orderid); DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0]; string send_api = "ds.omni.erp.third.order.send"; if (dt != null && dt.Rows.Count > 0) { send_api = "ds.omni.erp.third.order.uploadExtraLogistics";//额外发货 XLog.SaveLog(0, "额外发货:" + orderid + "-" + comCode + "-" + out_Sid); } string res = Base_Request(ro_json, send_api); if (res.Contains("上传额外运单信息成功")) { res = res.Replace("上传额外运单信息成功", "发货成功true"); } return res; } public static string API_LogisticsDummySend(string orderid, string pCode) { List postLst = new List(); var res_obj = new { refOid = orderid, posCode = pCode }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.omni.erp.third.order.dummy.send"); return res; } public static string API_PrintTemplate() { List postLst = new List(); var res_obj = new { templateType = "EXPRESS", templateSource = "CAINIAO" }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.omni.erp.print.template.query"); return res; } public static string API_GetWaybill(string cpCd, string ctid) { string sql = "select * from view_erptradecell where ctid='" + ctid + "'"; DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0]; if (dt != null && dt.Rows.Count > 0) { List postLst = new List(); Object receipts = null; string pos_code = dt.Rows[0]["posCode"].ToString(); if (ctid.IndexOf("N") != -1) { pos_code = "guliang"; receipts = new { province = dt.Rows[0]["receiver_state"].ToString(), city = dt.Rows[0]["receiver_city"].ToString(), district = dt.Rows[0]["receiver_district"].ToString(), town = dt.Rows[0]["receiver_town"].ToString(), detail = dt.Rows[0]["receiver_address"].ToString(), name = dt.Rows[0]["receiver_name"].ToString(), mobile = dt.Rows[0]["receiver_mobile"].ToString(), phone = dt.Rows[0]["receiver_phone"].ToString() }; } var res_obj = new { cpCode = cpCd, packages = new[] { new{ outerCode = dt.Rows[0]["ctid"].ToString(), posCode= pos_code, refOid = dt.Rows[0]["tid"].ToString(), items = new[] { new{ name = "印刷品", num = 1 } }, receipt = receipts == null?new{ }:receipts } } }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.omni.erp.waybill.third.get"); return res; } return ""; } public static string API_GetPrintData(string waybill) { List postLst = new List(); var res_obj = new { waybillCode = new[] { waybill } }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.omni.erp.waybill.printdata.get"); return res; } public static string Api_SyncOrderByTime(string posId) { List postLst = new List(); string starttime = DateTime.Now.AddMinutes(-35).ToString("yyyy-MM-dd HH:mm:ss"); string endtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var res_obj = new { startTime = starttime, endTime = endtime, timeType = "CREATE_TIME", posId = posId }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.omni.erp.third.order.sync.byTime"); return res; } public static string API_GetPrintData_SF(string waybill) { List postLst = new List(); var res_obj = new { request = new { waybillCodes = new[] { waybill } } }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request_SF(ro_json, "omni.print.open.appOpenPrintData.getExpressList"); return res; } public static string API_GetPrintPage(string waybillCode, string tempId, string reqId) { string appKey = appid; string secret = appSecret; List postLst = new List(); postLst.Add("waybillCodeList=" + waybillCode); postLst.Add("templateId=" + tempId); postLst.Add("requestId=" + reqId); postLst.Add("sourceType=THIRD_ORDER"); int sc = DateTimeToUnixTime(DateTime.Now); string redPageUrl = printPage_redirectUrl + "?" + string.Join("&", postLst.ToArray()); string en_redPageUrl = HttpUtility.UrlEncode(redPageUrl); string toSignStr = secret + "appKey" + appKey + "redirectUrl" + en_redPageUrl + "timestamp" + sc + secret; MD5 md5 = MD5.Create(); byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(toSignStr)); StringBuilder result = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { result.Append(bytes[i].ToString("x2")); } string sign = result.ToString(); string toAuthUrl = "http://d3.diansan.com/app-web/open/tenant/auth?appKey=" + appKey + "&redirectUrl=" + en_redPageUrl + "×tamp=" + sc + "&sign=" + sign; return toAuthUrl; } public static string API_CancelPrint(string waybillCode) { var res_obj = new { waybillCode }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.omni.erp.waybill.third.cancel"); return res; } public static List API_GetUserId(string waybillCode, string nickName) { var res_obj = new { posCode = waybillCode, buyerNicks = nickName }; string ro_json = JsonConvert.SerializeObject(res_obj); string res = Base_Request(ro_json, "ds.tb.user.openuid.get"); List resultList = new List(); if (res == "") { return resultList; } try { api_userId_response api = JsonConvert.DeserializeObject(res); if (api != null && api.response.code == 200 && api.response.data.content != null && api.response.data.content.Count > 0) { resultList = api.response.data.content; } } catch (Exception ex) { } return resultList; } } }