using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; using NetLibrary.OnlineTrade; using NetLibrary; using System.Web.Script.Serialization; namespace TradeManageNew { public class ShopeeApi { /// /// 是否测试 默认false正式 false正式 true测试 /// private bool IsTest = false; public int Partner_Id = 0; public string Partner_Key = ""; public int shopid = 0; /// /// 域名 /// public string HostUrl = ""; //public ShopeeApi(bool isTest = false) //{ // IsTest = isTest; // if (!IsTest) { // HostUrl = "https://partner.shopeemobile.com"; // Partner_Id = 846936; // Partner_Key = "660400cc224f0cfef1fcd409f9ccfe57c507c3be9bf173592fc8c9bc01e6b150"; // } // else { // HostUrl = "https://partner.uat.shopeemobile.com";//测试 // Partner_Id = 845572; // Partner_Key = "e2ff57deae953f738a160f74bbe29f4c4c37f475c77ebe0228b216c9f354a6ae"; // } //} /// token计算 /// /// /// public static string GetSHA256HashFromString(string strData) { byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(strData); SHA256 sha256 = new SHA256CryptoServiceProvider(); byte[] retVal = sha256.ComputeHash(bytValue); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } public static string CreateToken(string message, string secret) { secret = secret ?? ""; var encoding = new System.Text.UTF8Encoding(); byte[] keyByte = encoding.GetBytes(secret); byte[] messageBytes = encoding.GetBytes(message); using (var hmacsha256 = new HMACSHA256(keyByte)) { byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hashmessage.Length; i++) { builder.Append(hashmessage[i].ToString("x2")); } return builder.ToString(); } } /// /// 生成签名 /// public static string CreateSignature(string url, string data, string signKey) { var str = url + "|" + data; return HmacSHA256(str, signKey).ToLower(); } /// 加密算法HmacSHA256 /// /// /// /// public static string HmacSHA256(string secret, string signKey) { string signRet = string.Empty; using (HMACSHA256 mac = new HMACSHA256(Encoding.UTF8.GetBytes(signKey))) { byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(secret)); signRet = ToHexString(hash); } return signRet; } /// /// byte[]转16进制格式string /// public static string ToHexString(byte[] bytes) { string hexString = string.Empty; if (bytes != null) { StringBuilder strB = new StringBuilder(); foreach (byte b in bytes) { strB.AppendFormat("{0:x2}", b); } hexString = strB.ToString(); } return hexString; } #region 读取订单 public List GetOrders(out string ErrorMessage) { string Url = "https://partner.shopeemobile.com/api/v1/orders/basics"; List ListModel = new List(); #region 设置市场所在地借口地址 //switch (country) //{ // case "印尼": // Url = "https://api.sellercenter.lazada.co.id"; // break; // case "马来": // Url = "https://api.sellercenter.lazada.com.my"; // break; // case "泰国": // Url = "https://api.sellercenter.lazada.co.th"; // break; // case "菲律宾": // Url = "https://api.sellercenter.lazada.com.ph"; // break; // case "新加坡": // Url = "https://api.sellercenter.lazada.sg"; // break; // case "越南": // Url = "https://api.sellercenter.lazada.vn"; // break; //} #endregion var param = new Dictionary(); param.Add("partner_id",Partner_Id); param.Add("update_time_to", GetTimeStamp(DateTime.Now)); param.Add("update_time_from", GetTimeStamp(DateTime.Now.AddDays(-7))); //param.Add("Status", "pending"); param.Add("shopid",shopid); param.Add("pagination_offset", 0); param.Add("timestamp",GetTimeStamp(DateTime.Now)); param.Add("pagination_entries_per_page",50); string surl =""; if (param != null) { foreach (var item in param) { surl += item.Key + "=" + item.Value + "&"; } } surl = surl.TrimEnd('&'); var JsonConvert = new JavaScriptSerializer(); var sign = CreateSignature(Url, JsonConvert.Serialize(param), Partner_Key); string postmessage = JsonConvert.Serialize(param); List ListHeader = new List(); ListHeader.Add("Authorization:" + sign); //string sss = postmessage.Substring(1087, 50); UTF8Encoding encoding = new UTF8Encoding(); byte[] data = encoding.GetBytes(postmessage); string XmlContent = CustomIO.HttpRequest2(Url, "Post", "application/json;charset=UTF-8", ListHeader, System.Net.HttpVersion.Version10, data, out ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) { return null; } var smd = JsonConvert.Deserialize(XmlContent); bool flag = false; if(smd!=null&&smd.more==true) flag = true; if (smd != null && smd.orders!=null) { List olist = new List(); foreach (var omd in smd.orders) { if (omd.order_status == "READY_TO_SHIP") { olist.Add(omd.ordersn); } } var dlist=GetOrdersdetail(olist, out ErrorMessage); if (dlist != null) { foreach (var dmd in dlist) { ListModel.Add(dmd); } } } int pagination_offset = 0; while (flag) { pagination_offset += 50; param = new Dictionary(); param.Add("partner_id", Partner_Id); param.Add("update_time_to", GetTimeStamp(DateTime.Now)); param.Add("update_time_from", GetTimeStamp(DateTime.Now.AddDays(-7))); //param.Add("Status", "pending"); param.Add("shopid", shopid); param.Add("pagination_offset", pagination_offset); param.Add("timestamp", GetTimeStamp(DateTime.Now)); param.Add("pagination_entries_per_page", 50); surl = ""; if (param != null) { foreach (var item in param) { surl += item.Key + "=" + item.Value + "&"; } } surl = surl.TrimEnd('&'); sign = CreateSignature(Url, JsonConvert.Serialize(param), Partner_Key); postmessage = JsonConvert.Serialize(param); ListHeader = new List(); ListHeader.Add("Authorization:" + sign); //string sss = postmessage.Substring(1087, 50); data = encoding.GetBytes(postmessage); XmlContent = CustomIO.HttpRequest2(Url, "Post", "application/json;charset=UTF-8", ListHeader, System.Net.HttpVersion.Version10, data, out ErrorMessage); smd = JsonConvert.Deserialize(XmlContent); flag = false; if (smd != null && smd.more == true) flag = true; if (smd != null && smd.orders != null) { List olist = new List(); foreach (var omd in smd.orders) { if (omd.order_status == "READY_TO_SHIP") { olist.Add(omd.ordersn); } } var dlist = GetOrdersdetail(olist, out ErrorMessage); if (dlist != null) { foreach (var dmd in dlist) { ListModel.Add(dmd); } } } } return ListModel; } #endregion /// /// 时间戳转为C#格式时间 /// /// Unix时间戳格式 /// C#格式时间 public static DateTime GetStampTimeToDate(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } #region 读取订单 public List GetOrdersdetail(List olist,out string ErrorMessage) { string Url = "https://partner.shopeemobile.com/api/v1/orders/detail"; List ListModel = new List(); var param = new Dictionary(); // List os = new List(); // os.Add("210225SWK6PJP8"); param.Add("ordersn_list", olist); param.Add("partner_id", Partner_Id); param.Add("shopid", shopid); param.Add("timestamp", GetTimeStamp(DateTime.Now)); string surl = ""; if (param != null) { foreach (var item in param) { surl += item.Key + "=" + item.Value + "&"; } } surl = surl.TrimEnd('&'); var JsonConvert = new JavaScriptSerializer(); var sign = CreateSignature(Url, JsonConvert.Serialize(param), Partner_Key); string postmessage = JsonConvert.Serialize(param); List ListHeader = new List(); ListHeader.Add("Authorization:" + sign); //string sss = postmessage.Substring(1087, 50); UTF8Encoding encoding = new UTF8Encoding(); byte[] data = encoding.GetBytes(postmessage); string XmlContent = CustomIO.HttpRequest2(Url, "Post", "application/json;charset=UTF-8", ListHeader, System.Net.HttpVersion.Version10, data, out ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) { return null; } var smd = JsonConvert.Deserialize(XmlContent); if (smd != null) { if (smd.orders != null) { foreach (var ordermd in smd.orders) { OrderModel model = new OrderModel(); model.OrderCode = ordermd.ordersn.ToString(); //if (model.OrderCode == "190206133129H0M") //{ // string a = "1"; //} model.TotalPrice = Convert.ToDecimal(ordermd.total_amount); model.MoneyCode = ordermd.currency; model.OrderDate = GetStampTimeToDate(ordermd.create_time.ToString()); model.BuyerID = ""; model.OrderState = 2; if (ordermd.recipient_address != null) model.BuyerName = ordermd.recipient_address.name; if (ordermd.recipient_address != null) model.BuyerCountry = ordermd.recipient_address.country; if (model.BuyerCountry == null || model.BuyerCountry == "") model.BuyerCountry = ordermd.country; if (ordermd.recipient_address != null) model.BuyerAddr = ordermd.recipient_address.full_address; model.BuyerPhone = ""; model.BuyerPhone = ordermd.recipient_address.phone; model.BuyerMobile = ""; model.BuyerMail = ""; //model.logisticsAmount =ordermd.buyerInfo.logisticsAmount; if (ordermd.escrow_tax != null) { model.escrowFee = Convert.ToDecimal(ordermd.escrow_tax); // model.TotalPrice = Convert.ToDecimal(ordermd.escrow_amount); } if (ordermd.escrow_amount != null && ordermd.escrow_amount != "") model.TotalPrice = Convert.ToDecimal(ordermd.escrow_amount); model.BuyerFax = ""; if (ordermd.recipient_address != null) model.BuyerZip = ordermd.recipient_address.zipcode; if (ordermd.recipient_address != null) model.BuyerProvince = ordermd.recipient_address.state; if (ordermd.recipient_address != null) model.BuyerCity = ordermd.recipient_address.city; if (ordermd.recipient_address != null) model.BuyerArea = ordermd.recipient_address.district; model.OrderRemark = ""; //memo model.LeaveWord = ordermd.message_to_seller; model.PayDate = model.OrderDate; model.OutOrderDate = model.OrderDate.Value.AddDays(7); if (ordermd.days_to_ship != null) model.OutOrderDate = model.OrderDate.Value.AddDays(ordermd.days_to_ship.Value); model.PostInfo = ordermd.shipping_carrier; model.ListModel = new List(); if (ordermd.items != null) { foreach (var item2 in ordermd.items) { OrderDetailModel model2 = new OrderDetailModel(); // {"item_name":"Adjustable Kids Safety Harness Wrist Leash Anti-lost Link","item_sku":"\tZHI049","variation_discounted_price":"7.74","variation_id":320874188,"variation_name":"Blue, 250CM","item_id":418147192, // "variation_quantity_purchased":1,"variation_sku":"\tZHI049","variation_original_price":"8.60" model2.TypeDesc = item2.variation_sku; model2.productImgUrl = ""; model2.GoodsNum = item2.variation_quantity_purchased; if (item2.variation_original_price != null) model2.GoodsPrice = Convert.ToDecimal(item2.variation_original_price); model2.MoneyCode = ""; model2.GoodsName = item2.item_name + " " + item2.variation_name; model2.GoodsSKU = item2.variation_sku; model2.PostInfo = ""; model.ListModel.Add(model2); } } ListModel.Add(model); } } } return ListModel; } #endregion private int GetTimeStamp(DateTime dt) { DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0); int timeStamp = Convert.ToInt32((dt - dateStart).TotalSeconds); return timeStamp; } } public class Recipient_address { /// /// /// public string town { get; set; } /// /// /// public string city { get; set; } /// /// /// public string name { get; set; } /// /// /// public string district { get; set; } /// /// /// public string country { get; set; } /// /// /// public string zipcode { get; set; } /// /// /// public string full_address { get; set; } /// /// /// public string phone { get; set; } /// /// /// public string state { get; set; } } public class Items { /// /// /// public string group_id { get; set; } /// /// /// public double weight { get; set; } /// /// /// public string item_name { get; set; } /// /// /// public bool? is_wholesale { get; set; } /// /// /// public string promotion_type { get; set; } /// /// /// public string item_sku { get; set; } /// /// /// public string variation_discounted_price { get; set; } /// /// /// public string variation_id { get; set; } /// /// /// public string variation_name { get; set; } /// /// /// public bool? is_set_item { get; set; } /// /// /// public bool? is_add_on_deal { get; set; } /// /// /// public string item_id { get; set; } /// /// /// public string promotion_id { get; set; } /// /// /// public string add_on_deal_id { get; set; } /// /// /// public Int32? variation_quantity_purchased { get; set; } /// /// /// public string variation_sku { get; set; } /// /// /// public string variation_original_price { get; set; } /// /// /// public bool? is_main_item { get; set; } /// /// /// public string order_item_id { get; set; } } public class ShopeeOrdersDeatil { /// /// /// public string estimated_shipping_fee { get; set; } /// /// /// public string order_flag { get; set; } /// /// /// public string payment_method { get; set; } /// /// /// public long? update_time { get; set; } /// /// /// public string message_to_seller { get; set; } /// /// /// public string shipping_carrier { get; set; } /// /// /// public string currency { get; set; } /// /// /// public long? create_time { get; set; } /// /// /// public long? pay_time { get; set; } /// /// /// public string note { get; set; } /// /// /// public string credit_card_number { get; set; } /// /// /// public int? days_to_ship { get; set; } /// /// /// public bool? is_split_up { get; set; } /// /// /// public int? ship_by_date { get; set; } /// /// /// public string escrow_tax { get; set; } /// /// /// public string tracking_no { get; set; } /// /// /// public string order_status { get; set; } /// /// /// public long? note_update_time { get; set; } /// /// /// public string fm_tn { get; set; } /// /// /// public string dropshipper_phone { get; set; } /// /// /// public string cancel_reason { get; set; } /// /// /// public string checkout_shipping_carrier { get; set; } /// /// /// public Recipient_address recipient_address { get; set; } /// /// /// public string cancel_by { get; set; } /// /// /// public string escrow_amount { get; set; } /// /// /// public string buyer_cancel_reason { get; set; } /// /// /// public bool? goods_to_declare { get; set; } /// /// /// public string lm_tn { get; set; } /// /// /// public string total_amount { get; set; } /// /// /// public string service_code { get; set; } /// /// /// public List items { get; set; } /// /// /// public string actual_shipping_cost { get; set; } /// /// /// public bool? cod { get; set; } /// /// /// public string country { get; set; } /// /// /// public string ordersn { get; set; } /// /// /// public string dropshipper { get; set; } /// /// /// public bool? is_actual_shipping_fee_confirmed { get; set; } /// /// /// public string buyer_username { get; set; } } public class ShopeeRoot { /// /// /// public List errors { get; set; } /// /// /// public List orders { get; set; } /// /// /// public string request_id { get; set; } } public class ShopeeOrders { /// /// /// public string ordersn { get; set; } /// /// /// public string order_status { get; set; } /// /// /// public int update_time { get; set; } /// /// /// public bool is_actual_shipping_fee_confirmed { get; set; } } public class ShopeeOrdersRoot { /// /// /// public string request_id { get; set; } /// /// /// public List orders { get; set; } /// /// /// public bool more { get; set; } } }