PHP: USPS rates calculator

The USPS Web Tools allow developers of web-based and shrink-wrapped applications access to the on-line services of the United States Postal Service (USPS). They provide easy access to shipping information and services for your customers. Your customers can utilize the functions provided by the USPS without ever leaving your web site. Once the Web Tools are integrated, your server communicates through the USPS Web Tools server over HTTP using XML (eXtensible Markup Language).

Rates Calculators

Everything in details can be found here:
http://www.usps.com/webtools/htm/Rates-Calculatorsv1-0.htm

First steps:

  1. Register online (You will get your own user name)
  2. Test this script (You can use only test data)
  3. Contact ICCC and go live.

When you have completed your testing, email the USPS Internet Customer Care Center (ICCC). They will switch your profile to allow you access to the production server and will provide you with the production URL.

Domestic and International Rates

Domestic rates

Test 1:


    $usps = new USPS;
    $usps->setServer("http://testing.shippingapis.com/ShippingAPITest.dll");
    $usps->setUserName("?????????");
    $usps->setService("PRIORITY");
    $usps->setDestZip("20008");
    $usps->setOrigZip("10022");
    $usps->setWeight(10, 5);
    $usps->setContainer("Flat Rate Box");
    $usps->setCountry("USA");
    $price = $usps->getPrice();

Response 1:


    usps Object
    (
        [server] => http://testing.shippingapis.com/ShippingAPITest.dll
        [user] => ???????????
        [pass] =>
        [service] => PRIORITY
        [dest_zip] => 20008
        [orig_zip] => 10022
        [pounds] => 10
        [ounces] => 5
        [container] => Flat Rate Box
        [size] => REGULAR
        [machinable] =>
        [country] => USA
        [zone] => 3
        [list] => Array
            (
                [0] => price Object
                    (
                        [mailservice] => "Priority Mail Flat Rate Box (11.25'' x 8.75'' x 6'')"
                        [rate] => 7.70
                    )
                [1] => price Object
                    (
                        [mailservice] => "Priority Mail Flat Rate Box (14''x 12'' x 3.5'')"
                        [rate] => 7.70
                    )
            )
    )

Test 2:


    $usps = new USPS;
    $usps->setServer("http://testing.shippingapis.com/ShippingAPITest.dll");
    $usps->setUserName("?????????");
    $usps->setService("All");
    $usps->setDestZip("20008");
    $usps->setOrigZip("10022");
    $usps->setWeight(10, 5);
    $usps->setContainer("Flat Rate Box");
    $usps->setCountry("USA");
    $usps->setMachinable("true");
    $usps->setSize("LARGE");
    $price = $usps->getPrice();

Response 2:


    usps Object
    (
        [server] => http://testing.shippingapis.com/ShippingAPITest.dll
        [user] => ???????????
        [pass] =>
        [service] => All
        [dest_zip] => 20008
        [orig_zip] => 10022
        [pounds] => 10
        [ounces] => 5
        [container] => Flat Rate Box
        [size] => LARGE
        [machinable] => true
        [country] => USA
        [zone] => 3
        [list] => Array
            (
                [0] => price Object
                    (
                        [mailservice] => "Express Mail to PO Addressee"
                        [rate] => 39.20
                    )
                [1] => price Object
                    (
                        [mailservice] => "Priority Mail"
                        [rate] => 8.95
                    )
                [2] => price Object
                    (
                        [mailservice] => "Parcel Post"
                        [rate] => 7.80
                    )
                [3] => price Object
                    (
                        [mailservice] => "Bound Printed Matter"
                        [rate] => 3.53
                    )
                [4] => price Object
                    (
                        [mailservice] => "Media Mail"
                        [rate] => 5.14
                    )
                [5] => price Object
                    (
                        [mailservice] => "Library Mail"
                        [rate] => 4.91
                    )
            )
    )

International rates:

Test 1:


    $usps = new USPS;
    $usps->setServer("http://testing.shippingapis.com/ShippingAPITest.dll");
    $usps->setUserName("??????????");
    $usps->setWeight(2, 0);
    $usps->setCountry("Albania");
    $price = $usps->getPrice();

