【问题标题】:USPS Price Calculator V4 (Update to PHP file)USPS 价格计算器 V4(更新到 PHP 文件)
【发布时间】:2014-02-11 19:49:44
【问题描述】:

在修改 USPS 价格计算器 API V4 方面需要您的帮助。我的网站目前正在使用 V3,并且自从 API 升级到 V4 后运费计算器停止工作。它只能计算美国特定邮政编码的运费。

以下是之前的 Web 开发人员使用的代码。我试图将所有“V3”更改为“V4”,但没有运气。我猜它比这更复杂。请查看下面的代码并告知我需要做什么。提前感谢您的帮助。

--------- 第一个 PHP 文件 -------------------

    <?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: webmaster@nutriblendz.net' . "\r\n" .'Reply-To: webmaster@nutriblendz.net' . "\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;
}
?>

【问题讨论】:

  • 它是如何失败的?它会产生什么错误?它做了什么而不是你期望它做什么?
  • 如果 API 像这样更改主要版本,您可能需要修改请求签名和响应处理。仅仅改变一个版本号除了破坏你的代码之外不可能做任何事情。您需要阅读新 API 的文档并进行相应的更改。如果您不知道怎么做,您可能需要聘请开发人员来做。

标签: php usps


【解决方案1】:

根据这一行判断,我是您的代码在 USPS() 函数中引用的原始脚本的作者,尽管该脚本已被大量修改:

// 此脚本由 Mark Sanborn 在http://www.marksanborn.net 编写

USPS Rate API V4 所需的基本请求结构如下:

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>

我采用了您发布的内容并对其进行了修改,以向您展示对 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')
);

请注意,在请求期间可以指定更多可以影响费率的包属性,以及用于国际费率的完全不同的 API。

见:https://www.usps.com/business/web-tools-apis/rate-calculators-v1-7a.htm

如果您无法将这些放在一起,您真的应该考虑我在https://rocketship.it 提供的商业产品,因为它功能齐全,支持多个运营商,最重要的是,当运营商更改他们的 API 时会更新,就像他们在您的案例中所做的那样。

【讨论】:

  • 太棒了,需要你的帮助,我正在使用它,它给了我这个回复 597599021051REGULARFALSE5Priority Mail Express 2-Day<sup>™</sup>55.70Priority Mail Express 2-Day&lt ;支持&gt ......
  • 反应正常,说明有效!要获取特定值,您需要将 XML 解析为对象或数组。结帐:php.net/manual/en/simplexml.examples-basic.php
猜你喜欢
  • 2017-04-14
  • 2013-03-25
  • 2017-08-11
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2020-03-28
相关资源
最近更新 更多