Skip to content

Instantly share code, notes, and snippets.

@ahwm
Last active October 30, 2025 16:40
Show Gist options
  • Select an option

  • Save ahwm/c49c4e5949d01f2b5533e28ee46d0654 to your computer and use it in GitHub Desktop.

Select an option

Save ahwm/c49c4e5949d01f2b5533e28ee46d0654 to your computer and use it in GitHub Desktop.
USPS Rates Basic Example
try
{
using (var usps = new USPSRates(UseUSPSSandbox, USPSClientId, USPSClientSecret))
{
Dictionary<string, object> rates = usps.GetRates(FromZip, toZip, weightIn / 16); // weight in pounds
foreach (var rate in (JArray)rates["rateOptions"])
{
ListItem li = new ListItem();
string service = ((JArray)rate["rates"])[0]["productName"].ToString();
if (service == "")
continue;
decimal amount = Convert.ToDecimal(rate["totalBasePrice"]);
li.Text = "USPS " + service + " " + amount.ToString("c");
li.Value = amount.ToString("c") + "^USPS " + service;
if (ShipService.Items.FindByValue(li.Value) != null)
continue;
ShipService.Items.Add(li);
}
}
}
catch
{
}
public class USPSRates : IDisposable
{
private readonly HttpClient _client;
public USPSRates(bool sandbox, string clientId, string clientSecret)
{
_client = new HttpClient
{
BaseAddress = new Uri(sandbox ? "https://apis-tem.usps.com/" : "https://apis.usps.com/")
};
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new { client_id = clientId, client_secret = clientSecret, grant_type = "client_credentials" };
using (var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"))
{
var resp = _client.PostAsync("oauth2/v3/token", content).GetAwaiter().GetResult();
resp.EnsureSuccessStatusCode();
var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(resp.Content.ReadAsStringAsync().GetAwaiter().GetResult());
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result["access_token"].ToString());
}
}
public Dictionary<string, object> GetRates(string originZip, string destinationZip, decimal weightInPounds)
{
var requestBody = new
{
originZIPCode = originZip,
destinationZIPCode = destinationZip,
weight = weightInPounds,
mailClasses = new string[] { "PRIORITY_MAIL", "FIRST-CLASS_PACKAGE_SERVICE", "USPS_RETAIL_GROUND" },
width = 0,
length = 0,
height = 0,
priceType = "COMMERCIAL",
};
using (var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json"))
{
var response = _client.PostAsync("prices/v3/total-rates/search", content).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
}
}
public void Dispose()
{
_client.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment