using NetLibrary; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Script.Serialization; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO; using NetLibrary.Data; using System.Data.Common; using System.Data; using NetLibrary.OnlineTrade; using NetLibrary.Log; using System.Security.Cryptography; using System.Net.Sockets; using System.Runtime.Remoting.Metadata.W3cXsd2001; using System.Net.Http; using System.Security.Policy; using System.Web; namespace TradeManageNew { public class Shopify { public string IP = "http://50.196.110.198:8099"; //美国跳转服务器ip地址 public string ShopName { get; set; } public string AccessToken { get; set; } public string AppKey { get; set; } public string AppSecret { get; set; } JavaScriptSerializer JsonConvert = null; public Shopify() { //验证服务器证书回调自动验证 // ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate; JsonConvert = new JavaScriptSerializer(); } public List GetOrdersNew(out string ErrorMessage) { //if (RefreshToken == null || RefreshToken == "") //{ // GetToken(out ErrorMessage); //} //else try { if (AccessToken == null) { ErrorMessage = "店铺未授权"; return null; } ErrorMessage = ""; // string sdt =DateTime.Today.AddDays(-7).ToString("yyyy-MM-dd")+"T00:00:00-08:00"; // string URL = "https://" + AppKey + ":" + AppSecret + "@" + ShopName + ".myshopify.com/admin/api/2023-07/orders.json?created_at_min=" + sdt + "&fulfillment_status=unshipped&financial_status=paid&limit=250"; // string ErrMessage = ""; // List head = new List(); // head.Add("X-Shopify-Access-Token:" + AccessToken); //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; //.net 4.5 设置: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls1.2; // ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; // GetSentosaCertificate(); //ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072; //string XmlContent =HttpRequest2(URL, "GET", "application/x-www-form-urlencoded", head, System.Net.HttpVersion.Version11, null, out ErrMessage); //if (string.IsNullOrEmpty(ErrMessage) == false) //{ // ErrorMessage = ErrMessage; // return null; //} var ordersContent = GetShopifyOrders(); if (string.IsNullOrEmpty(ordersContent)) { ErrorMessage = "失败"; return null; } ShopifyOrder Model = JsonConvert.Deserialize(ordersContent); List ListModel = new List(); if (Model.orders != null) { foreach (var md in Model.orders) { var omd = ToOrderModel(md); if (omd != null) ListModel.Add(omd); } } return ListModel; } catch (Exception ex) { ErrorMessage = ex.Message; return null; } } /// /// 从跳转服务器获取SHopify订单 /// /// public string GetShopifyOrders() { try { var sdate= DateTime.Today.AddDays(-7).ToString("yyyy-MM-dd") + "T00:00:00-08:00"; var apiUrl = "https://" + AppKey + ":" + AppSecret + "@" + ShopName + ".myshopify.com/admin/api/2023-07/orders.json?created_at_min=" + sdate + "&fulfillment_status=unshipped&financial_status=paid&limit=250"; //var path = ""; //using (Aes aesAlg = Aes.Create()) //{ // aesAlg.Key = Encoding.UTF8.GetBytes("ThisIsShopifyKey12365498");//加密密码 // aesAlg.IV = new byte[16]; // 使用默认的 IV // ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // byte[] encrypted; // using (var msEncrypt = new System.IO.MemoryStream()) // { // using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) // { // using (var swEncrypt = new System.IO.StreamWriter(csEncrypt)) // { // swEncrypt.Write(apiUrl); // } // encrypted = msEncrypt.ToArray(); // } // } // path= Convert.ToBase64String(encrypted); //} var path = EncryptString(apiUrl, "ThisIsShopifyKey12365498"); var path2= HttpUtility.UrlEncode(path); //path2= HttpUtility.UrlEncode(path2); var url = IP + "/api/ShopifyHelp/getShopifyOrderList?url=" + path2 + "&accessToken=" + AccessToken; //using (HttpClient client = new HttpClient()) //{ // HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); // var response = client.SendAsync(request); // string responseContent = response.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // if(string.IsNullOrEmpty(responseContent) || responseContent == "失败") // { // return ""; // } // return responseContent; //} using (WebClient client = new WebClient()) { client.Encoding = Encoding.UTF8; // 指定下载内容编码方式为 UTF-8 string responseContent = client.DownloadString(url); ErrorFollow.TraceWrite("自动导入Shopify订单列表", " URL:" + url, " 返回信息:" + responseContent); if (string.IsNullOrEmpty(responseContent) || responseContent == "失败") { return ""; } return responseContent; } } catch(Exception ex) { return ""; } } public static string EncryptString(string plainText, string key) { using (Aes aesAlg = Aes.Create()) { aesAlg.Key = Encoding.UTF8.GetBytes(key); aesAlg.IV = new byte[16]; // 使用默认IV ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); byte[] encryptedBytes; using (var msEncrypt = new System.IO.MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(plainBytes, 0, plainBytes.Length); csEncrypt.FlushFinalBlock(); encryptedBytes = msEncrypt.ToArray(); } } return Convert.ToBase64String(encryptedBytes); } } #region Http请求2 public string HttpRequest2(string url, string Method, string ContentType, List ListHeader, Version ver, byte[] bytes, out string ErrorMessage) { try { ErrorMessage = ""; if (string.IsNullOrEmpty(ContentType) == true) ContentType = "application/x-www-form-urlencoded"; HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = Method; //GET,POST myRequest.ContentType = ContentType; myRequest.KeepAlive = true; //myRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; qihu theworld)"; // myRequest.Headers.Add("Accept-Language: zh-CN"); // myRequest.Headers["Pragma"] = "no-cache"; //禁用缓存 // myRequest.Headers["Cache-Control"] = "no-cache"; //禁用缓存 myRequest.Timeout = 3 * 60 * 1000; myRequest.ProtocolVersion = ver; if (ListHeader != null) { foreach (var item in ListHeader) { myRequest.Headers.Add(item); } } if (bytes != null && bytes.Length > 0) { //myRequest.GetRequestStream().Write(bytes, 0, bytes.Length); Stream stream = myRequest.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); stream.Close(); } //获得接口返回值 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); Stream myResponseStream = myResponse.GetResponseStream(); StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); string content = reader.ReadToEnd(); reader.Close(); myResponseStream.Close(); myRequest.Abort(); myResponse.Close(); return content; } catch (Exception ex) { ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); ErrorMessage = ex.Message; } return ""; } #endregion private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } #region 转换成统一的订单对象 public OrderModel ToOrderModel(ShopifyOrder_Order md) { try { OrderModel model = new OrderModel(); //if (this.orderId.ToString() == "72860947447064") //{ // string treqq = "72860947447064"; //} model.PlatOrderCode = md.name.ToString(); model.OrderCode = md.name.ToString(); if(md.total_price!=null) model.TotalPrice = Convert.ToDecimal(md.total_price); else if (md.subtotal_price != null) model.TotalPrice = Convert.ToDecimal(md.subtotal_price); // Convert.ToDecimal(md.pay_amount.cent) / Convert.ToDecimal(md.pay_amount.cent_factor); model.MoneyCode = md.currency; if(md.created_at!=null) model.OrderDate = GetDateTime(md.created_at); model.OrderState = 1; if (md.cancelled_at != null && md.cancelled_at != "") { model.OrderState = 3; model.OrderRemark = md.cancel_reason; } if (md.shipping_address != null && md.shipping_address.name != null) model.BuyerName = md.shipping_address.name; if (md.shipping_address != null && md.shipping_address.country_code != null) model.BuyerCountry = md.shipping_address.country_code; if (md.shipping_address != null && md.shipping_address.address1 != null) model.BuyerAddr = md.shipping_address.address1; if (md.shipping_address != null && md.shipping_address.address2 != null) model.BuyerAddr += " " + md.shipping_address.address2; model.BuyerPhone = ""; if (md.shipping_address != null && md.shipping_address.phone != null) model.BuyerPhone = md.shipping_address.phone; // if (mdxx.result.receipt_address != null && this.buyerInfo.receiptAddress.phoneArea != null) // model.BuyerPhone += this.buyerInfo.receiptAddress.phoneArea + "-"; model.BuyerMail = md.contact_email; //model.logisticsAmount = this.buyerInfo.logisticsAmount; // model.escrowFee = this.buyerInfo.escrowFee; model.BuyerFax = ""; if (md.shipping_address != null && md.shipping_address.zip != null) model.BuyerZip = md.shipping_address.zip; if (md.shipping_address != null && md.shipping_address.province_code != null) model.BuyerProvince = md.shipping_address.province_code; if (md.shipping_address != null && md.shipping_address.city != null) model.BuyerCity = md.shipping_address.city; model.BuyerArea = ""; //if (md.note_attributes != null) //{ // string aa = ""; // for (int i = 0; i < md.note_attributes.Count; i++) // { // aa += md.note_attributes[i] + " "; // } // model.OrderRemark = aa; //} //else model.OrderRemark = ""; //memo model.LeaveWord = ""; if (md.updated_at != null) model.PayDate = Convert.ToDateTime(md.updated_at); else model.PayDate = model.OrderDate; model.OutOrderDate = DateTime.Now.AddDays(7); if (model.OrderDate != null && model.OrderDate.Value <= Convert.ToDateTime("1753-01-01")) { model.OrderDate = DateTime.Now; } if (model.PayDate != null && model.PayDate.Value <= Convert.ToDateTime("1753-01-01")) { model.PayDate = DateTime.Now; } if (model.OutOrderDate != null && model.OutOrderDate.Value <= Convert.ToDateTime("1753-01-01")) { model.OutOrderDate = DateTime.Now.AddDays(7); } if (md.line_items != null && md.line_items.Count>0) model.PostInfo = md.line_items[0].fulfillment_service; model.ListModel = new List(); //Alibaba_productAttributes pmd = null; //if (this.buyerInfo != null&&this.buyerInfo.childOrderList!=null) // { // if (this.buyerInfo.childOrderList.productAttributes != null && this.buyerInfo.childOrderList.productAttributes != "") // { // JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); // pmd = JsonConvert.Deserialize(this.buyerInfo.childOrderList.productAttributes); // } // } if (md.line_items != null) { foreach (var item2 in md.line_items) { OrderDetailModel model2 = new OrderDetailModel(); model2.TypeDesc = item2.variant_title; if (item2.gift_card != null && item2.gift_card== "true") model2.TypeDesc += "备注:gift_card" + item2.gift_card; model2.OrderItemId = item2.product_id; model2.GoodsNum = item2.quantity; model2.GoodsName = item2.name; model2.GoodsSKU = item2.sku; model2.PostInfo = item2.fulfillment_service; model.ListModel.Add(model2); } } return model; } catch (Exception ex) { ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); return null; } } #endregion public DateTime? GetDateTime(string dt) { if (string.IsNullOrEmpty(dt) == true) return null; dt = dt.Replace("T", " "); dt = dt.Remove(dt.Length - 1); return Convert.ToDateTime(dt); } } public class ShopifyOrder { public List orders { get; set; } } public class ShopifyOrder_Order { public string id { get; set; } public string name { get; set; } public string contact_email { get; set; } public string total_price { get; set; } public string subtotal_price { get; set; } public string currency { get; set; } public string financial_status { get; set; } public string referring_site { get; set; } public string cancel_reason { get; set; } public string fulfillment_status { get; set; } // public List note_attributes { get; set; } public Shopify_shipping_address shipping_address { get; set; } public List line_items { get; set; } public string created_at { get; set; } public string processed_at { get; set; } public string updated_at { get; set; } public string cancelled_at { get; set; } } public class Shopify_shipping_address { public string name { get; set; } public string address1 { get; set; } public string phone { get; set; } public string city { get; set; } public string zip { get; set; } public string province { get; set; } public string country { get; set; } public string country_code { get; set; } public string address2 { get; set; } public string province_code { get; set; } public string company { get; set; } } public class Shopify_line_items { public string title { get; set; } public int? quantity { get; set; } public string sku { get; set; } public string fulfillment_service { get; set; } public string product_id { get; set; } public string variant_title { get; set; } public string vendor { get; set; } public string gift_card { get; set; } public string name { get; set; } } }