Response 1:


    usps Object
    (
        [server] => http://testing.shippingapis.com/ShippingAPITest.dll
        [user] => ?????????
        [pass] =>
        [service] =>
        [dest_zip] =>
        [orig_zip] =>
        [pounds] => 2
        [ounces] => 0
        [container] => None
        [size] => REGULAR
        [machinable] =>
        [country] => Albania
        [list] => Array
            (
                [0] => intprice Object
                    (
                        [id] => 0
                        [rate] => 87
                        [pounds] => 2
                        [ounces] => 0
                        [mailtype] => "Package"
                        [country] => "ALBANIA"
                        [svccommitments] => "See Service Guide"
                        [svcdescription] => "Global Express Guaranteed (GXG) Document Service"
                        [maxdimensions] => "Max. length 46'', depth 35'', height 46'' and max. girth 108''"
                        [maxweight] => 22
                    )
                [1] => intprice Object
                    (
                        [id] => 1
                        [rate] => 96
                        [pounds] => 2
                        [ounces] => 0
                        [mailtype] => "Package"
                        [country] => "ALBANIA"
                        [svccommitments] => "See Service Guide"
                        [svcdescription] => "Global Express Guaranteed (GXG) Non-Document Service"
                        [maxdimensions] => "Max. length 46'', depth 35'', height 46'' and max. girth 108''"
                        [maxweight] => 22
                    )
            )
    )

Possible errors:


    usps Object
    (
        [server] => http://testing.shippingapis.com/ShippingAPITest.dll
        [user] => ???????????
        [pass] =>
        [service] => Alll
        [dest_zip] => 20008
        [orig_zip] => 10022
        [pounds] => 10
        [ounces] => 5
        [container] => Flat Rate Box
        [size] => LARGE
        [machinable] => true
        [country] => USA
        [error] => error Object
            (
                [number] => -2147219487
                [source] => Rate_Respond;SOLServerRatesTest.RateV2_Respond
                [description] => "Invalid value for package size."
                [helpcontext] => 1000440
                [helpfile] =>
            )
    )

Downlod this freeware PHP script: USPS rates calculator v1.2

Please make a donation of 1$ if you find our software useful and want to support the continued development.


Thank you.

