Main menu
WalkswithMeAPI PHPUSPS Shipping API with PHP

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.

USPS Shipping APi

usps shipping api registration

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("&lt;sup&gt;&amp;reg;&lt;/sup&gt;", "", $serviceName); $serviceNameKey = str_replace("&lt;sup&gt;&amp;trade;&lt;/sup&gt;", "", $serviceNameKey); $serviceNameKey = str_replace("&lt;sup&gt;&#8482;&lt;/sup&gt;", "", $serviceNameKey); $serviceNameKey = str_replace("&lt;sup&gt;&#174;&lt;/sup&gt;", "", $serviceNameKey); $serviceNameKey = str_replace("l&lt;sup&gt;&#174;&lt;/sup&gt;", "", $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("&lt;sup&gt;&amp;reg;&lt;/sup&gt;","",$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 ?

Download946 downloads

14 thoughts on “USPS Shipping API with PHP

      1. 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.

    1. 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']);

  1. 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

    1. 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.

  2. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

FacebookTwitterGoogle+RSS