Calculating USPS Shipping Rates with PHP

Calculating USPS Shipping Rates with PHP

If you have a custom shopping cart and you want to calculate actual shipping rates from USPS this is the post for you. I hope that by the end of this post you will have an understanding of the process and you can begin implementing USPS rates in your own website.

You may wish to grab a copy of the USPS Rates Manual for yourself.

Things you Need

  • USPS Webtools Account – free but requires registration
  • USPS Username – Comes with the Webtools account
  • cURL
  • PHP – You should know a little bit about using PHP. After all you are about to create a custom USPS shipping calculator.
  • XML – If you know what PHP is you should know what XML is. You should at least know how XML works in a nutshell.
  • SSH access – Many web hosts offer SSH. You don’t HAVE to have it but it can make troubleshooting easier.

USPS Service Codes

  • FIRST CLASS
  • PRIORITY
  • EXPRESS
  • BPM
  • PARCEL
  • MEDIA
  • LIBRARY
  • ALL

Required XML Tags to Complete a Rate Request

The USPS API requires cetain XML tags in the request before it will start its rate calculations. If you fail to provide the required tags USPS will return with an error code. I have provided the required XML tags for you.

  • RateV3Request – Required Once
  • RateV3Request/USERID – Required
  • RateV3Request/Package – Required
  • RateV3Request/Package/Service – Required
  • RateV3Request/Package/ZipOrigination – Required Once
  • RateV3Request/Package/Pounds – Required Once (if it weighs less than a lb use ‘0′ Max: 70lbs)
  • RateV3Request/Package/Ounces – Required (use ‘0′ if you don’t use ounces)
  • RateV3Request/Package/Size – Required (LARGE,REGULAR,OVERSIZE)

Simple XML Request Example

A barebones request was taken straight from the USPS manual. It is a simple XML file that needs to be posted to the USPS server. As you can see it contains all the required XML tags. Of course you will need to change the USERID to your actual USERID that you got from registering with USPS.

<RateV3Request USERID="000AAAAA9999">

<Package ID="1ST">
   <Service>FIRST CLASS</Service>
   <FirstClassMailType>LETTER</FirstClassMailType>
   <ZipOrigination>44106</ZipOrigination>

   <ZipDestination>90210</ZipDestination>
   <Pounds>0</Pounds>
   <Ounces>0.75</Ounces>
   <Size>REGULAR</Size>

   <Machinable>false</Machinable>
</Package>
</RateV3Request>

If you noticed there was only one package included in this request. The USPS API allows multiple packages in one XML request. To lighten the load and time it takes to generate rates for multiple packages it is recommended that you send a single XML request with multiple packages as opposed to sending multiple XML requests for single packages.

You can add more packages to the code by adding another XML package set:

<Package ID="2nd">

The USPS Rate Calculator PHP Function

Finally, the code that you have all been waiting for. This is the PHP function that will return the USPS rate as a decimal value for use in displaying or calculating the shipping cost and final charge to the customer.

<?php
function USPSParcelRate($weight,$dest_zip) {

// ========== CHANGE THESE VALUES TO MATCH YOUR OWN ===========

$userName = 'username'; // Your USPS Username
$orig_zip = '12345'; // Zipcode you are shipping FROM

// =============== DON'T CHANGE BELOW THIS LINE ===============

$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=RateV3&XML=<RateV3Request USERID=\"$userName\">
<Package ID=\"1ST\"><Service>PRIORITY</Service>
<ZipOrigination>$orig_zip</ZipOrigination>
<ZipDestination>$dest_zip</ZipDestination>
<Pounds>$weight</Pounds><Ounces>0</Ounces>
<Size>REGULAR</Size><Machinable>TRUE</Machinable>
</Package></RateV3Request>";

// 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 line above to see xml tags
return $params['RATEV3RESPONSE']['1ST']['1']['RATE'];
}
?>

To use the function you use the following format:

USPSParcelRate($weight,$dest_zip)

An example of this being called on your website would be:

echo USPSParcelRate(3,90210);

If you are not recieving a rate from the USPS servers you need to check what error message they gave. My script will output the entire XML response in html comment tags. This will allow you to view any errors generated by the USPS API. To view this you will need to uncomment the lines specified in the function and simply click view source in your browser and look for the XML data.

Advertisements
By Rz Rasel Posted in Php

5 comments on “Calculating USPS Shipping Rates with PHP

  1. My brother recommended I may like this blog. He was once entirely right. This publish truly made my day. You can not believe simply how so much time I had spent for this information! Thanks!

  2. Good day! I just noticed your webpage: Calculating USPS Shipping Rates with PHP | arzrasel when I was browsing reddit.com. It looks as though someone enjoyed your site so much they decided to bookmark it. I’ll certainly be coming back here more often.

  3. You realize therefore significantly in terms of this topic, made me in my view believe it from so many varied angles. Its like women and men aren’t involved until it’s one thing to do with Girl gaga! Your individual stuffs outstanding. At all times maintain it up!

  4. I just want to tell you that I’m beginner to blogging and definitely liked you’re web page. Most likely I’m likely to bookmark your blog post . You definitely have amazing writings. Cheers for sharing with us your blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s