public IEnumerable <ServiceInfo> DomesticServices(string userId, string password, string zip) { var request = new RateV4Request { UserId = userId, Password = password, Packages = new List <DomesticPackage> { new DomesticPackage { Id = "1", SelectedServiceType = ServiceTypes.All, Pounds = 1, ZipOrigination = zip, ZipDestination = zip, } } }; string response = DoRequest(request); if (HasError(response)) { throw new Exception("Service Request Error\n\n" + response); } var rateResponse = response.ToObject <RateV4Response>(); return((rateResponse.Packages.SelectMany(package => package.Postages, (package, postage) => new ServiceInfo { Id = postage.ClassId, FullName = postage.MailService, })).Distinct()); }
public static RateV4Request GetDomesticRequestWithZipDestinationNull() { var request = new RateV4Request { UserId = Settings.Default.UspsUserId, Password = Settings.Default.UspsPassword, Packages = new List <DomesticPackage> { new DomesticPackage { Container = "RECTANGULAR", Height = 10, Length = 10, Ounces = 6, Pounds = 5, ReturnLocations = false, ShipDate = String.Format( "{0:dd-MMM-yyyy}", DateTime.Now.Date), Value = "600.00", Width = 10, ZipDestination = null, ZipOrigination = "18507", SelectedServiceType = ServiceTypes.Express, SpecialServices = new SpecialServices { SpecialService = new[] { "11" } }, }, } }; return(request); }
public RateV4Response Get(RateV4Request request) { string response = DoRequest(request); return(response.Contains("<Error>") && !response.Contains("<RateV4Response>") ? new RateV4Response { Error = response.ToObject <RequestError>() } : response.ToObject <RateV4Response>()); }
private RateV4Request CreateDomesticRequest(GetShippingOptionRequest shipmentPackage, string username, string password) { var request = new RateV4Request { UserId = username, Password = password, Packages = new List <DomesticPackage>() }; decimal totalWeight = _shippingService.GetTotalWeight(shipmentPackage); IEnumerable <List <USPSVolumetrics> > splitVolumetrics = SplitShipmentByVolumetrics(shipmentPackage, totalWeight); foreach (var item in splitVolumetrics) { foreach (ServiceTypes baseService in EnabledBaseDomesticServices()) { request.Packages.Add(CreateDomesticPackage(shipmentPackage, item, baseService)); } } return(request); }
private List <ShippingOption> DoDomesticRequest(GetShippingOptionRequest shipmentPackage, decimal minimumShippingRate, string password, string username) { IRateResponse response; RateV4Request domesticRequest = CreateDomesticRequest(shipmentPackage, username, password); try { response = _rateService.Get(domesticRequest); } catch (Exception e) { throw new Exception("Unhandled exception with domestic request:\n\n" + domesticRequest.ToXmlString(), e); } return(response.Error == null ? InterpretShippingOptions((RateV4Response)response, minimumShippingRate) : new List <ShippingOption> { new ShippingOption { Name = response.Error.Description } }); }
private string DoRequest(RateV4Request request) { return(_request.GetResponse(_apiUrl, string.Format("API=RateV4&XML={0}", request.ToXmlString()))); }
public async System.Threading.Tasks.Task <IActionResult> GetAsync() { var webRootPath = _hostingEnvironment.WebRootPath; Package package = new Package() { PackageId = "0", Service = "ALL", FirstClassMailType = "PACKAGE SERVICE", ZipOrigination = "90001", ZipDestination = "10001", Pounds = 0, Ounces = 6, Container = "VARIABLE", Size = "REGULAR", Machinable = "FALSE" }; string userId = _configuration["USPS:UserId"]; RateV4Request request = new RateV4Request { Package = package, UserId = userId }; XmlSerializer xsSubmit = new XmlSerializer(typeof(RateV4Request)); var xml = ""; using (var sww = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sww)) { xsSubmit.Serialize(writer, request); xml = sww.ToString(); } } var requestXmlFile = Path.Combine(webRootPath, "request.xml"); System.IO.File.WriteAllText(requestXmlFile, xml); string uspsUrl = "http://production.shippingapis.com/ShippingAPI.dll"; var formData = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("API", "RateV4"), new KeyValuePair <string, string>("XML", xml) }); HttpClient httpClient = new HttpClient(); var response = await httpClient.PostAsync(uspsUrl, formData); var content = await response.Content.ReadAsStringAsync(); var responseXmlFile = Path.Combine(webRootPath, "response.xml"); System.IO.File.WriteAllText(responseXmlFile, content); try { XmlSerializer deserializer = new XmlSerializer(typeof(RateV4Response)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); RateV4Response responseJson = (RateV4Response)deserializer.Deserialize(ms); return(Ok(responseJson)); } catch (Exception ex) { XmlSerializer serializer = new XmlSerializer(typeof(Error)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); Error error = (Error)serializer.Deserialize(ms); return(NotFound(error)); } }
public Request() { _request = new RateV4Request(); }
internal static async Task <List <UspsApi.Models.RateAPI.Response.Package> > FetchRatesAsync(List <UspsApi.Models.RateAPI.Request.Package> input) { // limit is 25 packages per request string requestGuid = Guid.NewGuid().ToString(); Log.Information("{area}: New request for {packageTotal} packages. {requestGuid}", "FetchRates()", input.Count, requestGuid); List <UspsApi.Models.RateAPI.Response.Package> output = new(); RateV4Request request; int index = 0; while (index < input.Count) { request = new RateV4Request { USERID = UspsApiUsername, Revision = "2", Package = input.Skip(index).Take(25).ToList() }; Log.Information("{area}: Fetching rates for {packageCount} package(s). {requestGuid}", "FetchRates()", request.Package.Count, requestGuid); XmlSerializer xsSubmit = new(typeof(RateV4Request)); var xml = ""; using (var sww = new StringWriter()) { using XmlWriter writer = XmlWriter.Create(sww); xsSubmit.Serialize(writer, request); xml = sww.ToString(); } string uspsUrl = "https://secure.shippingapis.com/ShippingAPI.dll"; var formData = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("API", "RateV4"), new KeyValuePair <string, string>("XML", xml) }); HttpClient httpClient = new() { Timeout = TimeSpan.FromSeconds(120) }; HttpResponseMessage response = null; int retryCount = 0; DateTime responseTimer = DateTime.Now; retry: while (response == null || response.StatusCode != System.Net.HttpStatusCode.OK) { if (retryCount > 50) { Log.Error("{area}: USPS Failed to Respond after 50 attempts. {requestGuid}", "FetchRates()", retryCount, requestGuid); throw new UspsApiException("408: After many attempts, the request to the USPS API did not recieve a response. Please try again later."); } if (retryCount > 0) { Log.Warning("{area}: USPS Failed to Respond after " + retryCount + " seconds. Attempt {retryCount}. {requestGuid}", "FetchRates()", retryCount, requestGuid); } try { response = await httpClient.PostAsync(uspsUrl, formData).ConfigureAwait(false); Thread.Sleep(2500 * retryCount); httpClient.CancelPendingRequests(); retryCount++; } catch { httpClient.CancelPendingRequests(); retryCount++; goto retry; } } TimeSpan responseTime = DateTime.Now.TimeOfDay.Subtract(responseTimer.TimeOfDay); var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); Log.Information("{area}: USPS response received in {responseTime} ms. {requestGuid}", "FetchRates()", responseTime.Milliseconds, requestGuid); try { if (content.StartsWith("<Error")) // detect if there was an error { XmlSerializer deserializer = new(typeof(Error)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); Error responseJson = (Error)deserializer.Deserialize(ms); Log.Warning("{errorNumber}: {errorDescription} {requestGuid}", "FetchRates()", responseJson.Number, responseJson.Description, requestGuid); Package newResponse = new() { ID = input.First().ID, Error = responseJson }; return(new List <Package>() { newResponse }); } else { XmlSerializer deserializer = new(typeof(RateV4Response)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); RateV4Response responseJson = (RateV4Response)deserializer.Deserialize(ms); index += 25; foreach (UspsApi.Models.RateAPI.Response.Package pkg in responseJson.Package) { if (pkg.Error != null) { Log.Warning("{area}: USPS Returned Error: {uspsErrorNumber} {uspsErrorDescription} {requestGuid}", "FetchRates()", pkg.Error.Number, pkg.Error.Description, requestGuid); } output.Add(pkg); } } } catch (Exception ex) { Log.Error("{area}: Exception: {ex} {requestGuid}", "FetchRates()", ex.ToString(), requestGuid); throw new UspsApiException(ex); } } if (output.Count != input.Count) { // something went wrong because counts should always match Console.WriteLine("Counts did not match between input and output"); Log.Error("{area}: Counts did not match between input and output. {requestGuid}", "FetchRates()", requestGuid); throw new UspsApiException("Counts did not match between input and output"); } return(output); }