You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

545 lines
29 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TradeManageNew.UpsSHIPWebReference;
using System.Net;
using NetLibrary.Express;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net.Http;
using System.IO;
using System.Drawing;
namespace TradeManageNew
{
public class UpsShip
{
public static string AccessLicenseNumber = "";
public static string Username = "";
public static string Password = "";
public static string ShipperNumber = "";
public string GetTrackCode(UPSOrder md,out string error)
{
try
{
ShipService shpSvc = new ShipService();
ShipmentRequest shipmentRequest = new ShipmentRequest();
UPSSecurity upss = new UPSSecurity();
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = AccessLicenseNumber;//"5D83BCCDEFB9A5D5";// "BCBE8EEC50CF3B56";
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = Username;// "Karmasfar";
upssUsrNameToken.Password = Password;// "Km28862820";
upss.UsernameToken = upssUsrNameToken;
shpSvc.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "nonvalidate" };
request.RequestOption = requestOption;
shipmentRequest.Request = request;
ShipmentType shipment = new ShipmentType();
shipment.Description = "";// "2xKM0765";
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = ShipperNumber;// "RE8474";
PaymentInfoType paymentInfo = new PaymentInfoType();
ShipmentChargeType shpmentCharge = new ShipmentChargeType();
BillShipperType billShipper = new BillShipperType();
billShipper.AccountNumber = ShipperNumber;// "RE8474";
shpmentCharge.BillShipper = billShipper;
shpmentCharge.Type = "01";
ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
paymentInfo.ShipmentCharge = shpmentChargeArray;
shipment.PaymentInformation = paymentInfo;
ShipAddressType shipperAddress = new ShipAddressType();
String[] addressLine = { md.Rever.StreetLines };// "480 Parkton Plaza"
shipperAddress.AddressLine = addressLine;
shipperAddress.City = md.Rever.City;// "Timonium";
shipperAddress.PostalCode = md.Rever.PostalCode;// "91761";
shipperAddress.StateProvinceCode = md.Rever.StateOrProvinceCode;// "CA";
shipperAddress.CountryCode = md.Rever.CountryCode;// "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipper.Name = md.Rever.PersonName;// "2xKM0765-s-m";
shipper.AttentionName = md.Rever.PersonName;// "2xKM0765-s-m";
ShipPhoneType shipperPhone = new ShipPhoneType();
shipperPhone.Number = md.Rever.PhoneNumber;// "1234567890";
shipper.Phone = shipperPhone;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
ShipAddressType shipFromAddress = new ShipAddressType();
String[] shipFromAddressLine = { md.Shiper.StreetLines };
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = md.Shiper.City;// "Timonium";
shipFromAddress.PostalCode = md.Shiper.PostalCode;// "91761";
shipFromAddress.StateProvinceCode = md.Shiper.StateOrProvinceCode;// "CA";
shipFromAddress.CountryCode = md.Shiper.CountryCode;// "US";
shipFrom.Address = shipFromAddress;
shipFrom.AttentionName = md.Shiper.PersonName;// "Mr.ABC";
shipFrom.Name = md.Shiper.PersonName;//"2xKM0765-s-m";
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { md.Rever.StreetLines };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = md.Rever.City;// "ONTARIO";
shipToAddress.PostalCode=md.Rever.PostalCode;// "91761";
shipToAddress.CountryCode = md.Rever.CountryCode;// "US";
shipToAddress.StateProvinceCode = md.Rever.StateOrProvinceCode;// "CA";
shipTo.Address = shipToAddress;
shipTo.AttentionName = md.Rever.PersonName;// "Associates";
shipTo.Name = md.Rever.PersonName;// "DEF Associates";
ShipPhoneType shipToPhone = new ShipPhoneType();
shipToPhone.Number = md.Rever.PhoneNumber;// "1234567890";
shipTo.Phone = shipToPhone;
shipment.ShipTo = shipTo;
ServiceType service = new ServiceType();
service.Code =md.shipservicecode;// "93";
shipment.Service = service;
ShipmentTypeShipmentServiceOptions shpServiceOptions = new ShipmentTypeShipmentServiceOptions();
/** **** International Forms ***** */
// InternationalFormType internationalForms = new InternationalFormType();
/** **** Commercial Invoice ***** */
// String[] formTypeList = { "01" };
// internationalForms.FormType = formTypeList;
///** **** Contacts and Sold To ***** */
//ContactType contacts = new ContactType();
//SoldToType soldTo = new SoldToType();
//soldTo.Option = "1";
//soldTo.AttentionName = "Sold To Attn Name";
//soldTo.Name = "Sold To Name";
//PhoneType soldToPhone = new PhoneType();
//soldToPhone.Number = "1234567890";
//soldToPhone.Extension = "1234";
//soldTo.Phone = soldToPhone;
//AddressType soldToAddress = new AddressType();
//String[] soldToAddressLine = { "34 Queen St" };
//soldToAddress.AddressLine = soldToAddressLine;
//soldToAddress.City = "Frankfurt";
//soldToAddress.PostalCode = "60547";
//soldToAddress.CountryCode = "DE";
//soldTo.Address = soldToAddress;
//contacts.SoldTo = soldTo;
//internationalForms.Contacts = contacts;
/** **** Product ***** */
//ProductType product1 = new ProductType();
//String[] description = { md.GoodsList[0].SKU };
//product1.Description = description;
//product1.CommodityCode = md.GoodsList[0].SKU;// "111222AA";
//product1.OriginCountryCode = "CN";
//UnitType unit = new UnitType();
//unit.Number = "147";
//unit.Value = "478";
//UnitOfMeasurementType uomProduct = new UnitOfMeasurementType();
//uomProduct.Code = "BOX";
//uomProduct.Description = "BOX";
//unit.UnitOfMeasurement = uomProduct;
//product1.Unit = unit;
//ProductWeightType productWeight = new ProductWeightType();
//productWeight.Weight = "10";
//UnitOfMeasurementType uomForWeight = new UnitOfMeasurementType();
//uomForWeight.Code = "LBS";
//uomForWeight.Description = "LBS";
//productWeight.UnitOfMeasurement = uomForWeight;
//product1.ProductWeight = productWeight;
//ProductType[] productList = { product1 };
//internationalForms.Product = productList;
///** **** InvoiceNumber, InvoiceDate, PurchaseOrderNumber, TermsOfShipment, ReasonForExport, Comments and DeclarationStatement ***** */
//internationalForms.InvoiceNumber = "asdf123";
//internationalForms.InvoiceDate = "20151225";
//internationalForms.PurchaseOrderNumber = "999jjj777";
//internationalForms.TermsOfShipment = "CFR";
//internationalForms.ReasonForExport = "Sale";
//internationalForms.Comments = "Your Comments";
//internationalForms.DeclarationStatement = "2xKM0765";
///** **** Discount, FreightCharges, InsuranceCharges, OtherCharges and CurrencyCode ***** */
//IFChargesType discount = new IFChargesType();
//discount.MonetaryValue = "0";
//internationalForms.Discount = discount;
//IFChargesType freight = new IFChargesType();
//freight.MonetaryValue = "0";
//internationalForms.FreightCharges = freight;
//IFChargesType insurance = new IFChargesType();
//insurance.MonetaryValue = "0";
//internationalForms.InsuranceCharges = insurance;
//OtherChargesType otherCharges = new OtherChargesType();
//otherCharges.MonetaryValue = "0";
//otherCharges.Description = "Misc";
//internationalForms.OtherCharges = otherCharges;
//internationalForms.CurrencyCode = "USD";
//shpServiceOptions.InternationalForms = internationalForms;
shipment.ShipmentServiceOptions = shpServiceOptions;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = md.GoodsList[0].Weight.ToString();// "1";
ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
uom.Code = "LBS";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
DimensionsType dm = new DimensionsType();
dm.Height = md.GoodsList[0].Height;
dm.Length = md.GoodsList[0].Lenght;
dm.Width = md.GoodsList[0].Width;
ShipUnitOfMeasurementType uom2 = new ShipUnitOfMeasurementType();
uom2.Code = "IN";
uom2.Description = "inches";
dm.UnitOfMeasurement = uom2;
package.Dimensions = dm;
PackagingType packType = new PackagingType();
packType.Code = md.packType;// "02";
package.Packaging = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
LabelSpecificationType labelSpec = new LabelSpecificationType();
LabelStockSizeType labelStockSize = new LabelStockSizeType();
labelStockSize.Height = "6";
labelStockSize.Width = "4";
labelSpec.LabelStockSize = labelStockSize;
LabelImageFormatType labelImageFormat = new LabelImageFormatType();
labelImageFormat.Code = "GIF";
labelSpec.LabelImageFormat = labelImageFormat;
shipmentRequest.LabelSpecification = labelSpec;
shipmentRequest.Shipment = shipment;
TransactionReferenceType rft=new TransactionReferenceType();
rft.CustomerContext = md.GoodsList[0].SKU;// "2xKM0765";
request.TransactionReference = rft;
// Console.WriteLine(shipmentRequest);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
shpSvc.Url = "https://onlinetools.ups.com/webservices/Ship";
ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
//if (shipmentResponse.ShipmentResults.Form != null && shipmentResponse.ShipmentResults.Form.Image != null && shipmentResponse.ShipmentResults.Form.Image.GraphicImage != null)
//{
// string labelBuffer = shipmentResponse.ShipmentResults.Form.Image.GraphicImage;
// string LabelPath = AppDomain.CurrentDomain.BaseDirectory + "ups/";// @"F:\褚明杰\fedex\ShipService_v2014_cs\cs\ShipWebServiceClient\Express\International\ShipWebServiceClient\bin\Release\pdf\";
// String LabelFileName = LabelPath + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".png";
// Base64StringToImage(labelBuffer);
//}
if (shipmentResponse.ShipmentResults != null && shipmentResponse.ShipmentResults.ShipmentIdentificationNumber != null)
{
error = "";
return shipmentResponse.ShipmentResults.ShipmentIdentificationNumber;
}
//Console.WriteLine("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
//Console.WriteLine("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
//Console.ReadKey();
error = "shipmentResponse.Response.ResponseStatus.Description";
return "";
}
catch (System.Web.Services.Protocols.SoapException ex)
{
//Console.WriteLine("");
//Console.WriteLine("---------Ship Web Service returns error----------------");
//Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
//Console.WriteLine("SoapException Message= " + ex.Message);
//Console.WriteLine("");
//Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
//Console.WriteLine("");
//Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
//Console.WriteLine("");
//Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
//Console.WriteLine("-------------------------");
//Console.WriteLine("");
error = ex.Message + "shipmentResponse.Response.ResponseStatus.Description" + "SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText + "SoapException XML String for all= " + ex.Detail.LastChild.OuterXml;
return "";
}
//catch (System.ServiceModel.CommunicationException ex)
//{
// Console.WriteLine("");
// Console.WriteLine("--------------------");
// Console.WriteLine("CommunicationException= " + ex.Message);
// Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
// Console.WriteLine("-------------------------");
// Console.WriteLine("");
//}
catch (Exception ex)
{
//Console.WriteLine("");
//Console.WriteLine("-------------------------");
//Console.WriteLine(" General Exception= " + ex.Message);
//Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
//Console.WriteLine("-------------------------");
error = ex.Message + ex.StackTrace;
return "";
}
finally
{
//Console.ReadKey();
}
}
public string GetTrackCodeNew(UPSOrder md,out string error)
{
try
{
//var URL = "https://wwwcie.ups.com/api/shipments/v1/ship";//测试地址
var URL = "https://onlinetools.ups.com/api/shipments/v1/ship";//正式地址
var inquiryNumber = DateTime.Now.ToString("yyyyMMddhhmmss");
var token = UPSTokenHelp.GetUPSToken();
// 创建HttpClient实例
HttpClient client = new HttpClient();
// 设置Basic Auth验证
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//生成一个随机数
var random = new Random().Next(1000, 9990);
// 添加自定义Header
client.DefaultRequestHeaders.Add("transId", inquiryNumber + random.ToString() + "Id");
client.DefaultRequestHeaders.Add("transactionSrc", inquiryNumber + random.ToString() + "Src");
// 创建 HttpRequestMessage 实例
var request = new HttpRequestMessage(HttpMethod.Post, URL);
var shipping = new ShippingRequestModel()
{
ShipmentRequest = new ShipmentRequestNew
{
Request = new Request
{
RequestOption = "nonvalidate ",
SubVersion = "2205",
TransactionReference = new TransactionReference
{
CustomerContext = "CustomerContext"
}
},
Shipment = new ShippingShipment
{
Shipper = new Ship_Shipment_Shipper
{
Name = md.Shiper.PersonName,
AttentionName = "",
ShipperNumber = ShipperNumber,
Phone = new Ship_Shipper_Phone
{
Number = md.Shiper.PhoneNumber,
Extension = "",
},
Address = new AddressFrom
{
AddressLine = new List<string>() { md.Shiper.StreetLines },
City = md.Shiper.City,
StateProvinceCode = md.Shiper.StateOrProvinceCode,
PostalCode = md.Shiper.PostalCode,
CountryCode = md.Shiper.CountryCode
}
},
ShipTo = new Ship_Shipment_ShipTo
{
Name = md.Rever.PersonName,
AttentionName = md.Rever.PersonName,
//Phone=new Ship_Shipper_Phone
//{
// Number=md.Rever.PhoneNumber,
// Extension=""
//},
Address = new AddressTo
{
AddressLine = new List<string>() { md.Rever.StreetLines },
City = md.Rever.City,
StateProvinceCode = md.Rever.StateOrProvinceCode,
PostalCode = md.Rever.PostalCode,
CountryCode = md.Rever.CountryCode,
}
},
ShipFrom = new Ship_Shipment_ShipFrom
{
Name = md.Shiper.PersonName,
Phone = new Ship_Shipper_Phone
{
Number = md.Shiper.PhoneNumber,
Extension = "",
},
Address = new AddressFrom
{
AddressLine = new List<string>() { md.Shiper.StreetLines },
City = md.Shiper.City,
StateProvinceCode = md.Shiper.StateOrProvinceCode,
PostalCode = md.Shiper.PostalCode,
CountryCode = md.Shiper.CountryCode
}
},
PaymentInformation = new PaymentInformation
{
ShipmentCharge = new List<ShipmentCharge> { new ShipmentCharge
{
Type="01",
BillShipper=new BillShipper
{
AccountNumber=ShipperNumber
}
} },
},
Service = new Service
{
Code = md.shipservicecode,
Description = "",
},
Package = new List<Ship_Shipment_Package> { new Ship_Shipment_Package {
Packaging=new CodeAndDescription
{
Code=md.packType,
Description=""
},
Dimensions=new DimensionsNew
{
UnitOfMeasurement=new UnitOfMeasurement
{
Code="IN",
Description="Inches"
},
Length=md.GoodsList[0].Lenght,
Width=md.GoodsList[0].Width,
Height=md.GoodsList[0].Height,
},
PackageWeight=new PackageWeight
{
UnitOfMeasurement=new UnitOfMeasurement
{
Code="LBS",
Description="Pounds",
},
Weight=md.GoodsList[0].Weight.ToString()
}
} },
},
LabelSpecification = new Ship_ShipmentRequest_LabelSpecification
{
LabelImageFormat = new CodeAndDescription
{
Code = "PNG"
},
HTTPUserAgent = "",
LabelStockSize = new LabelStockSize
{
Height = "6",
Width = "4"
}
}
}
};
var bodyStr = JsonConvert.SerializeObject(shipping);
//bodyStr = "{\"ShipmentRequest\":{\"Request\":{\"RequestOption\":\"validate\",\"SubVersion\":\"2205\",\"TransactionReference\":{\"CustomerContext\":\"CustomerContext\"}},\"Shipment\":{\"Description\":null,\"Shipper\":{\"Name\":\"Karmas Far Inc\",\"AttentionName\":\"\",\"CompanyDisplayableName\":null,\"TaxIdentificationNumber\":null,\"Phone\":{\"Number\":\"8045971260\",\"Extension\":\"\"},\"ShipperNumber\":\"44434A\",\"FaxNumber\":null,\"EMailAddress\":null,\"Address\":{\"AddressLine\":[\"11190 White Birch Dr Suite 100\"],\"City\":\"Jacksonville\",\"StateProvinceCode\":\"FL\",\"PostalCode\":\"32226\",\"CountryCode\":\"US\"}},\"ShipTo\":{\"Name\":\"sheila kowall\",\"AttentionName\":\"sheila kowall\",\"CompanyDisplayableName\":null,\"TaxIdentificationNumber\":null,\"Phone\":{\"Number\":\"210-728-4548\",\"Extension\":\"\"},\"FaxNumber\":null,\"EMailAddress\":null,\"Address\":{\"AddressLine\":[\"4184 hwy 11\"],\"City\":\"Enterprise\",\"StateProvinceCode\":\"MS\",\"PostalCode\":\"39330\",\"CountryCode\":\"US\",\"ResidentialAddressIndicator\":null},\"LocationID\":null},\"ShipFrom\":{\"Name\":\"Karmas Far Inc\",\"AttentionName\":null,\"CompanyDisplayableName\":null,\"TaxIdentificationNumber\":null,\"Phone\":{\"Number\":\"9045971260\",\"Extension\":\"\"},\"FaxNumber\":null,\"Address\":{\"AddressLine\":[\"11190 White Birch Dr Suite 100\"],\"City\":\"Jacksonville\",\"StateProvinceCode\":\"FL\",\"PostalCode\":\"32226\",\"CountryCode\":\"US\"}},\"PaymentInformation\":{\"ShipmentCharge\":[{\"Type\":\"01\",\"BillShipper\":{\"AccountNumber\":\"44434A\"},\"BillReceiver\":null,\"BillThirdParty\":null,\"ConsigneeBilledIndicator\":null}],\"SplitDutyVATIndicator\":null},\"Service\":{\"Code\":\"03\",\"Description\":\"\"},\"Package\":[{\"Description\":null,\"Packaging\":{\"Code\":\"02\",\"Description\":\"\"},\"Dimensions\":{\"UnitOfMeasurement\":{\"Code\":\"IN\",\"Description\":\"Inches\"},\"Length\":\"24\",\"Width\":\"11\",\"Height\":\"5\"},\"PackageWeight\":{\"UnitOfMeasurement\":{\"Code\":\"LBS\",\"Description\":\"Pounds\"},\"Weight\":\"6.625000\"}}],\"LabelSpecification\":null},\"LabelSpecification\":{\"LabelImageFormat\":{\"Code\":\"GIF\",\"Description\":null},\"HTTPUserAgent\":\"\",\"LabelStockSize\":{\"Height\":\"6\",\"Width\":\"4\"}}}}";
request.Content = new StringContent(bodyStr, System.Text.Encoding.UTF8, "application/json");
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
// 发送 POST 请求并返回响应结果
var response = client.SendAsync(request).Result;
var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var resObj = JsonConvert.DeserializeObject<ShippingResponseModel>(result);
if(resObj.ShipmentResponse!=null && resObj.ShipmentResponse.ShipmentResults != null)
{
error = "";
var imageBase64 = resObj.ShipmentResponse.ShipmentResults.PackageResults.ShippingLabel.GraphicImage;//面单图片的Base64字符串
var trackingNumber= resObj.ShipmentResponse.ShipmentResults.ShipmentIdentificationNumber;//跟踪码
string LabelPath = AppDomain.CurrentDomain.BaseDirectory + "attached/ups/";
Random rd = new Random();
String LabelFileName = LabelPath + DateTime.Now.ToString("yyyyMMddHHmmssfff") + rd.Next(100, 999).ToString() + ".png";
String LabelFileName2 = LabelPath + trackingNumber + ".png";
Base64StringToImage(imageBase64, LabelFileName);
using (FileStream file = new FileStream(LabelFileName, FileMode.Open))
{
Image img = Image.FromStream(file);
UpsLabel obj3 = new UpsLabel();
var img2 = obj3.RotateImg(img, 90);
img2.Save(LabelFileName2);
}
return resObj.ShipmentResponse.ShipmentResults.ShipmentIdentificationNumber;
}
error = "shipmentResponse.Response.ResponseStatus.Description:" + result;
return "";
}
catch(Exception ex)
{
error = ex.Message + ex.StackTrace;
return "";
}
}
/// <summary>
/// 把base64字符串转化为图片传入base64字符串
/// </summary>
/// <param name="strbase64"></param>
/// <returns></returns>
public static void Base64StringToImage(string strbase64, string path)
{
try
{
strbase64 = strbase64.Replace(' ', '+');
System.IO.MemoryStream stream = new System.IO.MemoryStream(Convert.FromBase64String(strbase64));
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
byte[] b = stream.ToArray();
//byte[] b = stream.GetBuffer();
fs.Write(b, 0, b.Length);
fs.Close();
}
catch (Exception ex)
{
}
}
}
public class UPSOrder
{
public string CustomerTransactionId { get; set; }
public List<UpsGoods> GoodsList { get; set; }
public int? PostId { get; set; }
public Rever Rever { get; set; }
public Shiper Shiper { get; set; }
public string shipservicecode { get; set; }
public string packType { get; set; }
}
public class UpsGoods
{
public decimal Amount { get; set; }
public string CountryOfManufacture { get; set; }
public string Description { get; set; }
public string Height { get; set; }
public string Lenght { get; set; }
public string NumberOfPieces { get; set; }
public decimal Quantity { get; set; }
public string SKU { get; set; }
public decimal Weight { get; set; }
public string Width { get; set; }
}
}