php实现快递进度
PHP实现快递进度查询的方法
通过调用第三方快递查询接口是常见的实现方式。以下是几种典型的方法:
使用快递100API
注册快递100账号获取API Key后,可通过以下代码实现查询:
$apiKey = '你的API Key';
$com = '快递公司编码'; //如SF表示顺丰
$num = '快递单号';
$url = "https://api.kuaidi100.com/v8/query?com=$com&num=$num&key=$apiKey";
$result = file_get_contents($url);
$data = json_decode($result, true);
print_r($data);
使用阿里云快递API
阿里云市场提供多种快递查询接口服务:
$appcode = '你的AppCode';
$url = 'http://wuliu.market.alicloudapi.com/kdi';
$headers = [
'Authorization:APPCODE ' . $appcode
];
$params = [
'no' => '快递单号',
'type' => '快递公司'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
自建数据库方案
对于自有快递数据,可设计数据库表结构:
CREATE TABLE `express` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`express_no` varchar(50) NOT NULL COMMENT '快递单号',
`company` varchar(30) NOT NULL COMMENT '快递公司',
`status` varchar(100) NOT NULL COMMENT '当前状态',
`update_time` datetime NOT NULL COMMENT '更新时间',
`details` text COMMENT '详细轨迹',
PRIMARY KEY (`id`),
UNIQUE KEY `express_no` (`express_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
查询PHP代码示例:
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM express WHERE express_no = ?');
$stmt->execute([$_GET['no']]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result) {
echo json_encode([
'status' => $result['status'],
'details' => json_decode($result['details'], true)
]);
}
注意事项
选择API服务时需注意请求频率限制和费用问题。免费接口通常有每日查询次数限制。
返回数据通常包含以下字段:
- 快递单号
- 物流公司
- 当前状态
- 物流轨迹(时间、地点、状态描述)
- 预计送达时间(部分API提供)
建议对API返回结果进行缓存,减少重复查询。可设置缓存过期时间为1小时或根据业务需求调整。






