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. After giving up searching the internet for PHP scripts or examples of implementing USPS rates I decided to create my own. 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.

The function discussed below is used for communicating with the United States Postal Service (USPS). If you are looking for the United Postal Service (UPS) function see, Calculating UPS Shipping Rate with PHP.

After looking through the USPS rates manual I begain to try and create a working script. None of the examples in the manual worked for me so I called them up. They ended up just moving my account from testing to production. If you are just starting out I would suggest you call them and start mentioning how their examples didn’t produce the same results and you are attempting to create an application using their API.

When I called USPS the lady on the phone said, “I don’t know what you are talking about. I’ll just move your account to production”. Once I was moved to the production server all of the examples in the user manual worked and I was on my way to creating my very own implementation of the USPS rates API.

I am still not sure why they provide a testing server if it doesn’t work the same way as the production server.

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
  • serverReporter

  • cURL – Most LAMP (Linux, Apache, Mysql, PHP) web hosts have this installed by default. If you are not sure you have this installed on your server you can use the serverReporter script. Just copy and paste the file upload to your webserver and view it. Go here if you want to know more about the serverReporter.
  • 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) {

// This script was written by Mark Sanborn at http://www.marksanborn.net
// If this script benefits you are your business please consider a donation
// You can donate at http://www.marksanborn.net/donate.  

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

I have created a working model of the rates calculation that will compare rates between USPS and UPS.

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);

Troubleshooting

 
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.

Future Versions and More

 
I plan to create a more intricate version that will have many more options. Instead of being a simple function it will be a complete rate calculation tool. I plan to eventually create a framework that allows developers an easy and quick way to develop entire full feature shipping modules. The current open source shopping projects in my opinion are very lacking and do not really allow the users complete control to integrate with their own systems or systems that are already in place. The current solutions are more like a pre-built website with a shipping module. My framework would be for those who wish to create their own shipping systems or integrate with an existing one.

So, what would you like to see in a framework? What options and configurations would you like to see? Please leave a comment below.

Also stay tuned for my post about how I created a script that calculates how many widgets will fit in a box before having to add another box to the shipping total. Many sites will end up charging the customer one package for the total weight of the cart. Other times they will charge as if each widget was shipped in its own box. I will discuss why each of these methods are flawed and how I found a solution.


Was this information useful?


