Reputation: 11
I need your help on modifying the USPS Price Calculator API V4. My site is currently using V3 and the shipping rate calculator stopped working since the API upgraded to V4. It can only calculate shipping rate for a certain zip codes in US.
Below is the code that the previous web developer used. I tried to change all "V3" to "V4" but no luck. I'm guessing it's more complicated than that. Please take a look at the code below and advise what I need to do. Thank you for your help in advance.
--------- 1st PHP file -------------------
<?php
function USPS($uspsinfo)
{ //$pounds, $ounces, $service, $dest_zip
extract ($uspsinfo);
$service="PARCEL";
// 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 = '890NUTRI5006';
if ($dest_zip&&$_SESSION['country']=="US"){
$sql = "SELECT * FROM `zipcodes` WHERE `prefix` =".substr ($dest_zip, 0,3)." LIMIT 1";
$new=submit_get($sql);
if ($new[0]['ny']<$new[0]['ca']){
$orig_zip = '14624'; /// sets origin zip to be from NY
$_SESSION['warehouse']="ny";}
else{
$orig_zip = '92833'; /// sets origin zip to be from LA DR SMOOTHIE
$_SESSION['warehouse']="ca";}
//echo $orig_zip.'------------------------------'.substr ($dest_zip, 0,3).'--------------------------';
}
// =============== DON'T CHANGE BELOW THIS LINE ===============
/*
FIRST CLASS
PRIORITY
EXPRESS
BPM
PARCEL
MEDIA
LIBRARY
ALL
*/
//NOTES : If First Class is selected, package cannot weigh more than 13 ounces.
//NOTES : Maximum USPS package size is 70 pounds 0 ounces.
$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);
if($service=='FIRST CLASS') { $fctype="<FirstClassMailType>PARCEL</FirstClassMailType>"; }
if ($_SESSION['country']<>"US")
$data = "API=IntlRate&XML=<IntlRateRequest USERID=\"$userName\"><Package ID=\"1\"><Pounds>".($pounds)."</Pounds><Ounces>".($ounces)."</Ounces><Machinable>FALSE</Machinable><MailType>Package</MailType><Country>$country</Country></Package>
<Package ID=\"2\"><Pounds>32</Pounds><Ounces>0</Ounces><Machinable>FALSE</Machinable><MailType>Package</MailType><Country>$country</Country></Package></IntlRateRequest>";
else
$data = "API=RateV3&XML=<RateV3Request USERID=\"$userName\"><Package ID=\"1\"><Service>$service</Service>$fctype<ZipOrigination>$orig_zip</ZipOrigination><ZipDestination>$dest_zip</ZipDestination><Pounds>$pounds</Pounds><Ounces>".($ounces)."</Ounces><Size>REGULAR</Size><Machinable>FALSE</Machinable></Package>
<Package ID=\"2\"><Service>$service</Service>$fctype<ZipOrigination>$orig_zip</ZipOrigination><ZipDestination>$dest_zip</ZipDestination><Pounds>32</Pounds><Ounces>0</Ounces><Size>REGULAR</Size><Machinable>FALSE</Machinable></Package></RateV3Request>";
//echo $data;
// 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
$i=1;
while($i < 15) {
if($params['INTLRATERESPONSE']['1ST']["$i"]['RATE']=='') { $i++; }
else { return $params['INTLRATERESPONSE']['1ST']["$i"]['RATE']; break; }
}
if ($params['RATEV3RESPONSE']['1']['ERROR'])
$_SESSION['shippingerror']="There has been an error calculating your shipping cost.<br>";
return $params;
}
function delete_white_space($a)
{
$new=preg_replace("/ /", "", $a);
return $new;
}
function change_password($username, $new_password)
// change password for username/old_password to new_password
// return true or false
{
// if the old password is right
// change their password to new_password and return true
// else throw an exception
$conn = db_connect();
$result = $conn->query( "update customers set password ='$new_password' where username = '$username'");
if (!$result)
throw new Exception('<p align="center"><font color="#385364"><b>Ooops! We could not save your new password.<br> If you are having difficulty, please<a class="leftmenu" href="contact.php">contact</a> a Dr. Smoothie representative 888-466-9941</b></font></p><br>');
else
return true; // changed successfully
}
function send_mail($to, $subject, $message, $h, $allinfo=true)
{
if ($allinfo)
{
$a=date("F j, Y, g:i a")."\r\n $_SESSION \r\n";
foreach($_SESSION as $k => $v)
$a.="$k = $v \r\n";
foreach($_SERVER as $k => $v)
$a.="$k = $v \r\n";
$message.=$a;
}
if (!$h)
$h = 'From: [email protected]' . "\r\n" .'Reply-To: [email protected]' . "\r\n".'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $h);
}
function fill_full_array()
{
$a=date("F j, Y, g:i a")."\r\n $_SESSION \r\n";
foreach($_SESSION as $k => $v)
$a.="$k = $v \r\n";
foreach($_SERVER as $k => $v)
$a.="$k = $v \r\n";
return $a;
}
?>
Upvotes: 1
Views: 4528
Reputation: 187
I am the author of the original script that your code is referencing to in the USPS() function judging by this line, although the script has been heavily modified:
// This script was written by Mark Sanborn at http://www.marksanborn.net
The basic request structure needed for the USPS Rate API V4 is as follows:
API=RateV4&XML=<RateV4Request USERID="YOURIDHERE">
<Revision>2</Revision>
<Package ID="1ST">
<Service>ALL</Service>
<ZipOrigination>59759</ZipOrigination>
<ZipDestination>90210</ZipDestination>
<Pounds>5</Pounds>
<Ounces>5</Ounces>
<Container />
<Size>REGULAR</Size>
<Width>2</Width>
<Length>1</Length>
<Height>3</Height>
<Girth>10</Girth>
<Machinable>false</Machinable>
</Package>
</RateV4Request>
I took what you have posted and modified it to show you a basic example request to the USPS V4 API:
<?php
function USPS($pounds, $ounces, $originZip, $destZip)
{
// 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 = 'YOURAPIUSERNAME';
// ========== CHANGE THESE VALUES TO MATCH YOUR OWN ===========
$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);
// You would want to actually build this xml using dimensions
// and other attributes but this is a bare minimum request as
// an example.
$data = "API=RateV4&XML=<RateV4Request USERID=\"{$username}\">
<Revision>2</Revision>
<Package ID=\"1ST\">
<Service>ALL</Service>
<ZipOrigination>{$originZip}</ZipOrigination>
<ZipDestination>{$destZip}</ZipDestination>
<Pounds>{$pounds}</Pounds>
<Ounces>{$ounces}</Ounces>
<Container />
<Size>REGULAR</Size>
<Width>2</Width>
<Length>1</Length>
<Height>3</Height>
<Girth>10</Girth>
<Machinable>false</Machinable>
</Package>
</RateV4Request>";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec ($ch);
return $result;
}
var_dump(
USPS(5, 1, '59759', '90210')
);
Please note, there are a more package attributes that can be specified during the request that can effect the rate as well as an entirely different API for international rates.
See: https://www.usps.com/business/web-tools-apis/rate-calculators-v1-7a.htm
If you are having trouble putting this together you really should consider my commercial offering at https://rocketship.it as it is feature complete, supports multiple carriers, and most importantly updated when the carriers change their APIs as they did in your case.
Upvotes: 5