USPS Shipping API with PHP
Calculating the shipping cost for different USPS services with usps shipping api is pretty simple.For calculating the actual shipping cost of your item simply pass your product weight and zip codes to the shipping api .For using this usps shipping api you must signup with usps.
when you get the usps shipping api key (username) from the usps then you have to create a file with usps.php and copy and paste the following codes.
<?php
function USPSParcelRate($weight,$dest_zip,$origin_zip ,$pack_size="REGULAR",$userName,$servicecode) {
// =============== DON'T CHANGE BELOW THIS LINE API CALL===============
$url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$data = "API=RateV4&XML=<RateV4Request USERID=\"$userName\"><Package ID=\"1ST\"><Service>ALL</Service><ZipOrigination>$orig_zip</ZipOrigination><ZipDestination>$dest_zip</ZipDestination><Pounds>$weight</Pounds><Ounces>0</Ounces><Container/><Size>$pack_size</Size><Machinable>FALSE</Machinable></Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$data = strstr($result, '<?');
// echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
// echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see the full array
return $params['RATEV3RESPONSE']['1ST'][$servicecode]['RATE'];
}
$res = USPSParcelRate($weight,$dest_zip,$origin_zip ,"REGULAR",$userName,$servicecode);
echo "Price ".$res;
?>
The available usps methods are follows.
//Domestic Services The USPS updated their Services Name on last month Aprl2013
/* Customized For getting Service name and Price as array*/
function filterServiceName($serviceName){
$serviceNameKey = str_replace("<sup>&reg;</sup>", "", $serviceName);
$serviceNameKey = str_replace("<sup>&trade;</sup>", "", $serviceNameKey);
$serviceNameKey = str_replace("<sup>™</sup>", "", $serviceNameKey);
$serviceNameKey = str_replace("<sup>®</sup>", "", $serviceNameKey);
$serviceNameKey = str_replace("l<sup>®</sup>", "", $serviceNameKey);
return $serviceNameKey;
}
function removeDay($serviceName){
$serviceName = str_replace(array(' 1-Day',' 2-Day',' 3-Day',' Military',' DPO'), '', $serviceName);
return $serviceName;
}
$ship_postage = '';
$servicesNotConfigurated = array();
$document_xml = new DomDocument; // Instanciation d'un DOMDocument
$new_xml = $data;
$document_xml->loadXML($new_xml); // On charge
$matchingNodes = $document_xml->getElementsByTagName("Postage");
// print_r($matchingNodes);
if ($matchingNodes != NULL) {
for ($i = 0; $i < $matchingNodes->length; $i++) {
$currNode = $matchingNodes->item($i);
$serviceName = $currNode->getElementsByTagName("MailService");
$serviceName = $serviceName->item(0);
$serviceNameKey = filterServiceName($serviceName->nodeValue);
$serviceNameKey = removeDay($serviceNameKey);
if (!isset($ship_postage[$serviceNameKey])) {
$ship_postage[$serviceNameKey] ['rate'] = 0;
}
$this_rate = $currNode->getElementsByTagName("Rate");
$this_rate = $this_rate->item(0);
$this_rate = $this_rate->nodeValue;
$ship_postage[$serviceNameKey] ['rate'] = $this_rate;
}
echo "<pre/>";
print_r($ship_postage);
}
/* Customized */
If you want to find a particular service cost with usps shipping api you can use the following code too.
<?php
/* This section will help you to find a usps service price with its name
foreach($params as $kesService=>$valServices){
//print_r($valServices);
foreach($valServices as $keyScode=>$vaScode){
foreach($vaScode as $innerkey=>$valinner){
$service_name = trim(str_replace("<sup>&reg;</sup>","",$valinner['MAILSERVICE']));
if(strtolower($service_name) == strtolower(trim($serviceName))){
return $valinner['RATE'];
exit;
}
}
}
}
*/
?>
The new service names are.
$DomesticServices[0] ="Priority Mail Express 1-Day";
$DomesticServices[1]="Priority Mail Express 1-Day Hold For Pickup";
$DomesticServices[2]="Priority Mail Express 1-Day Flat Rate Boxes";
$DomesticServices[3]="Priority Mail Express 1-Day Flat Rate Boxes Hold For Pickup";
$DomesticServices[4]="Priority Mail Express 1-Day Flat Rate Envelope";
$DomesticServices[5]="Priority Mail Express 1-Day Flat Rate Envelope Hold For Pickup";
$DomesticServices[6]="Priority Mail Express 1-Day Legal Flat Rate Envelope";
$DomesticServices[7]="Priority Mail Express 1-Day Legal Flat Rate Envelope Hold For Pickup";
$DomesticServices[8]="Priority Mail Express 1-Day Padded Flat Rate Envelope";
$DomesticServices[9]="Priority Mail Express 1-Day Padded Flat Rate Envelope Hold For Pickup";
$DomesticServices[10]="Priority Mail 1-Day";
$DomesticServices[11]="Priority Mail 1-Day Large Flat Rate Box";
$DomesticServices[12]="Priority Mail 1-Day Medium Flat Rate Box";
$DomesticServices[13]="Priority Mail 1-Day Small Flat Rate Box";
$DomesticServices[14]="Priority Mail 1-Day Flat Rate Envelope";
$DomesticServices[15]="Priority Mail 1-Day Legal Flat Rate Envelope";
$DomesticServices[16]="Priority Mail 1-Day Padded Flat Rate Envelope";
$DomesticServices[17]="Priority Mail 1-Day Gift Card Flat Rate Envelope";
$DomesticServices[18]="Priority Mail 1-Day Small Flat Rate Envelope";
$DomesticServices[19]="Priority Mail 1-Day Window Flat Rate Envelope";
$DomesticServices[20]="First-Class Mail Postcards";
$DomesticServices[21]="First-Class Mail Large Postcards";
$DomesticServices[24]="Standard Post";
$DomesticServices[25]="Media Mail";
$DomesticServices[26]="Library Mail";
Also the size limits and packages are described here. Download script ?
14 thoughts on “USPS Shipping API with PHP”
I just tried this script and nothing, no response, no error. Is this script updated to the latest API
What do I alter to get international rates? Thanks for the code.
change
$xmlPost = 'API=IntlRateV2&XML=< IntlRateV2Request USERID=USER_NAME>';
also no need of passing destination zip code.
Thanks. I see how to get the return results back for the international rates, but I have trouble getting your code to break the shipping type with rates apart. Do you have any suggestions? Thanks again for the great code.
Hi,
I have used this API, Its calculating the shipping cost but also the Notice error:
Notice: Undefined offset: 1 in /var/www/html/usps/usps.php on line 90
Please Help,
The notice errors are not critical. Once its in production mode you will not see these type of errors.
You can avoid it by checking the array index of following .
if(isset($xml_elem['attributes']))
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
Thanks for this post.IT is very much useful for me.
But in result i am not getting the price of priority mail express.I have updated the version of api but still not getting the answer.
Please advice.
Thanks
In USPS latest update they limited few services to some region so the zip code you are using may not support the priority mail express.
The list you will get from USPS site.
Thanks a lot….:)
I got this web page fropm my paal who told me regarding this website and
at the moment this time I amm browsing this web site and reading
very informative articles here.
Awesome post.
dosent work at all!
USPSParcelRate is not defined function!
Please download the API file and just follow the instruction,
Let me know the status.
Really Good info about auto transport.