Calculate Shipping Cost Using UPS OnLine Tools

Before using this code, all you need to do is register for an UPS OnLine Tools account and then apply for a XML Access key using your developer key which you will receive after creating an account. After you get your access key, just plug your username, password and the key into the highlighted line below and you should be good to go!

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;

/// <summary>
/// Summary description for ShippingCalculator
/// </summary>
namespace MyCo.BusinessLogic
{
    public static class ShippingCalculator
    {
        public static decimal GetShippingCost(string shipFromZipCode, string shipToZipCode, string serviceRateCode, string packageWeight)
        {
            decimal shippingCost = -1;
            string URL = "https://www.ups.com/ups.app/xml/Rate";
            WebRequest objRequest = WebRequest.Create(URL);
            objRequest.Method = "POST";
            objRequest.ContentType = "application/x-www-form-urlencoded";

            using (StreamWriter writer = new StreamWriter(objRequest.GetRequestStream()))
            {
                writer.Write(GetAuthXML("accesskey", "username", "password"));
                writer.Write(GetRequestXML(shipFromZipCode, shipToZipCode, serviceRateCode, packageWeight));
                writer.Flush();
                writer.Close();
            }

            objRequest.Timeout = 5000;

            try
            {
                using (WebResponse objResponse = objRequest.GetResponse())
                {
                    XmlDocument xmlResponse = new XmlDocument();
                    xmlResponse.Load(objResponse.GetResponseStream());
                    int responseStatusCode = int.Parse(xmlResponse.SelectSingleNode("//RatingServiceSelectionResponse/Response/ResponseStatusCode").InnerText);

                    if (responseStatusCode == 1)
                    {
                        XmlNodeList xmlNodeList = xmlResponse.SelectNodes(string.Format("/RatingServiceSelectionResponse/RatedShipment/TotalCharges[../Service/Code={0}]/MonetaryValue", serviceRateCode));

                        foreach (XmlElement xmlElement in xmlNodeList)
                        {
                            shippingCost = decimal.Parse(xmlElement.InnerText);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Log exception
            }

            return shippingCost;
        }
        private static string GetAuthXML(string accessLicenseNumber, string userID, string password)
        {
            StringBuilder xmlAuthTemplate = new StringBuilder();

            xmlAuthTemplate.Append("<?xml version="1.0"?>");
            xmlAuthTemplate.Append("<AccessRequest xml:lang="en-US">");
            xmlAuthTemplate.Append(string.Format("<AccessLicenseNumber>{0}</AccessLicenseNumber>", accessLicenseNumber));
            xmlAuthTemplate.Append(string.Format("<UserId>{0}</UserId>", userID));
            xmlAuthTemplate.Append(string.Format("<Password>{0}</Password>", password));
            xmlAuthTemplate.Append("</AccessRequest>");
            xmlAuthTemplate.Append("<?xml version="1.0"?>");

            return xmlAuthTemplate.ToString();
        }
        private static string GetRequestXML(string shipFromZipCode, string shipToZipCode, string serviceRateCode, string packageWeight)
        {
            StringBuilder xmlRequestTemplate = new StringBuilder();

            xmlRequestTemplate.Append("<RatingServiceSelectionRequest xml:lang="en-US">");
            xmlRequestTemplate.Append("<Request>");
            xmlRequestTemplate.Append("<TransactionReference>");
            xmlRequestTemplate.Append("<CustomerContext>Rating and Service</CustomerContext>");
            xmlRequestTemplate.Append("<XpciVersion>1.0001</XpciVersion>");
            xmlRequestTemplate.Append("</TransactionReference>");
            xmlRequestTemplate.Append("<RequestAction>Rate</RequestAction>");
            xmlRequestTemplate.Append("<RequestOption>shop</RequestOption>");
            xmlRequestTemplate.Append("</Request>");
            xmlRequestTemplate.Append("<PickupType>");
            xmlRequestTemplate.Append("<Code>01</Code>");
            xmlRequestTemplate.Append("</PickupType>");
            xmlRequestTemplate.Append("<Shipment>");
            xmlRequestTemplate.Append("<Shipper>");
            xmlRequestTemplate.Append("<Address>");
            xmlRequestTemplate.Append(string.Format("<PostalCode>{0}</PostalCode>", shipFromZipCode));
            xmlRequestTemplate.Append("</Address>");
            xmlRequestTemplate.Append("</Shipper>");
            xmlRequestTemplate.Append("<ShipTo>");
            xmlRequestTemplate.Append("<Address>");
            xmlRequestTemplate.Append(string.Format("<PostalCode>{0}</PostalCode>", shipToZipCode));
            xmlRequestTemplate.Append("</Address>");
            xmlRequestTemplate.Append("</ShipTo>");
            xmlRequestTemplate.Append("<Service>");
            xmlRequestTemplate.Append(string.Format("<Code>{0}</Code>", serviceRateCode));
            xmlRequestTemplate.Append("</Service>");
            xmlRequestTemplate.Append("<Package>");
            xmlRequestTemplate.Append("<PackagingType>");
            xmlRequestTemplate.Append("<Code>02</Code>");
            xmlRequestTemplate.Append("<Description>Package</Description>");
            xmlRequestTemplate.Append("</PackagingType>");
            xmlRequestTemplate.Append("<Description>Rate Shopping</Description>");
            xmlRequestTemplate.Append("<PackageWeight>");
            xmlRequestTemplate.Append(string.Format("<Weight>{0}</Weight>", packageWeight));
            xmlRequestTemplate.Append("</PackageWeight>");
            xmlRequestTemplate.Append("</Package>");
            xmlRequestTemplate.Append("<ShipmentServiceOptions/>");
            xmlRequestTemplate.Append("</Shipment>");
            xmlRequestTemplate.Append("</RatingServiceSelectionRequest>");
            xmlRequestTemplate.Append("</RatingServiceSelectionRequest>");

            return xmlRequestTemplate.ToString();
        }
    }
}
If you liked this post, 🗞 subscribe to my newsletter and follow me on 𝕏!