using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Ups1
{
public class Program
{
static void Main()
{
string client_id = "clientid";
string client_secret = "clientSecret";
string ups_account_number = "AccountNumber";
// ***** SHIPPING SERVICE AVAILABLE OPTIONS *****
// Domestic
// 14 = UPS Next Day Air Early
// 01 = UPS Next Day Air
// 13 = UPS Next Day Air Saver
// 59 = UPS 2nd Day Air A.M.
// 02 = UPS 2nd Day Air
// 12 = UPS 3 Day Select
// 03 = UPS Ground
// International
// 11 = UPS Standard
// 07 = UPS Worldwide Express
// 54 = UPS Worldwide Express Plus
// 08 = UPS Worldwide Expedited
// 65 = UPS Worldwide Saver
// 96 = UPS Worldwide Express Freight
// 82 = UPS Today Standard
// 83 = UPS Today Dedicated Courier
// 84 = UPS Today Intercity
// 85 = UPS Today Express
// 86 = UPS Today Express Saver
// 70 = UPS Access Point Economy
// ***** PACKAGE TYPE AVAILABLE OPTIONS *****
// 01 = Bag,
// 02 = Box,
// 03 = Carton/Piece,
// 04 = Crate,
// 05 = Drum,
// 06 = Pallet/Skid,
// 07 = Roll,
// 08 = Tube,
// PACKAGE
// var packages = new List<Package>();
// packages.Add(new Package(0M, 0M, 0M, 60, 0M));
var package_info = new
{
service = "59",
package_type = "02",
Weight = "10",
length = "7",
width = "4",
height = "2",
};
// SHIPPER
var shipper_info = new
{
account_number = ups_account_number,
name = "fromaddressname",
address1 = "addr1",
address2 = "addr2",
address3 = "",
city = "city",
state = "state",
zip = "zipcode",
country = "us",
};
// FROM ADDRESS
var from_address_info = new
{
name = "fromaddressname",
address1 = "addr1",
address2 = "addr2",
address3 = "",
city = "city",
state = "state",
zip = "zipcode",
country = "US",
};
// TO ADDRESS
var to_address_info = new
{
name = "Thomas Jefferson",
address1 = "931 Thomas Jefferson Parkway",
address2 = "",
address3 = "",
city = "Charlottesville",
state = "CO",
zip = "80125",
country = "US",
};
// Get Token
var accessToken = GetToken(client_id, client_secret);
// Use API to get price
var totalCharges = GetShippingCost(accessToken, shipper_info, to_address_info, from_address_info, package_info);
// Show Price
Console.WriteLine("Total Charges: $" + totalCharges);
}
//static string GetToken(string client_id, string client_secret)
//{
// var combineUserAndPassword = client_id + ":" + client_secret;
// var payload = "grant_type=client_credentials";
// var authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(combineUserAndPassword));
// using (var client = new HttpClient())
// {
// //client.DefaultRequestHeaders.Add("Content-Type", "application/json");
// client.DefaultRequestHeaders.Add("x-merchant-id", "string");
// client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
// var response = client.PostAsync("https://wwwcie.ups.com/security/v1/oauth/token", new StringContent(payload, Encoding.UTF8, "application/json")).Result;
// var result = response.Content.ReadAsStringAsync().Result;
// // Convert the JSON response string to an associative array
// var responseArray = JObject.Parse(result);
// // Extract the access token
// var accessToken = responseArray["access_token"].ToString();
// return accessToken;
// }
//}
static string GetToken(string client_id, string client_secret)
{
var combineUserAndPassword = client_id + ":" + client_secret;
var payload = "grant_type=client_credentials";
var authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(combineUserAndPassword));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("x-merchant-id", "string");
client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = client.PostAsync("https://wwwcie.ups.com/security/v1/oauth/token", content).Result;
var result = response.Content.ReadAsStringAsync().Result;
// Check if the request was successful
if (!response.IsSuccessStatusCode)
{
// Handle error, log, or throw an exception
Console.WriteLine("Token request failed: " + result);
return null;
}
// Convert the JSON response string to an associative array
var responseArray = JObject.Parse(result);
// Explicitly check for null before extracting the access token
var accessTokenTokenProperty = responseArray["access_token"];
var accessToken = accessTokenTokenProperty != null ? accessTokenTokenProperty.ToString() : null;
return accessToken;
}
}
static decimal GetShippingCost(string accessToken, dynamic shipper_info, dynamic to_address_info, dynamic from_address_info, dynamic package_info)
{
var version = "v1601";
var requestOption = "Shop";
var query = new System.Collections.Generic.Dictionary<string, string>();
using (var client = new HttpClient())
{
var payload = new
{
RateRequest = new
{
Request = new
{
TransactionReference = new
{
CustomerContext = "CustomerContext"//,
//TransactionIdentifier = "TransactionIdentifier"
}
},
Shipment = new
{
Shipper = new
{
Name = shipper_info.name,
ShipperNumber = shipper_info.account_number,
Address = new
{
AddressLine = new[]
{
shipper_info.address1,
shipper_info.address2,
shipper_info.address3
},
City = shipper_info.city,
StateProvinceCode = shipper_info.state,
PostalCode = shipper_info.zip,
CountryCode = shipper_info.country
}
},
ShipTo = new
{
Name = to_address_info.name,
Address = new
{
AddressLine = new[]
{
to_address_info.address1,
to_address_info.address1,
to_address_info.address1
},
City = to_address_info.city,
StateProvinceCode = to_address_info.state,
PostalCode = to_address_info.zip,
CountryCode = to_address_info.country
}
},
ShipFrom = new
{
Name = from_address_info.name,
Address = new
{
AddressLine = new[]
{
from_address_info.address1,
from_address_info.address2,
from_address_info.address3
},
City = from_address_info.city,
StateProvinceCode = from_address_info.state,
PostalCode = from_address_info.zip,
CountryCode = from_address_info.country
}
},
PaymentDetails = new
{
ShipmentCharge = new
{
Type = "01",
BillShipper = new
{
AccountNumber = shipper_info.account_number
}
}
},
Service = new
{
Code = package_info.service,
Description = "ground"
},
NumOfPieces = "1",
Package = new
{
PackagingType = new
{
Code = package_info.package_type,
Description = "Packaging"
},
Dimensions = new
{
UnitOfMeasurement = new
{
Code = "IN",
Description = "Inches"
},
Length = package_info.length,
Width = package_info.width,
Height = package_info.height
},
PackageWeight = new
{
UnitOfMeasurement = new
{
Code = "LBS",
Description = "Pounds"
},
Weight = package_info.Weight
}
}
}
}
};
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
//client.DefaultRequestHeaders.Add("Content-Type", "application/json");
client.DefaultRequestHeaders.Add("transId", "string");
client.DefaultRequestHeaders.Add("transactionSrc", "testing");
var response = client.PostAsync("https://wwwcie.ups.com/api/rating/v1/Rate?{ToQueryString(query)}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")).Result;
//var response = client.PostAsync("https://wwwcie.ups.com/api/rating/{version}/{requestOption}?{ToQueryString(query)}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")).Result;
var result = response.Content.ReadAsStringAsync().Result;
// Convert the JSON response string to an associative array
var responseArray = JObject.Parse(result);
// Extract the total charges
var totalCharges = Convert.ToDecimal(responseArray["RateResponse"]["RatedShipment"]["TotalCharges"]["MonetaryValue"]);
return totalCharges;
}
}
static string ToQueryString(System.Collections.Generic.Dictionary<string, string> query)
{
var array = query.Select(kvp => "{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}").ToArray();
return "?" + string.Join("&", array);
}
}
}
Note : Change your client id , Account Number and client secret and add the correct from and to address in the above program
After token expire we will get
this error First = {"response": {
"errors": [
{
"code": "250002",
"message": "Invalid Authentication Information."
}
]
}}