87 Responses to "Calculating USPS Shipping Rates with PHP"
  1. [...] If you are looking for the United States Postal Service (USPS) function see, Calculating USPS Shipping Rates with PHP. [...]

  2. Chaaban on May 31st, 2008

    $orig_Zip = ‘12345′; // Zip code you are shipping FROM

    change that to

    $orig_zip = ‘12345′ // the capital letter (of the Z) will cause problem ;)

  3. Mark Sanborn on May 31st, 2008

    Lol, Nice catch.

    When I wrote the function I tested everything and then added those variable declarations after the fact and forgot to test it again.

  4. Dirkus on June 12th, 2008

    The USPS testing server is still non functional. I called the 800 number and told them that. I then told them that “I had heard that the testing server was broken, but the production server worked.” The gal just enabled my account for the production server.

    I just want you share that the test server is still broken.

  5. Mark Sanborn on June 12th, 2008

    Dirkus,

    Thanks for the status report. :)

  6. My Blog is Now 1 Year Old on July 8th, 2008

    [...] Calculating USPS Shipping Rates with PHP [...]

  7. Mettled on July 11th, 2008

    I must be doing something wrong. I have my document uspstest.php as follows:

    This calls on your php function, obviously filled out with my user name and zip code (do I not need my password?). But with the lines uncommented all I get is:

    Array
    (
    )

    Perhaps this is due to the server problems you mentioned. I just wanted to make sure I was taking what you have here and implementing it properly.

    By the way, you are my hero because I was able to use your UPS shipping calculator successfully. I’ve had a headache all week trying to figure this stuff out. Is there any chance you could email me your “working model” — without your account info obviously — because that’s exactly what I’m trying to do.

    Thanks for everything!

  8. Mettled on July 11th, 2008

    Oops. I guess my uspstest.php didn’t show because the enclosing code. Here it is without:

    include(“usps.php”);

    $weight = ‘5′;
    $dest_zip = ‘90210′;

    echo USPSParcelRate($weight,$dest_zip);

  9. bill on July 31st, 2008

    Hi I am getting this :
    Array
    (
    )

    with nothing working ?

    you know what is wrong?

  10. Mark Sanborn on August 1st, 2008

    Bill,
    Are you on production or testing server? do you have the username and password put in there?

  11. Carl on August 2nd, 2008

    Mark,
    How would I go about getting rates for both “PARCEL” and “PRIORITY”, the last line which returns the value seems to be set in stone:
    return $params['RATEV3RESPONSE']['1ST']['17']['RATE'];

    PARCEL would be :
    return $params['RATEV3RESPONSE']['1ST']['4']['RATE'];

  12. Carl on August 2nd, 2008

    Mark,
    It seems I have found the answer to my own post,
    instead of:
    return $params['RATEV3RESPONSE']['1ST']['1']['RATE'];
    I use:
    return $params['RATEV3RESPONSE']['1ST'][$level['3']]['RATE'];

    This allows for all params to be returned.
    I have heavily modified your script, and it works great!

  13. Mark Sanborn on August 2nd, 2008

    Carl,
    I wrote a seperate function for parcel vs priority.

    Glad you were able to figure it out!

  14. Mike on August 6th, 2008

    I keep getting two “Undefined offset: 1″ errors, both in this line:

    list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);

    I have tried unsuccessfully to fix this. I know it has something to do with an undefined set in the arrays. I have not changed any of the code. I also see no one else reporting any errors like this.

    Any help at all would be greatly appreciated.

  15. Keith on August 11th, 2008

    When I run your function as standalone code, it works find. But when I import it into my other code, I get “Undefined offset: 1″ errors. The backtrace seems to point to the line :
    $level = array();

    based on displays I can see that I am getting a proper return from USPS.

    Hope you can point me in the right direction.

  16. T Munk on August 14th, 2008

    Some more data about USPS’s broken test server:

    If you are setting up the code above and get back the empty array on testing:

    array
    (
    )

    you can change the line:
    $result=curl_exec ($ch);
    to
    if (!$result=curl_exec ($ch)) {print “cURL Failed to connect!”;} else {print “$result”;}
    and you’ll get the entire response from the test server, which is informative as to what’s wrong with the test server.

    The error I get is:
    HTTP/1.1 100 Continue
    Server: Microsoft-IIS/5.0
    Date: Thu, 14 Aug 2008 20:42:37 GMT
    HTTP/1.1 200 OK
    Server: Microsoft-IIS/5.0
    Date: Thu, 14 Aug 2008 20:42:37 GMT
    Connection: close

    80040b1a
    API Authorization failure. RateV3 is not a valid API
    name for this protocol.
    UspsCom::DoAuth

    which indicates that the test server thinks that “API=RateV3″ is not a valid request via the API, which, of course, is completely loopy.

    Additionally, for those who’ve commented about “Where do I put my password?”, you should be aware that, according to the manual, the API does not use your password, so you don’t need to put it anywhere.

  17. T Munk on August 14th, 2008

    Update:
    After emailing the USPS support with the error message above, they upgraded my account to production with no further comment, and Mark’s test script above now works perfectly.

    Perhaps they don’t ever intend to fix the test server, considering how long it’s stayed broken. |:

  18. Mark Sanborn on August 14th, 2008

    T Munk, yeah their test servers are completely worthless. :(

  19. Keith on August 18th, 2008

    when I was working with USPS support, they indicated that RateV3 does not work in the test server, that you need to use RateV2 instead.

  20. Mark Sanborn on August 18th, 2008

    Keith, What good is testing on the RateV2 server when the production server uses RateV3. I wouldn’t have accepted that answer from tech support.

    I would request to move to production since their test server is a joke.

  21. T Munk on August 18th, 2008

    Quote: Keith-
    “when I was working with USPS support, they indicated that RateV3 does not work in the test server, that you need to use RateV2 instead.”

    Well, it would be nice if USPS would document that more visibly in their dev guide. (:

    Well, at least those who come to this blog will know. :D

  22. Barbara on August 18th, 2008

    I did try testing on the RateV2 server, but even that is broken — I got an error message that the origination zip code was invalid. Everything worked immediately on the production server (thank you for both this and the ups code).

    Don’t waste your time dealing with the test server.

  23. David Tobey on August 27th, 2008

    Just to summarize my experience, I tried asking USPS to activate me on their production server right away but they said I had to submit at least 3 successful test requests on their test server first.

    That’s a surprising policy, being that submitting even one successful test request is impossible(!)

    When I called back explaining about the RateV3 error, they said I had to send an email explaining the problem instead. Waiting for a reply as I type.

  24. Ian on September 2nd, 2008

    Hello Mark,
    This is just the thing I’ve been looking for. Thanks.
    I’m having some trouble, when i run the script i get nothing. no errors, no shipping rates etc. just a blank page.

    i tried to run a test similar to the one abot

    include(‘usps_shipping_calc.php’);

    $weight = ‘5′;
    $dest_zip = ‘95926′;

    echo USPSParcelRate($weight, $dest_zip);

    any help would be greatly appreciated

    Thanks

  25. Ian on September 2nd, 2008

    I think i just figured it out. I uncommented the section at the bottom, i’m now getting errors like other.
    I’m on the phone now with usps getting my account switch to production. Thanks

  26. Mark Sanborn on September 2nd, 2008

    Yeah thats why I recommened just going to production right away. :)

  27. Mike on September 8th, 2008

    Hi, I’m having problem when i user ready made script to find real time shipping USPS rate.. I try to enter username and origination zip code. i got Connection: close 80040b1a Authorization failure. Perhaps username and/or password is incorrect. UspsCom::DoAuth error. Can anyone help me out to solve this error? waiting for reply…

  28. Mark Sanborn on September 9th, 2008

    Do you have access to the USPS production servers? If not call them up and ask them to give you access.

    DoAuth error means you have the wrong username/password.

  29. Mike on September 24th, 2008

    yes. i got the result for USPS domestic and international rate. But i have one problem how to use dimensions height,weight,length of product to count exact weight. And i have to generate shipping label for each too…
    Pl help me. i have all access permission for production server.

  30. Mark Sanborn on September 24th, 2008

    I currently have a program that will generate shipping labels with perl. Would you like that or would you want one written in PHP?

    I plan on doing both in the future anyways.

  31. Mike on September 24th, 2008

    First of all, Thanks a lot..4 reply. If you have ready script for shipping label generate for USPS in Perl. Just put it on net. I’ll use it in my php file.
    Thanks..
    waiting for your label generator file…
    I use this script for my company. so, i change my mail address to company…

  32. Mike on September 26th, 2008

    Hi Mark,
    Do u have script for generating USPS shipping Label either in perl or php? it is good enought for me..
    thanks..
    waiting….

  33. Mark Sanborn on September 26th, 2008

    Mike,
    I’ll post it on here later today.

  34. Robert Saylor on October 26th, 2008

    Thanks for the great script. I’ve been trying to get this thing to work in the test area… I should have read all these posts 1st lol. Well, I just requested to be placed on the production server.

    BTW, would you happen to have a FedEx function?

  35. Mark Sanborn on October 27th, 2008

    Robert,

    FedEx actually provides sample PHP code with their development kit. It’s pretty easy to use check it out.

  36. steve on November 4th, 2008

    The following XML worked for me when making a request to the test server.

    $data = ‘API=RateV2&XML=
    EXPRESS1002220008
    105Flat Rate BoxREGULAR’;

    The test server doesn’t yet accept requests from RateV3.

  37. Anit Parikh on November 17th, 2008

    Hi Mark,

    Would you mind sharing your source code for the working model (rateCompare.php)?

    Thanks

  38. Kate on November 19th, 2008

    Thank you so much for this code. I am currently waiting to be switched to the production server, so I will see how that goes.

    Do you (or does anybody) have or know of a similar type script that would get international shipping rates depending on what country you ship to?

    Thank you!!

  39. Mark Sanborn on November 19th, 2008

    Kate,
    Just send me a some info about what you want to do in my contact form and I’ll help you in via email or IM.

    Mark

  40. Faisal on November 25th, 2008

    Good Work!

  41. Robert on November 28th, 2008

    Excellent work Mark. You saved me a lot of time this week. I implemented both your UPS and USPS code for one of my clients to test.

    I can confirm that the USPS test server is really still broken. It does respond to RateV2 requests, but doesn’t recognize any sender ZIP code as valid. I sent them an e-mail about it and got access to the production server in about 10 minutes.

    Do you have a way, preferably PHP but perl would be OK too, to actually ship a product and get a shipping label back? I’m not sure if we’re going to use UPS or USPS yet, but I will definitely need to ship in real time and have a shipping label generated for each order. You can contact me directly via e-mail or my web site if that code isn’t available to the general public.

    Here’s some code I was using while testing the USPS system. Others might be able to use it as well.

    In the USPS function change the service tag to ONLINE (ALL and ONLINE seem to generate the same result so I don’t know the difference) so the full request looks like this:

    ONLINE
    $orig_zip
    $dest_zip
    $weight
    0
    $container
    REGULAR
    $width
    $length
    $height
    $girth
    TRUE
    $shipdate

    Then at the end of the function return an array like so:

    return $params['RATEV3RESPONSE']['1ST'];

    Now in the actual calling PHP code you can look at all of the rates like this:

    $usps_rates = USPSParcelRate($usps_service,$zip,$length,$width,$height,$weig
    ht);

    foreach($usps_rates as $key=>$values) {
    $service = $values["MAILSERVICE"];
    $rate = $values["RATE"];
    $commitdate = $values["COMMITMENTDATE"];
    if($service != $rate) {
    echo “   $ $rate – $service – $commitdate\n”;
    }
    }

    That will print the service name, cost and for Express Mail the estimated delivery date.

    There’s some stuff in the returned array that didn’t look useful, or maybe my code was bad. But anyway, the silly test for $service != $rate stops displaying the junk.

    Keep up the good work at the Google site.

  42. Mark Sanborn on November 29th, 2008

    Robert,

    To quickly answer your question on the UPS label printing, the answer is yes. The bad news is that we don’t have it implemented yet. We are working on that part. It is much trickier and to actually do it you have to be certified with UPS. For these reasons it has been put off but I assure you we will have it done soon.

    For USPS you can print a label out and get the free tracking number on priority quite easily, but you cannot attach postage AFAIK.

    I’ll port the Perl label generation code to PHP and post it when I get it done.

    Mark

  43. Printing a Label for USPS with PHP on December 1st, 2008

    [...] you have been following the posts on USPS you should know how to calculate USPS shipping rates with PHP. Today we are going to use the same USPS API to print out a label. One of the advantages of this is [...]

  44. Sulaiman on December 31st, 2008

    Why pull your hair out on this one? When you will find working PHP demos that work with the USPS. Here is the link http://freshsoftware.net/scripts_for_sale/usps/

  45. Mark Sanborn on December 31st, 2008

    Sulaiman,

    My scripts are working perfectly and they are FREE for all to use. Enjoy

  46. Sujen on January 20th, 2009

    Hi,
    I have applied this code for calculating real time shipping cost but still getting ….
    “HTTP/1.1 200 OK Connection: close Date: Tue, 20 Jan 2009 11:45:22 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET 80040b1a API Authorization failure. RateV2 is not a valid API name for this protocol. UspsCom::DoAuth”

    please help me.

  47. Mark Sanborn on January 20th, 2009

    Try changing ratev2 to RateV3 in your $data variable. Also, are you trying to use this script on an ASP server?

  48. aryan on January 21st, 2009

    Where do i enter my password for the USPS API.

  49. Mark Sanborn on January 22nd, 2009

    You don’t…

  50. Scott on January 27th, 2009

    Hi,

    Great script. But can you help me figure out how to calculate first class shipping with this? I believe I have everything entered in correct however it returns nothing.

    Thanks,
    Scott

  51. Christian on January 31st, 2009

    I had the same problem as mentioned before regarding the testing server and V3. I called the support number and was instantly upgraded to the production server and all seems to be well with it.

    Changing service to All is handy for getting the rates for all shipping services. It will come in handy as I give customers the option to see estimated shipping costs before final checkout in my shopping cart.

    Christian

  52. Mike on February 2nd, 2009

    I have the same Undefined offset issue as Mike and Keith above which was never addressed.

    The same undefined offset Notice comes out every time there is an attribute in the XML returned from USPS. I get the notices mentioned in the UPS rate script comments as well but that is on a different line of code, but equally concerning.

    I would really like some guidance in to fixing these issues. I think others don’t see the messages simply because they have notices suppressed, but I’d rather fix the code if possible. Can you offer me any guidance?

  53. Mark Sanborn on February 2nd, 2009

    Mike if you go check out the UPS example there are some solutions to your question in the comments.

    If that doesn’t work and you are using php5 you can convert the bottom part of the code to use the simplexml function.

  54. John on February 6th, 2009

    Thanks for the code, but please show how to work with FIRST CLASS.

  55. Mark Sanborn on February 8th, 2009

    Yes, look for it in an article soon.

  56. Yuvraj on February 23rd, 2009

    When i am using above script i am getting below error
    “Fatal error: Call to undefined function curl_init() in C:\Program Files\xampp\htdocs\sites_comp\USPS test\index.php on line 16
    “.

    Can u please tell where u declared ‘curl_init()’ this function.
    have i need to any other file for this function….

  57. Mark Sanborn on February 23rd, 2009

    You need to have curl installed… This is a standard program, most hosts support it.

  58. Tim on February 25th, 2009

    I’ve never been more unsatisfied with a customer care department as I have been with USPS. I’ve made about 3-5 phone calls to the IT number 1-800-344-7779 and gotten the same response (even after explaining RateV2 returns invalid zip code erros and RateV3 is an invalid XML format) that I need to email icustomercare@usps.com which I have already done and gotten in a back and forth argument with the “care” representative that I know what I’m talking about and he is not helping me.

    Absolutely ridiculous. And I can’t simply use UPS or FedEx because the client wants USPS for its lower prices. I can see now why, they spend no money on their technical support.

  59. Mark Sanborn on February 25th, 2009

    Unfortunately USPS is a quasi-government institution that makes money no matter how bad they treat their customers. They have no competition since they literally cannot go out of business. Unfortunately this is how the majority of government run operations are.

  60. Tim on February 25th, 2009

    The only semi-valid response i’ve gotten was that I need to use “canned” request data when submitting to the testing server, this is great, because all the examples I see in the documentation are V3?

    Does anyone know what the canned XML request is so I can get this over with? I’m going on 4 weeks of BS with these people and I’ve had the script done since the middle of january!

  61. Tim on February 25th, 2009

    Sorry for hijacking your board, here are two “canned” XML requests you can use to successfully ping the testing server for your account:

    Test Request #1

    PRIORITY
    10022
    20008
    10
    5
    Flat Rate Box
    REGULAR

    Test Request #2

    All
    10022
    20008
    10
    5
    LARGE
    TRUE

    Ping the server 3 times, then call 1-800-344-7779 and have them check your status on the testing server for your username

  62. Tim on February 25th, 2009

    crap Mark can you edit that to have the tags? sorry, i’m out, good luck everyone!

  63. Mark Sanborn on February 25th, 2009

    @Tim, You need to get on the production server. Their test server is totally worthless.

    Mark

  64. Tim on February 25th, 2009

    I know, I am now. But what I’m saying is, I tried 7 times or so by phone and email to just ask them and tell them why and they still made me submit those queries. The XML I posted above I’m going to try and “pre” tag below, maybe it will work. Once I sent these 3 times they let me on.

    Test Request #1

    PRIORITY
    10022
    20008
    10
    5
    Flat Rate Box
    REGULAR

    Test Request #2

    All
    10022
    20008
    10
    5
    LARGE
    TRUE

    (i’m sorry in advance if the pre tags don’t work)

  65. James on March 5th, 2009

    There is this “Undefined offset: 1 in ..” mentioned in this blog several times which has yet to be solved. Reading the ups-php doesn’t help.

  66. James on March 5th, 2009

    OK Sorry. I figured that out already. No need any fix. Sorry!

  67. Sam on March 22nd, 2009

    Is it possible to get estimated delivery times with a request? I noticed when doing international requests (with another script), estimated delivery times are returned, but not with domestic. When I use this script and change the SERVICE to ALL, and add a ShipDate parameter, I *do* get estimated delivery responses, but only for the Express options. Not Priority, First Class, Media Mail, etc. Do I need to use the separate delivery times API?

  68. Uday on March 23rd, 2009

    Hello all,
    I am new to PHP.Please advice me how to intregrate Shipping rate API to my web page.
    thnx in advance

  69. Mark Sanborn on March 24th, 2009

    Uday,

    Unfortuantely I don’t have the time right now to teach someone PHP. :(

  70. Mark Sanborn on March 24th, 2009

    I beleive they have a service for that. It may infact be in the same API call. Print out the response array and check.

  71. Jade Robbins on March 24th, 2009

    Uday,
    the examples are pretty helpful, but you will need to have some php knowledge to use it.

    Good luck!

  72. Nick on April 1st, 2009

    I can’t seem to get any delivery times for non-express non-international shipments as well.

    In the webtools api document, it says that shipdate is ignored for all domestic non-express shipments.

    I’m trying to figure out if there is a correlation between and delivery times, as there must be but I cannot find a chart.

  73. James on April 7th, 2009

    Mark,
    Oh no. This “Undefined offset: 1 in ..” problem comes back again and I haven’t changed anything. It never really gets solved in the first place. Seriously has anyone ever managed without this problem? Would anyone be kind to share the solution? Thanks very much.

  74. Edward Hamilton on April 7th, 2009

    This was the most helpful page I’ve found yet on the USPS api.

    After spending several hours poring over the USPS webtools site I discovered this site through Google and I’m glad I did.

    By adding a short input form, this code can be adapted to return most of the info available from the USPS. Thanks again.

  75. Brendan on April 21st, 2009

    I’d like to implement this in an existing form of mine so customers could add their shipping amount before our form posts to paypal for payment. Would you be willing to look at my existing checkout code (we currently sell 1 product only, nothing fancy) and point me in the right direction? I’ve been attempting to get through the usps manual and it’s unfathomable to me and yes, I know, the testing server is useless. Whatever info you need from me and however you’d like to work it, if at all, just let me know. Thanks

  76. Brendan on April 21st, 2009

    I’m obviously missing something as it isn’t working properly. It’s showing up as text in a web page I used to test the code. I’ve managed to get through coding problems before but this one has me at a loss. It’s probably some miniscule detail that I’m not seeing. Any help would be appreciated, I’ll send the page to you if that helps.

  77. Debra on May 30th, 2009

    Mark:

    Thanks SO much for this. I don’t think I could have figured this out on my own. After reading through all the comments here, I futzed around with the testing server a little, emailed the USPS on a Friday night with my production server request and got moved Saturday afternoon. The script works perfectly. You rock!

  78. imran on June 5th, 2009

    Hello Everyone, I am facing the problem. I have to integrate USPS API to my site to calculate shipping price of products. I am getting these errors on test and development server.

    This error produces on test server of USPS.

    These are parameters which I am using

    $userName = ‘abc’; // Your USPS Username

    $PWD = ‘123456′;

    $orig_zip = ‘35006′; // Zipcode you are shipping FROM

    $url = “http://testing.shippingapis.com/ShippingAPITest.dll”;

    API=RateV2&XML=PRIORITY3500636310300REGULARTRUEHTTP/1.1 200 OK Connection: close Date: Fri, 05 Jun 2009 10:18:24 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET -2147219498Rate_Respond.DomesticRatesV2Test:clsRatesV2TestValidateParameters:clsRatesV2TestProcessRequest;SOLServerRatesTest.RateV2_RespondPlease enter a valid ZIP Code for the sender. 1000440

    This error produces on production server

    $userName = ‘abc’; // Your USPS Username

    $PWD = ‘123456′;

    $orig_zip = ‘35006′; // Zipcode you are shipping FROM

    $url = ” https://Production.ShippingAPIs.com/ShippingAPI.dll”

    API=RateV3&XML=PRIORITY3500636310300REGULARTRUEcURL Failed to connect!
    Please help me to solve this problem.

  79. pawan vidya on June 17th, 2009

    Hi I am getting this every time
    Array
    (
    )

    with no result?
    i have done registration on USPS site . i am using user_name and zip_code but not working .
    please help me

  80. prash on June 17th, 2009

    hi Mark,

    can you tell me how to implement USPS directly with production server bcoz in test mode you can change parameters.

  81. rkane on August 8th, 2009

    If you are not in production you can use the testing server, and the only addresses that I know that will work are NY 10022, and DC 20008 with a weight of 10 lbs, 5 oz.

  82. kyle on September 8th, 2009

    Talked to USPS several times and they sent me this twice:

    “Thank you for contacting us. The test logs under your UserID do not show valid test requests. We are unable to move your account to the production server until a valid test request is received. If you are using third party software, testing is not required. However, you must provide us with the name of the software you are using. We can then update your account.

    Thank you for using the USPS.”

    Then i showed my code and they said i had to use V2 and not V3 on the testing server:

    here is the code that fails even on the V2:

    http://testing.shippingapis.com/ShippingAPITest.dll?API=RateV2&XML=PRIORITY1002220008105FLAT RATE BOXREGULAR5.511true

    I am at a lose here anybody got any ideas, should i say im using mark sanborns code :)

  83. Mark Sanborn on September 8th, 2009

    Kyle,

    Unfortunately I already have a production key and cannot test this for you. Like you, I was unable to get any of the test xml to go through, but the production ran just fine. I called them up and they just moved me over. I would suggest calling them again and telling them you would like to move to the production server.

    Hope you get through,

    Mark

  84. Steve-o on September 12th, 2009

    Make sure you use 10022 as the “zip origination” (sender) and 20008 as the “zip destination.” If it’s reversed, it won’t work. Also, I could only get 10 lbs and 5 ounces to work.

    Totally useless test server.

  85. reva on October 29th, 2009

    Hi mark,
    First time i m using USPS.
    Can u please tell me how can i call to USPS production server to access them.

  86. Uday on November 5th, 2009

    Hi Jade and Mark
    Thankx for ur support..I have done UPS shipping successfully

  87. Bhavana on November 23rd, 2009

    Hi mark,
    Thanks for such a wonderful post.
    I am getting rates for domestic request, but i dont know that what changes i have to do for getting international shipping rates.

    Please help me out…
    I am getting error of invalid zip code for valid india’s city zipcode..
    Please help me.

    Thanks.