using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web.Script.Serialization; using NetLibrary.Data; namespace NetLibrary.Express { public class DHLApi { // string aa="{"labelRequest": { // "hdr": { // "messageType": "LABEL", // "messageDateTime": "2016-01-13T16:20:27+11:20", // "accessToken": "8e1fd7502fc810d3918d87a8a7bf98a9", // "messageVersion": "1.4", // "messageLanguage": "en" // }, // "bd": { // "customerAccountId": null, // "pickupAccountId": "5235568104", // "soldToAccountId": "5235568104", // "pickupDateTime": "2016-01-13T16:20:27+11:20", // "pickupAddress": { // "companyName": "Pickup Company", // "name": "Pickup Name", // "address1": "Address1", // "address2": "Address2", // "address3": "Address3", // "city": "City", // "state": "State", // "district": "District", // "country": "CN", // "postCode": "6278", // "phone": "9999", // "email": "test@dhl.com" // }, // "shipmentItems": [ // { // "consigneeAddress": { // "companyName": "Consignee Company", // "name": "Consigee Name", // "address1": "Address1", // "address2": "Address2", // "address3": "Address3", // "city": "City", // "state": "NY", // "district": null, // "country": "TT", // "postCode": "1234", // "phone": "9999", // "email": "test@dhl.com", // "idNumber": "9999", // "idType": "1" // }, // "returnAddress": { // "companyName": "Return Company", // "name": "Return Name", // "address1": "Address1", // "address2": "Address2", // "address3": "Address3", // "city": "Chennai", // "state": "Tamilnadu", // "district": "district", // "country": "IN", // "postCode": "627008", // "phone": "9999", // "email": "test@dhl.com" // }, // "shipmentID": "Today0043", // "deliveryConfirmationNo": "test", // "packageDesc": "Desc", // "totalWeight": 2000, // "totalWeightUOM": "G", // "dimensionUOM": "cm", // "height": 0.0, // "length": 0.0, // "width": 0.0, // "customerReference1": "test", // "customerReference2": "test", // "productCode": "PKD", // "incoterm": "DDU", // "contentIndicator": "01", // "codValue": 40.34, // "insuranceValue": 69.0, // "freightCharge": 0.0, // "totalValue": 23.1, // "currency": "BRL", // "shipmentContents": [ // { // "skuNumber": "Code001", // "description": "Desc", // "descriptionImport": "test", // "descriptionExport": "test", // "itemValue": 105.5, // "itemQuantity": 10, // "grossWeight": 100, // "netWeight": 100, // "weightUOM": "g", // "contentIndicator": "01", // "countryOfOrigin": "SG", // "hsCode": "9876543210" // }, { // "skuNumber": "Code002", // "description": "Desc", // "descriptionImport": "test", // "descriptionExport": "test", // "itemValue": 25.5, // "itemQuantity": 10, // "grossWeight": 100, // "netWeight": 100, // "weightUOM": "g", // "contentIndicator": "01", // "countryOfOrigin": "SG", // "hsCode": "9876543210" // }, { // "skuNumber": "Code002", // "description": "Desc", // "descriptionImport": "test", // "descriptionExport": "test", // "itemValue": 26.5, // "itemQuantity": 10, // "grossWeight": 100, // "netWeight": 100, // "weightUOM": "g", // "contentIndicator": "01", // "countryOfOrigin": "SG", // "hsCode": "9876543210" // } // ] // } // ], // "label": { // "pageSize": "400x600", // "format": "PDF", // "layout": "1x1" // } // } // } //}'; public string clientId { get; set; } public string password { get; set; } public string AccessToken { get; set; } public string token_type { get; set; } public DateTime? GetTime { get; set; } public string URL = "https://sandbox.dhlecommerce.asia"; public int flag = 0; JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); #region 当访问令牌超过23小时,那么重新请求 public void GetAccessToken(out string ErrorMessage) { // ErrorMessage = ""; //return; URL = "https://api.dhlecommerce.dhl.com/rest/v1/OAuth/AccessToken?clientId=" + clientId + "&password=" + password + "&returnFormat=json"; string XmlContent = CustomIO.HttpRequest(URL, "Get", out ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return; accessToken Model = JsonConvert.Deserialize(XmlContent); if (Model.accessTokenResponse.responseStatus.code == "100000") { AccessToken = Model.accessTokenResponse.token; token_type = Model.accessTokenResponse.token_type; GetTime = DateTime.Now; SaveDHLCode(); } else { ErrorMessage = Model.accessTokenResponse.responseStatus.message; } } #endregion #region 发货 public string SendGoods(DHLOrder model, out string ErrorMessage) { // ErrorMessage = ""; //return; try { if (GetTime == null || GetTime.Value < DateTime.Now.AddHours(-23)) { GetAccessToken(out ErrorMessage); } URL = "https://api.dhlecommerce.dhl.com/rest/v2/Label"; // "https://sandbox.dhlecommerce.asia/rest/v2/Label"; model.labelRequest.hdr.accessToken = AccessToken; model.labelRequest.bd.customerAccountId = null; string postmessage = JsonConvert.Serialize(model); byte[] data = Encoding.UTF8.GetBytes(postmessage); string XmlContent = CustomIO.HttpRequest2(URL, "Post", "application/json", null, HttpVersion.Version10, data, out ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return ""; // string str = XmlContent.Replace("null", "\"\""); DHLOrder2 model2 = JsonConvert.Deserialize(XmlContent); //string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; //if (System.IO.Directory.Exists(dir) == false) System.IO.Directory.CreateDirectory(dir); //string fname = Guid.NewGuid().ToString() + ".pdf"; //string filePath = dir + "/" + fname; //if (model2.labelResponse.bd.responseStatus.code == "200") // Base64StringToFile(model2.labelResponse.bd.labels[0].content, filePath); if (model2.labelResponse.bd.responseStatus.code == "200") //成功 { //closeOutRequest closemodel = new closeOutRequest(); //hd3 hd3 = new hd3(); //hd3.messageType = "CLOSEOUT"; //hd3.accessToken = ""; //hd3.messageDateTime = DateTime.Now.ToString("s"); //hd3.messageVersion = "1.3"; //hd3.messageLanguage = "en"; //closemodel.hdr = hd3; //bd3 bd3 = new bd3(); //shipmentItems3 smd = new shipmentItems3(); //List slist = new List(); //smd.shipmentID = model.labelRequest.bd.shipmentItems[0].shipmentID; //smd.bagID = null; //slist.Add(smd); //bd3.customerAccountId = null; //bd3.pickupAccountId =model.labelRequest.bd.pickupAccountId; //bd3.soldToAccountId = model.labelRequest.bd.soldToAccountId; //bd3.handoverID = null; //bd3.generateHandover = "Y"; //bd3.handoverMethod = 1; //bd3.shipmentItems = slist; //closemodel.bd = bd3; //var closeOut = new closeOut(); //closeOut.closeOutRequest = closemodel; // string error = ""; //Colse_out(closeOut, out error); return model2.labelResponse.bd.labels[0].deliveryConfirmationNo; } else { ErrorMessage = model2.labelResponse.bd.responseStatus.messageDetails[0].messageDetail + "失败"; if (flag == 0 && ErrorMessage.Contains("token") == true) { flag = 1; GetAccessToken(out ErrorMessage); SendGoods(model, out ErrorMessage); } } return ""; } catch (Exception ex) { ErrorMessage = ex.Message + "失败"; return ""; } } #endregion #region 发货 public string Colse_out(closeOut model, out string ErrorMessage) { // ErrorMessage = ""; //return; if (GetTime == null || GetTime.Value < DateTime.Now.AddHours(-20)) { GetAccessToken(out ErrorMessage); } URL = "https://api.dhlecommerce.dhl.com/rest/v2/Order/Shipment/CloseOut"; //"https://sandbox.dhlecommerce.asia/rest/v2/Order/Shipment/CloseOut"; model.closeOutRequest.hdr.accessToken = AccessToken; string postmessage = JsonConvert.Serialize(model); byte[] data = Encoding.UTF8.GetBytes(postmessage); string XmlContent = CustomIO.HttpRequest2(URL, "Post", "application/json", null, HttpVersion.Version10, data, out ErrorMessage); if (string.IsNullOrEmpty(ErrorMessage) == false) return ""; //string str = XmlContent.Replace("null", "\"\""); DHLOrder3 model2 = JsonConvert.Deserialize(XmlContent); if (model2.closeOutResponse.bd.responseStatus.code == "200") //成功 { return ""; } else ErrorMessage = model2.closeOutResponse.bd.responseStatus.messageDetails[0].messageDetail + "失败"; if (ErrorMessage.Contains("token")) { GetAccessToken(out ErrorMessage); } return ""; } #endregion public void Base64StringToFile(string strbase64, string strurl) { try { strbase64 = strbase64.Replace(' ', '+'); MemoryStream stream = new MemoryStream(Convert.FromBase64String(strbase64)); FileStream fs = new FileStream(strurl, FileMode.OpenOrCreate, FileAccess.Write); byte[] b = stream.ToArray(); //byte[] b = stream.GetBuffer(); fs.Write(b, 0, b.Length); fs.Close(); } catch (Exception e) { } } #region 保存dhl授权 public void SaveDHLCode() { string tsql = @" Update [JC_ExpressPost] set [UserCode]=@UserCode,CheckCode=@CheckCode,[GetTime]=getdate() where ExpressID in (234) "; Database db = DatabaseFactory.CreateDatabase(); DbCommand cmd = db.GetSqlStringCommand(tsql); db.AddInParameter(cmd, "@UserCode", DbType.String, AccessToken); db.AddInParameter(cmd, "@CheckCode", DbType.String, token_type); db.ExecuteNonQuery(cmd); } #endregion } #region 订单 public class DHLOrder { public labelRequest labelRequest { get; set; } } public class labelRequest { public hdr hdr { get; set; } public DHL_Order bd { get; set; } } public class DHLOrder2 { public labelResponse labelResponse { get; set; } } public class DHLOrder3 { public closeOutResponse closeOutResponse { get; set; } } public class closeOutResponse { // public hdr hdr { get; set; } public bd4 bd { get; set; } } public class bd4 { public responseStatus2 responseStatus { get; set; } } public class labelResponse { // public hdr hdr { get; set; } public bd2 bd { get; set; } } public class bd2 { public List labels { get; set; } public responseStatus2 responseStatus { get; set; } } public class labels { public string shipmentID { get; set; } public string deliveryConfirmationNo { get; set; } public string content { get; set; } } public class hdr { public string messageType { get; set; } public string messageDateTime { get; set; } public string accessToken { get; set; } public string messageVersion { get; set; } public string messageLanguage { get; set; } } public class DHL_Order { public string customerAccountId { get; set; } public string pickupAccountId { get; set; } public string soldToAccountId { get; set; } public string pickupDateTime { get; set; } public pickupAddress pickupAddress { get; set; } public shipperAddress shipperAddress { get; set; } public List shipmentItems { get; set; } public label label { get; set; } } public class pickupAddress { public string companyName { get; set; } public string name { get; set; } public string address1 { get; set; } public string address2 { get; set; } public string address3 { get; set; } public string city { get; set; } public string state { get; set; } public string district { get; set; } public string country { get; set; } public string postCode { get; set; } public string phone { get; set; } public string email { get; set; } } public class shipperAddress { public string companyName { get; set; } public string name { get; set; } public string address1 { get; set; } public string address2 { get; set; } public string address3 { get; set; } public string city { get; set; } public string state { get; set; } public string district { get; set; } public string country { get; set; } public string postcode { get; set; } public string phone { get; set; } public string email { get; set; } } public class shipmentItems { public consigneeAddress consigneeAddress { get; set; } public returnAddress returnAddress { get; set; } public string shipmentID { get; set; } public string deliveryConfirmationNo { get; set; } public string packageDesc { get; set; } public Decimal? totalWeight { get; set; } public string totalWeightUOM { get; set; } public string dimensionUOM { get; set; } public Decimal? height { get; set; } public Decimal? length { get; set; } public Decimal? width { get; set; } public string customerReference1 { get; set; } public string customerReference2 { get; set; } public string productCode { get; set; } public string incoterm { get; set; } public string contentIndicator { get; set; } public string codValue { get; set; } public Decimal? insuranceValue { get; set; } public Decimal? freightCharge { get; set; } public Decimal? totalValue { get; set; } public string currency { get; set; } public List shipmentContents { get; set; } } public class consigneeAddress { public string companyName { get; set; } public string name { get; set; } public string address1 { get; set; } public string address2 { get; set; } public string address3 { get; set; } public string city { get; set; } public string state { get; set; } public string district { get; set; } public string country { get; set; } public string postCode { get; set; } public string phone { get; set; } public string email { get; set; } public string idNumber { get; set; } public string idType { get; set; } } public class returnAddress { public string companyName { get; set; } public string name { get; set; } public string address1 { get; set; } public string address2 { get; set; } public string address3 { get; set; } public string city { get; set; } public string state { get; set; } public string district { get; set; } public string country { get; set; } public string postCode { get; set; } public string phone { get; set; } public string email { get; set; } } public class shipmentContents { public string skuNumber { get; set; } public string description { get; set; } public string descriptionImport { get; set; } public string descriptionExport { get; set; } public Decimal? itemValue { get; set; } public Int32? itemQuantity { get; set; } public Int32? grossWeight { get; set; } public Int32? netWeight { get; set; } public string weightUOM { get; set; } public string contentIndicator { get; set; } public string countryOfOrigin { get; set; } public string hsCode { get; set; } } public class label { public string pageSize { get; set; } public string format { get; set; } public string layout { get; set; } } public class accessToken { public accessTokenResponse accessTokenResponse { get; set; } } public class accessTokenResponse { public string token { get; set; } public string token_type { get; set; } public string expires_in_seconds { get; set; } public responseStatus responseStatus { get; set; } } public class responseStatus { public string code { get; set; } public string message { get; set; } public string expires_in_seconds { get; set; } public string messageDetails { get; set; } } public class responseStatus2 { public string code { get; set; } public string message { get; set; } //public string expires_in_seconds { get; set; } public List messageDetails { get; set; } } public class Detail { public string messageDetail { get; set; } } public class closeOut { public closeOutRequest closeOutRequest { get; set; } } public class closeOutRequest { public hd3 hdr { get; set; } public bd3 bd { get; set; } } public class hd3 { public string messageType { get; set; } public string accessToken { get; set; } public string messageVersion { get; set; } public string messageDateTime { get; set; } public string messageLanguage { get; set; } } public class bd3 { public string customerAccountId { get; set; } public string pickupAccountId { get; set; } public string soldToAccountId { get; set; } public string handoverID { get; set; } public string generateHandover { get; set; } public int handoverMethod { get; set; } public List shipmentItems { get; set; } } public class shipmentItems3 { public string shipmentID { get; set; } public string bagID { get; set; } } #endregion }