Categories
Programming

USPS PHP Class

The shopping cart that I wrote some time ago has used rate and zone tables that were loaded into the local database.  The USPS rate and zones have been harder to get in CSV (comma separated variable) format for the last couple of years.  It was now time to drop the local rate charts and use the USPS online tools.

The USPS tools are nice in that they use XML to format both the request and the results. You format a request with your USPS User ID, the originating ZIP code, the destination ZIP code and the package weight and the tool returns a list of the available services and rates. This is nice, except that my old shopping cart expects to make a rate lookup for each service that it supports. I didn’t want to overload the USPS online tool. This class will cache the results of a rate request for a ZIP code and weight combination.  Create an instance of this class early in your PHP module. I used the object as a global data structure. At the point were I needed to do the rate lookup, it was easy to access the data.

$rate = $usps->GetRateUS_byService($dest_zip, $weight, 'Parcel Post');
$rate = $usps->GetRateUS_byService($dest_zip, $weight, 'Priority Mail');

If anyone has any improvements I would be interested in seeing them.

uspsTools.tar.gz