使用 PHP 获取 USPS 订单跟踪状态 [英] Obtaining USPS orders tracking status with PHP
问题描述
尝试使用 USPS 跟踪 API 检索 USPS 订单状态时抛出错误.
Error is thrown when trying to retrieve the status of a USPS order using the USPS Tracking API.
但是,在运行我根据 USPS 手册构建的代码时,出现以下错误:"80040B19XML 语法错误:请检查 XML 请求是否可以解析.USPSCOM::DoAuth"
However, when running the code I built based on the USPS manual, I am getting the following error: "80040B19XML Syntax Error: Please check the XML request to see if it can be parsed.USPSCOM::DoAuth"
手册链接:https://www.usps.com/business/web-tools-apis/track-and-confirm-v1-3a.htm
这是我的代码:
$trackingNumber = 123456;
$url = "http://production.shippingapis.com/shippingAPI.dll";
$service = "TrackV2";
$xml = rawurlencode("
<TrackRequest USERID='MYID'>
<TrackID ID=".$trackingNumber."></TrackID>
</TrackRequest>");
$request = $url . "?API=" . $service . "&XML=" . $xml;
// send the POST values to USPS
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$request);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// parameters to post
$result = curl_exec($ch);
//var_dump($result);
curl_close($ch);
$response = new SimpleXMLElement($result);
//print_r($result);
$deliveryStatus = $response->TrackResponse->TrackInfo->Status;
echo $deliveryStatus;
我做错了什么?
推荐答案
虽然我确信原作者现在已经解决了他们的问题,但在看到这个例子后发现它不起作用我想我会解决这些问题:
While I'm sure the original author resolved their issue by now, having come to this example and finding it didn't work I figured I would address the issues:
首先要解决的是,如果跟踪号是上面示例中的所有数字(我使用的测试跟踪号是 22 个字符的全数字字符串),PHP 会将跟踪号转换为科学记数法.因此,我将数字括在单引号中,将其视为字符串而不是数字.这个问题是在解决下一个问题后才发现的.
First thing to address is that PHP converts the tracking number into scientific notation if the tracking number is all numbers as in the example above (test tracking number I used was an all numeric string of 22 characters). So I encased the numbers in single quotes to treat it as a string instead of a number. This issue was only discovered after the next one was addressed.
对于 $xml,ID 需要用双引号括起来.所以代码应该是:
for the $xml, the ID needs to be encased in double quotes. So the code should be:
$xml = rawurlencode("
<TrackRequest USERID='MYID'>
<TrackID ID=\"".$trackingNumber."\"></TrackID>
</TrackRequest>");
进行这两项更改解决了海报的原始问题.希望这能帮助那些在这里绊倒的人.
Making these two changes resolved the posters original issue. Hope this helps anyone who also stumbles here.
这篇关于使用 PHP 获取 USPS 订单跟踪状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!