php实现快递进度
PHP实现快递进度查询
方法一:使用快递100 API
快递100提供了免费的快递查询API接口,可以通过PHP调用获取快递进度信息。
注册快递100开发者账号,获取API Key。 使用PHP的cURL函数发送HTTP请求到快递100的API接口。
$expressNo = '快递单号';
$companyCode = '快递公司编码';
$key = '你的API Key';
$url = "https://api.kuaidi100.com/api?id={$key}&com={$companyCode}&nu={$expressNo}&show=0&muti=1&order=desc";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$result = json_decode($output, true);
if($result['status'] == '200') {
foreach($result['data'] as $item) {
echo $item['time'] . ' ' . $item['context'] . '<br>';
}
} else {
echo '查询失败:' . $result['message'];
}
方法二:使用阿里云快递查询API
阿里云也提供了快递查询服务,需要先开通服务并获取AccessKey。
$expressNo = '快递单号';
$companyCode = '快递公司编码';
$accessKeyId = '你的AccessKey ID';
$accessKeySecret = '你的AccessKey Secret';
$params = [
'Action' => 'QueryExpress',
'Version' => '2018-05-01',
'ExpressNo' => $expressNo,
'CompanyCode' => $companyCode
];
// 生成签名
ksort($params);
$canonicalizedQueryString = '';
foreach($params as $key => $value) {
$canonicalizedQueryString .= '&' . rawurlencode($key) . '=' . rawurlencode($value);
}
$stringToSign = 'GET&%2F&' . rawurlencode(substr($canonicalizedQueryString, 1));
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
$url = 'https://express.aliyuncs.com/?' . http_build_query($params) . '&Signature=' . rawurlencode($signature);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessKeyId
]);
$output = curl_exec($ch);
curl_close($ch);
$result = json_decode($output, true);
if(isset($result['Traces'])) {
foreach($result['Traces'] as $trace) {
echo $trace['AcceptTime'] . ' ' . $trace['AcceptStation'] . '<br>';
}
}
方法三:直接抓取快递公司官网数据
对于不支持API的快递公司,可以使用PHP抓取官网数据。
$expressNo = '快递单号';
$url = "https://www.sf-express.com/cn/sc/dynamic_function/waybill/#search/bill-number/{$expressNo}";
$html = file_get_contents($url);
// 使用正则表达式或DOM解析提取数据
preg_match_all('/<div class="time">(.*?)<\/div>.*?<div class="context">(.*?)<\/div>/s', $html, $matches);
if(!empty($matches[1])) {
for($i = 0; $i < count($matches[1]); $i++) {
echo $matches[1][$i] . ' ' . $matches[2][$i] . '<br>';
}
}
注意事项
- API方式需要注册开发者账号并获取密钥
- 直接抓取网站数据可能违反网站使用条款
- 建议对查询结果进行缓存,避免频繁请求
- 处理返回数据时要注意错误处理和异常捕获
以上方法可以根据实际需求选择使用,API方式更稳定但可能有调用限制,直接抓取方式更灵活但维护成本较高。