28 Comments

  1. gezi says:

    First of all thanks for the code – it helped me a lot to get started!
    Now, I am wondering if I am doing something wrong here:
    I’m on the production server now and when I try to send a request with an invalid zip code I don’t get an error but just no data, or when I enter a country with a space (like United States) I also get no data back.
    Same effect if I try to limit the services from ‘All’ to something like PRIORITY – no data, and also no error message.
    Any idea?
    Thanks
    Gunter

  2. Algirdas says:

    There was a bug when you enter country name with space but few days ago I have fixed it and now you should get data from USPS.

    Also thank you for reporting another bug. Now when you put invalid zip code, there will be an error message.

  3. Algirdas says:

    Also when you are trying to get domestic rates, you shoud set “USA” as a country (not United states)

  4. [...] USPS rate quotes using Aldirgas Varnagiris’ USPS PHP rates calculator. It worked perfectly right away, however you can only run the specific examples (as opposed to [...]

  5. laredotornado says:

    Hi,

    I just downloaded the USPS rate calculation software for my PHP 4.4.4 installation on Fedora Core 6 Linux. I have error reporting to E_ALL and when I visit index.php, I get these warnings…

    Notice: Undefined index: HELPCONTEXT in /usr/local/apache2/htdocs/dhlovelife/v2/USPS/usps.php on line 105

    Notice: Undefined index: HELPFILE in /usr/local/apache2/htdocs/dhlovelife/v2/USPS/usps.php on line 106

    Is this a problem? Can it be fixed? Thanks, – Dave

  6. Algirdas says:

    Actually it’s not a problem, just a notice. And you should use error reporting only for testing reasons, when you will go LIVE, you should disable error reporting at all!

  7. gknight says:

    Algirdas,
    I know that this post will make me sound like an idiot and that’s ok. I have been programming with PHP and MySQL for a few years now and I never botherd to learn object oriented programming because all of the people that had left posts all over the net saying that it slowed things down a bit. What I am trying to do now is figure out how to get all of the mailing services and their rates to show up in a drop box and I can’t even figure out how to get it to display only one out of the array in the index.php. Any help, advice or maybe some sample code would really be appreciated.

    Now I am going to go and learn a little more.

    Thanks,
    gknight

  8. gknight says:

    A bit of a suggestion. You might want to add into the text above that before you can change any of the information in the sample that you have given, you need to get the production access from USPS first. Took me all this time and having to contact one of the other posters here to figure that one out. Kinda stupid on USPS’s part, but I guess they do it for a reason.

    Thanks again for posting this script.

    gknight

  9. Algirdas says:

    Maybe it’s not clear but there’s written: “Test this script (You can use only test data)”

  10. atiph says:

    Hi,

    Algirdas, I have downloaded this class. its working fine for me but when i change orign and destination zip codes from “20008″ and “10022″ to some valid zip codes like 07481 or 11375 or someone else.I just copy the files in my root folder and change password. Any help????

    Thanks

  11. atiph says:

    Hi,
    Discard my previous posting…Sorry for that

    Algirdas, I have downloaded this class. its working fine for me but when i change orign and destination zip codes from “20008″ and “10022″ to some valid zip codes like 07481 or 11375 or someone else, it shows following error:

    [error] => error Object
    (
    [number] => -2147219490
    [source] => Rate_Respond;SOLServerRatesTest.RateV2_Respond
    [description] => Invalid value for origin ZIP Code.
    [helpcontext] => 1000440
    [helpfile] =>
    )

    I just copy the files in my root folder and change userid. Any help????

    Thanks

  12. Algirdas says:

    zip codes “20008″ and “10022″ is for testing. So if you have changed them and to other valid zip codes and your script stopped working, that could mean your USPS account is not changed to LIVE, with TEST account you can use only test zip codes and other test data.

  13. atiph says:

    Thanks,

    You mean to say that i must go to LIVE for getting desired result and as I m using it with test URL so that these problems occured??

    OK i understand. Thanks for your help. Please also guide me what i have to do after i got my Production key activated??

    Thanks again

  14. skid says:

    Hi,

    Thanks for the script. I have a problem though, the domestic rates work just fine, but the international ones don’t, not on testings nor production.

    This is the error I get: API Authorization failure. IntlRate is not a valid API name for this protocol.

    I would really appreciate if you could help me, this is very important and urgent to me.

    Hope you can give me a reply. THANKS A LOT!
    Best regards

  15. Mrprez says:

    Has anyone used this on php5? How about the new V3 servers at USPS?

    John

  16. mike says:

    Hi,
    I have USPS realtime calculation API for both Domestic and International. It works fine with weight,zip code,country….But my problem is how can i use Dimension like length,height and width of product to calculate exact charges for both. I have my USPS username and password. Currently my API is working on production server. can u please give little bit code to use Dimension. Do u have any idea how to get Consignment No from USPS too..?
    I need real help..? Pl help me in this issue….
    waiting for your comment or reply…..

  17. brooksh says:

    How would you display just the rate?

    I have tried
    $price = $usps->getPrice();
    $total = $price->price->rate;
    echo $total;

    and it doesn’t work.

  18. Algirdas says:

    Hello brooksh,

    with this you get the response and the list of available methods and its prices:
    $price = $usps->getPrice();

    so to print the method name and price you should write this:

    foreach($price->list as $method)
    {
       echo $method->mailservice;
       echo $method->price;
       echo "\n";
    }
  19. stevepofd says:

    Hello,
    I saw someone ask a little while ago about updates for the new V3 system, it seems as i have been getting some strange shipping prices on my site, and i think the old version could be at fault. who knows with the usps though ;)

    thanks in advance for the help!
    -steve

  20. deference says:

    Hello! I am very interested in using this script, however I am required to use either an MIT or a BSD license on any third party script I use, since by not putting a license on this you inherently have it licensed to yourself. Would you mind putting on either an MIT or BSD license. Both licenses simply allow anyone to use the script for any use, which I believe is what you intended by stating ‘freeware’ up above. It also requires that your name and the MIT licensing stay on the code, so you will always keep credit of your work. Thanks so much for considering this, it means a lot to me!!

  21. prabhash says:

    Hi Algirdas,

    Thanx for posting such scripts.While using your code..i am getting an error.The error is from my part.I gave my userid(got after registration).And then on poasting, i am getting the below error.

    [error] => error Object
            (
                [number] => -2147219498
                [source] => Rate_Respond.DomesticRatesV2Test: clsRatesV2TestValidateParameters: clsRatesV2TestProcessRequest; SOLServerRatesTest.RateV2_Respond
                [description] => Please enter a valid ZIP Code for the sender.
                [helpcontext] => 1000440
                [helpfile] =>
            )
    

    I am testing it on test server.
    URL = http://testing.shippingapis.com/ShippingAPITest.dll
    Can u or any body help me by guiding wats going on wrong?
    Thanx.

  22. prabhash says:

    after posting, i gave one more try n was successfull.but still i have a question coz, i am getting result only when posting the same zip code for destination as well as for origin.Why is it so? does it works only for the given values.remember i still testing.

  23. Algirdas says:

    As I already mentioned in comments, You can use only test data in testing environment. So when you will go LIVE, you will be able to use zip codes whatever you want.

  24. scottbedard says:

    Hey, I’m trying to figure out how to calculate shipping for first class mail. Whenever I try though it doesn’t show the price, and i get no error messages.

  25. mkiehl says:

    Below is an example how to access and use the object results of the usps query. This aspect of php oop really confused me, probably because most of the tutorials recommend creating methods to return the results, but authors of code tend to just access the properties directly.

    
    $price = $usps->getPrice();
    // check for an error
    if (!empty($price->error->number)) {
     echo "Error # ".$price->error->number."\n";
     echo $price->error->description."\n";
     die();
    }
    echo "Container type: '".$price->container."'";
    echo "Origin zip: ".$price->orig_zip." ".$price->country."";
    echo "Destination zip: ".$price->dest_zip." ".$price->country."";
    echo "Container type: '".$price->container."'";
    echo "Weight: ".$price->pounds." lbs and ".$price->ounces." ounces.";
    echo "Size: '".$price->size."'";
    if ($price->machinable==true)
     echo "The package is 'machinable'";
    else
     echo "The package is 'non-machinable'";
    echo "Container type: '".$price->container."'";
    echo "\n";
    // To list all of the available usps services returned in $price...
    echo 'Services available: ('.count($price->list).')';
    for ($i = 0; $i < sizeof($price->list); $i++) {
        echo "  ".$i.") Mail service: '".$price->list[$i]->mailservice."' Rate: $".$price->list[$i]->rate."";
    }
    echo "\n";
  26. Sam says:

    Thanks very much for the code. Worked fine for me. Basically it looks like usps only allows certain restricted data to be passed to it while in test mode, so really all you’ll be changing is your userid. I tried changing weight, package size, etc and all returned errors. So the trick is to integrate the results as you want them on your site, and then go live to “test” variable data passing.

  27. Sreenu says:

    Iam getting the following error

    
    USPS Object
    (
        [server] => http://testing.shippingapis.com/ShippingAPITest.dll
        [user] => sreenuphp
        [pass] =>
        [service] => All
        [dest_zip] => 20008
        [orig_zip] => 10022
        [pounds] => 10
        [ounces] => 5
        [container] => Flat Rate Box
        [size] => LARGE
        [machinable] => true
        [country] => USA
        [error] => error Object
            (
                [number] => 80040b1a
                [source] => UspsCom::DoAuth
                [description] => Authorization failure.  Perhaps username and/or password is incorrect.
                [helpcontext] =>
                [helpfile] =>
            )
    
    )
    

    plz give me the solution

  28. sonali says:

    Hello.
    My Name Is sonali.. I registered in USPS. i want some test code

Leave a Reply