電商、ERP 系統常需整合物流查詢功能。快遞100(Kuaidi100)提供免費 API,支援超過 1000 家物流商,回傳 JSON 格式,整合極為簡單。本文示範以 PHP 串接查詢物流軌跡。
https://m.kuaidi100.com/querytype:快遞公司代碼(如 sf 順豐、yto 圓通)postid:運單號碼id:固定為 1valicode:驗證碼(選填)temp:隨機數防快取status、message、state、data(陣列)<?php
/**
* 查詢快遞物流資訊
* @param string $code 快遞公司代碼
* @param string $invoice 運單號碼
* @return array 結構化結果
*/
function getExpressDelivery($code, $invoice) {
$result = ['status' => 0, 'info' => '未知錯誤', 'state' => '', 'data' => []];
$url = sprintf(
'https://m.kuaidi100.com/query?type=%s&postid=%s&id=1&valicode=&temp=%d',
urlencode($code),
urlencode($invoice),
mt_rand(1, 9999)
);
$json = @file_get_contents($url);
if ($json === false) {
$result['info'] = '網路請求失敗';
return $result;
}
$data = json_decode($json, true);
if (!$data) {
$result['info'] = 'JSON 解析失敗';
return $result;
}
// 狀態碼 200 代表成功
if (($data['status'] ?? 0) == 200) {
$result['status'] = 1;
$result['info'] = $data['message'] ?? '查詢成功';
$result['state'] = $data['state'] ?? '';
$result['data'] = $data['data'] ?? [];
} else {
$result['info'] = $data['message'] ?? '查詢失敗';
}
return $result;
}
// 使用範例
$res = getExpressDelivery('sf', 'SF1234567890');
if ($res['status']) {
echo "狀態:{$res['state']}\n";
foreach ($res['data'] as $item) {
echo "{$item['time']} {$item['context']}\n";
}
} else {
echo "錯誤:{$res['info']}\n";
}
?>
生產環境建議使用 HTTPS 並加入超時控制:
function getExpressDeliveryCurl($code, $invoice) {
$url = 'https://m.kuaidi100.com/query';
$params = [
'type' => $code,
'postid' => $invoice,
'id' => 1,
'temp' => mt_rand(1, 9999)
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url . '?' . http_build_query($params),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false, // 若憑證驗證失敗可暫時關閉
CURLOPT_USERAGENT => 'Mozilla/5.0 (PHP/' . PHP_VERSION . ')'
]);
$json = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) return ['status' => 0, 'info' => 'cURL 錯誤: ' . $err];
return json_decode($json, true) ?: ['status' => 0, 'info' => '解析失敗'];
}
| 公司 | 代碼 |
|---|---|
| 順豐速運 | sf |
| 圓通速遞 | yto |
| 中通快遞 | zto |
| 韻達快遞 | yunda |
| 申通快遞 | sto |
| 百世快遞 | huitong |
| 京東物流 | jd |
| 郵政EMS | ems |
完整代碼請參考快遞100 官方文件。
200:查詢成功400:參數錯誤500:伺服器錯誤501:單號不存在或已過期502:快遞公司代碼錯誤valicode 驗證碼,需先呼叫驗證碼介面。