快遞100 提供免費的物流查詢接口,返回 JSON 格式數據。本文封裝一個通用函數,傳入快遞公司代碼與單號即可獲取標準化結果。
<?php
/**
* 查詢快遞信息
* @param string $code 快遞公司代碼(如 shunfeng, yuantong)
* @param string $invoice 快遞單號
* @return array ['status'=>1/0, 'info'=>'', 'state'=>'', 'data'=>[]]
*/
function getExpressDelivery($code, $invoice) {
$result = ['status' => 0, 'info' => '未知錯誤'];
$url = "https://m.kuaidi100.com/query?type={$code}&postid={$invoice}&id=1&valicode=&temp=" . rand(1, 710);
$body = @file_get_contents($url);
if ($body === false) {
$result['info'] = '請求失敗';
return $result;
}
$data = json_decode($body, true);
if (!$data) {
$result['info'] = '數據解析失敗';
return $result;
}
$result['status'] = ($data['status'] ?? 0) == 200 ? 1 : 0;
$result['info'] = $data['message'] ?? '未知狀態';
if (isset($data['data'])) {
$result['state'] = $data['state'] ?? '';
$result['data'] = $data['data'];
}
return $result;
}
?>
<?php
$res = getExpressDelivery('shunfeng', 'SF1234567890');
if ($res['status']) {
echo "查詢成功,狀態:{$res['state']}\n";
foreach ($res['data'] as $item) {
echo "{$item['time']} {$item['context']}\n";
}
} else {
echo "查詢失敗:{$res['info']}\n";
}
?>
| 公司 | 代碼 |
|---|---|
| 順豐 | shunfeng |
| 圓通 | yuantong |
| 中通 | zhongtong |
| 申通 | shentong |
| 韻達 | yunda |
| EMS | ems |
file_get_contents 可能失敗,可改用 cURL 並設置 CURLOPT_SSL_VERIFYPEER => false(僅測試環境)。