快递查询api(多接口方案)

时间:2024-01-06 14:15:32
/** 本环境使用php+smarty,结合两种快递api调取快递数据
* 说明,先快递鸟调取数据,失败后再调取快递网的数据
* 快递鸟 http://www.kdniao.com   快递网  http://www.kuaidi.com/
* ----前台调用代码----
<{if $de.is_virtual neq 1 && $de.logistics_name}>
<dl class="dl clearfix">
<dt>物流信息</dt>
<dd>物流名称:<{$de.logistics_name}></dd>
<{if $de.invoice_no}>
<dd>物流单号:<{$de.invoice_no}></dd>
<{/if}>
</dl>
<{if $de.logistics_name&&$de.invoice_no&&$logistics_config.logistics_connect==1}>
<dl><script src="<{$config.weburl}>/api/***.php?com=<{$de.logistics_name}>&nu=<{$de.invoice_no}>"></script></dl>
<{/if}>
<{/if}>
*/

快递查询api(多接口方案)  快递查询api(多接口方案)

 <?php
include_once("../includes/global.php");
@include_once("../config/logistics_config.php");
$api_id = $logistics_config['logistic_app_id'] ? $logistics_config['logistic_app_id'] : "";
$api_sceret = $logistics_config['logistic_api_sceret'] ? $logistics_config['logistic_api_sceret'] : "";
define("API_Id", $api_id);
define("API_Sceret", $api_sceret); //快递网只需这个 api_id不起作用 //llog('',true);
//llog('key'.API_Sceret); if ($_GET["com"] && $_GET["nu"]) {
//查询表中支持的快递公司
$sql = "select * from " . FASTMAIL . " where company='" . $_GET["com"] . "'";
$db->query($sql);
//llog('查询表中支持的快递公司:'.$sql);
if ($db->num_rows()) {
$fast_mail = $db->fetchRow();
$com = $fast_mail["pinyin"]; //快递公司代号
$nu = $_GET["nu"]; //快递单号
$order = ''; //订单号(可不填)
$sql2 = "select * from `fast_mail_record` where `number`='{$nu}'";
$db->query($sql2);
$info = $db->fetchRow(); //缓存记录
//llog('--------查询缓存数据:-------');
//llog($info);
$time = date('Y-m-d H:i:s', time());
//无缓存或缓存超过1小时直接获取
if (!$info || (time() - strtotime($info['uptime'])) > 3600) {
//llog('+++快递鸟调取++');
$birds = getOrderTracesByJson($order, $com, $nu);
//llog($birds);
if ($birds['Success'] && count($birds['Traces']) > 0) { //快递鸟调取
$tables = joinHtml($birds['Traces']);
//缓存数据
if ($info['id'])
$sql = "update `fast_mail_record` set `record`='{$tables}',`uptime`='{$time}' where id='{$info['id']}'";
else
$sql = "insert into `fast_mail_record` (`code`,`number`,`record`) VALUE ('{$birdsCode[$com]}','{$nu}','{$tables}')";
$db->query($sql);
//llog('+++快递鸟调取成功缓存数据:'.$sql);
echo "document.write('" . $tables . "');";
} else { //快递鸟调取失败,再调取快递网
//快递鸟公司代码->快递网代码
$birdsCode = array('AAE' => 'aae', 'YTO' => 'yuantong', 'QFKD' => 'quanfengkuaidi', 'DBL' => 'debangwuliu', 'ZYWL' => 'zhongyouwuliu', 'STO' => 'shentong', 'SF' => 'shunfeng', 'HHTT' => 'tiantian', 'ZJS' => 'zhaijisong', 'Aramex' => 'aramex', 'AXD' => 'anxinda', 'ZTO' => 'zhongtong', 'YD' => 'yunda');
$res = kuaidi($birdsCode[$com], $nu);
//llog('---快递网调取---');
//llog($res);
if ($res['success'] && count($res['data']) > 0) {
$tables = joinHtml($res['data']);
//缓存数据
if ($info['id'])
$sql = "update `fast_mail_record` set `record`='{$tables}',`uptime`='{$time}' where id='{$info['id']}'";
else
$sql = "insert into `fast_mail_record` (`code`,`number`,`record`) VALUE ('{$birdsCode[$com]}','{$nu}','{$tables}')";
$db->query($sql);
//llog('---快递网调取成功缓存数据++'.$sql);
echo "document.write('" . $tables . "');";
} elseif (isset($res['Reason']) && strlen($res['Reason']) > 0 || isset($res['reason']) && strlen($res['reason']) > 0) {
//llog('---调取失败返回数据--');
echo "document.write('<p style=\'color:#ff6933;font-size:14px;font-weight:bold;\'>" . $birds['Reason'] . "!</p><p style=\'color:red;font-size:14px;font-weight:bold;\'>" . $res['reason'] . "!</p>');";
} elseif (isset($info['record']) && strlen($info['record']) > 0) {
//llog('---还是用老数据--');
echo "document.write('" . $info['record'] . "');";
} else {
//llog('---无数据可用--');
echo "document.write('暂时没有物流信息!');";
}
}
} else {
//llog('---直接调用缓存返回数据--');
//调取缓存
echo "document.write('" . $info['record'] . "');";
}
} else {
//llog('表中不支持的快递公司--');
echo "document.write('暂时没有物流信息!');";
}
} /**快递鸟 查询订单第一方案
* @param string $OrderCode 订单编号(可空)
* @param $ShipperCode 快递公司编码
* @param $LogisticCode 物流单号
* @return url响应返回的html Json方式
*/
function getOrderTracesByJson($OrderCode = '', $ShipperCode, $LogisticCode)
{
$requestData = "{'OrderCode':'" . $OrderCode . "','ShipperCode':'" . $ShipperCode . "','LogisticCode':'" . $LogisticCode . "'}";
$url = 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx';
$datas = array(
'EBusinessID' => API_Id, // 用户ID
'RequestType' => '1002',
'RequestData' => urlencode($requestData),
'DataType' => '2',
);
$datas['DataSign'] = encrypt($requestData, API_Sceret);
$result = sendPost($url, $datas);
//根据公司业务处理返回的信息......json格式
return json_decode($result, true);
} /** 快递鸟
* post提交数据
* @param string $url 请求Url
* @param array $datas 提交的数据
* @return url响应返回的html
*/
function sendPost($url, $datas)
{
$temps = array();
foreach ($datas as $key => $value) {
$temps[] = sprintf('%s=%s', $key, $value);
}
$post_data = implode('&', $temps);
$url_info = parse_url($url); if ($url_info['port'] == '') {
$url_info['port'] = 80;
}
// echo $url_info['port'];
$httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
$httpheader .= "Host:" . $url_info['host'] . "\r\n";
$httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
$httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
$httpheader .= "Connection:close\r\n\r\n";
$httpheader .= $post_data;
$fd = fsockopen($url_info['host'], $url_info['port']);
fwrite($fd, $httpheader);
$gets = "";
$headerFlag = true;
while (!feof($fd)) {
if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
while (!feof($fd)) {
$gets .= fread($fd, 128);
}
fclose($fd); return $gets;
} /**快递鸟
* 电商Sign签名生成
* @param data 内容
* @param appkey Appkey
* @return DataSign签名
*/
function encrypt($data, $appkey)
{
return urlencode(base64_encode(md5($data . $appkey)));
} /**--------------------------------快递网 查询第二方案----------------------------------------------------
* @param $com 公司代号
* @param $nu 快递单号
* @param int $id 缓存表id
* @return string
*/
function kuaidi($com, $nu)
{
$AppKey = 'e456181bcd8234562928a92b0786acf1'; //申请的key
$url = 'http://api.kuaidi.com/openapi.html?id=' . $AppKey . '&com=' . $com . '&nu=' . $nu . '&show=0&muti=0&order=asc';
//优先使用curl模式发送数据
if (function_exists('curl_init') == 1) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
$res = curl_exec($curl);
curl_close($curl);
}
$res = json_decode($res, true);
return $res;
// return "document.write('" . $htmls ."');";
} //拼装html
function joinHtml($res)
{
$tables = '<table width="520px" border="0" cellspacing="0" cellpadding="0" id="showtablecontext" style="border-collapse:collapse;border-spacing:0;"><tbody><tr><td width="163" style="background:#39b54a;border:1px solid #39b54a;color:#FFFFFF;font-size:14px;font-weight:bold;height:28px;line-height:28px;padding:3px 5px;">时间</td><td width="354" style="background:#39b54a;border:1px solid #39b54a;color:#FFFFFF;font-size:14px;font-weight:bold;height:28px;line-height:28px;padding:3px 5px;">地点和跟踪进度</td></tr>';
foreach ($res as $vo) {
$time = $vo['AcceptTime'] ? $vo['AcceptTime'] : $vo['time'];
$context = $vo['AcceptStation'] ? $vo['AcceptStation'] : $vo['context'];
$tables .= '<tr><td width="163" style="border:1px solid #DDDDDD;font-size:12px;line-height:22px;padding:3px 5px;">' . $time . '</td><td width="354" style="border:1px solid #DDDDDD;font-size:12px;line-height:22px;padding:3px 5px;text-align: left;">' . $context . '</td></tr>';
}
$tables .= '</tbody></table>';
return $tables;
} function llog($msg, $f = false, $path = "/logs/temp")
{
define("APP_ROOT_DIRECTORY", dirname(dirname(__FILE__)));//获取项目根目录绝对路径
$file = APP_ROOT_DIRECTORY . $path . ".log";
if ($f)
file_put_contents($file, '');
error_log("[" . date("Y-m-d H:i:s") . "] " . print_r($msg, true) . "\n\r", 3, $file);
} ?>

前面使用了快递鸟调取数据,失败后再调取快递网的数据

==================================新版本加入了app端的支持

 //调试样例 http://www.abc.app/api/logistic.php?com=申通快递&nu=3315555780084&type=json
//代码开始
include_once("../includes/global.php");
@include_once("../config/logistics_config.php");
//管理后台--设置--物流查询平台 设置下列参数
$api_id = $logistics_config['logistic_app_id'] ? $logistics_config['logistic_app_id'] : "";
$api_sceret = $logistics_config['logistic_api_sceret'] ? $logistics_config['logistic_api_sceret'] : "";
define("API_Id", $api_id);
define("API_Sceret", $api_sceret);
$type=$_GET["type"]; //type=json app访问
if (!$type){
$type="html";
}
//快递网测试
if ($_GET["com"] && $_GET["nu"]) {
//查询表中支持的快递公司
$sql = "select * from " . FASTMAIL . " where company='" . $_GET["com"] . "'";
$db->query($sql);
//fb('查询表中支持的快递公司:'.$sql);
if ($db->num_rows()) {
$fast_mail = $db->fetchRow();
$com = $fast_mail["pinyin"]; //快递鸟对应物流公司代码
$com2 = $fast_mail["pinyin2"]; //快递网对应物流公司代码
$nu = $_GET["nu"]; //快递单号
$order = ''; //订单号(可不填)
$sql2 = "select * from `mallbuilder_fast_mail_record` where `number`='{$nu}' and `code`='{$com}'";
$db->query($sql2);
$info = $db->fetchRow(); //缓存记录
//fb('--------查询缓存数据:-------');
//fb($info);
$time = date('Y-m-d H:i:s', time());
//无缓存或缓存超过1小时直接获取
if (!$info || (time() - strtotime($info['uptime'])) > 3600) {
//fb('+++快递鸟调取++');
$birds = getOrderTracesByJson($order, $com, $nu);
//fb($birds);
if ($birds['Success'] && count($birds['Traces']) > 0) { //快递鸟调取
$tables = array();
foreach($birds['Traces'] as $k => $vo){
$tables[$k]['time'] = $vo['AcceptTime'];
$tables[$k]['context'] = $vo['AcceptStation'];
}
//fb($tables,'字段转换');
$tables = json_encode_ex($tables);
$record =addslashes($tables); //插入数据 \n 报错
//fb($tables,'json中文显示');
//缓存数据
if ($info['id'])
$sql = "update `mallbuilder_fast_mail_record` set `code`='{$com}',`record`='{$record}',`uptime`='{$time}' where id='{$info['id']}'";
else
$sql = "insert into `mallbuilder_fast_mail_record` (`code`,`number`,`record`) VALUE ('{$com}','{$nu}','{$record}')";
$db->query($sql);
//fb('+++快递鸟调取成功-开始缓存数据:'.$sql);
lookorder($tables);
} else {
//fb('---快递鸟调取失败,再调取快递网---');
$res = kuaidi($com2, $nu);
//fb($res);
if ($res['success'] && count($res['data']) > 0) {
$tables =json_encode_ex($res['data']);
$record =addslashes($tables);
//fb($tables,'json转换中文显示');
//缓存数据
if ($info['id'])
$sql = "update `mallbuilder_fast_mail_record` set `code`='{$com}', `record`='{$record}',`uptime`='{$time}' where id='{$info['id']}'";
else
$sql = "insert into `mallbuilder_fast_mail_record` (`code`,`number`,`record`) VALUE ('{$com}','{$nu}','{$record}')";
$db->query($sql);
//fb('---快递网调取成功--缓存数据++'.$sql);
lookorder($tables);
/* } elseif (isset($res['Reason']) && strlen($res['Reason']) > 0 || isset($res['reason']) && strlen($res['reason']) > 0) {
lookorder('',1);*/
} elseif (isset($info['record']) && strlen($info['record']) > 0) {
//fb('---调取失败原因---启用老数据--');
//fb($birds['Reason'].' | '.$res['reason']);
//fb($info['record']); lookorder($info['record']);
} else {
//fb('---无数据可用--');
lookorder('',1);
}
}
} else {
//fb('---直接调用缓存返回数据--');
// echo "document.write('" . $info['record'] . "');";
lookorder($info['record']);
}
} else {
//fb('表中不支持的快递公司--');
lookorder('',1);
}
}
/**输出信息
* @param string $con 快递信息(json)
* @param int $style 1为未查到数据
*/
function lookorder($con='',$style=0)
{
global $type;
//fb($type,'type');
if ($type == "json") {
if($style){
$con = array('errCode'=>403,'message'=>'没有查到相关信息。单号暂未收录或已过期!','data'=>'');
$con = json_encode($con);
echo $con;
}else{
$data =json_decode($con);
$con = array('errCode'=>0,'message'=>'','data'=>$data);
$con =json_encode($con);
echo $con;
}
//fb($con,'app输出');
}else{
if($style)
echo "document.write('<p style=\'color:red;font-size:14px;font-weight:bold;\'>没有查到相关信息。单号暂未收录或已过期!</p>')";
else{
$con = joinHtml($con);
echo "document.write('" . $con . "');";
}
//fb($con,'html输出');
}
exit;
} /**快递鸟 查询订单物流轨迹
* @param string $OrderCode 订单编号(可空)
* @param $ShipperCode 快递公司编码
* @param $LogisticCode 物流单号
* @return url响应返回的html Json方式
*/
function getOrderTracesByJson($OrderCode = '', $ShipperCode, $LogisticCode)
{
$requestData = "{'OrderCode':'" . $OrderCode . "','ShipperCode':'" . $ShipperCode . "','LogisticCode':'" . $LogisticCode . "'}";
$url = 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx';
$datas = array(
'EBusinessID' => API_Id, // 用户ID
'RequestType' => '1002',
'RequestData' => urlencode($requestData),
'DataType' => '2',
);
$datas['DataSign'] = encrypt($requestData, API_Sceret);
$result = sendPost($url, $datas);
//根据公司业务处理返回的信息......json格式
return json_decode($result, true);
} /**
* post提交数据
* @param string $url 请求Url
* @param array $datas 提交的数据
* @return url响应返回的html
*/
function sendPost($url, $datas)
{
$temps = array();
foreach ($datas as $key => $value) {
$temps[] = sprintf('%s=%s', $key, $value);
}
$post_data = implode('&', $temps);
$url_info = parse_url($url); if ($url_info['port'] == '') {
$url_info['port'] = 80;
}
// echo $url_info['port'];
$httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
$httpheader .= "Host:" . $url_info['host'] . "\r\n";
$httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
$httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
$httpheader .= "Connection:close\r\n\r\n";
$httpheader .= $post_data;
$fd = fsockopen($url_info['host'], $url_info['port']);
fwrite($fd, $httpheader);
$gets = "";
$headerFlag = true;
while (!feof($fd)) {
if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
while (!feof($fd)) {
$gets .= fread($fd, 128);
}
fclose($fd); return $gets;
} /**
* 电商Sign签名生成
* @param data 内容
* @param appkey Appkey
* @return DataSign签名
*/
function encrypt($data, $appkey)
{
return urlencode(base64_encode(md5($data . $appkey)));
} /**快递网 查询第二方案
* @param $com 公司代号
* @param $nu 快递单号
* @param int $id 缓存表id
* @return string
*/
function kuaidi($com, $nu)
{
$AppKey = '11222333444555';
// $AppKey= API_Sceret?API_Sceret:'1234567898765';
$url = 'http://api.kuaidi.com/openapi.html?id=' . $AppKey . '&com=' . $com . '&nu=' . $nu . '&show=0&muti=0&order=asc';
//优先使用curl模式发送数据
if (function_exists('curl_init') == 1) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
$res = curl_exec($curl);
curl_close($curl);
}
$res = json_decode($res, true);
return $res;
// return "document.write('" . $htmls ."');";
} //拼装html
function joinHtml($res)
{
//fb($res,'拼装html');
$res = str_replace('\r','<br/> ',$res); //把换行符替换成html格式
$res = json_decode($res,true);
$tables = '<table width="520px" border="0" cellspacing="0" cellpadding="0" id="showtablecontext" style="border-collapse:collapse;border-spacing:0;"><tbody><tr><td width="163" style="background:#39b54a;border:1px solid #39b54a;color:#FFFFFF;font-size:14px;font-weight:bold;height:28px;line-height:28px;padding:3px 5px;">时间</td><td width="354" style="background:#39b54a;border:1px solid #39b54a;color:#FFFFFF;font-size:14px;font-weight:bold;height:28px;line-height:28px;padding:3px 5px;">地点和跟踪进度</td></tr>';
foreach ($res as $vo) {
$time = $vo['time'] ? $vo['time'] : $vo['AcceptTime'] ;
$context = $vo['context'] ? $vo['context'] : $vo['AcceptStation'];
$tables .= '<tr><td width="163" style="border:1px solid #DDDDDD;font-size:12px;line-height:22px;padding:3px 5px;">' . $time . '</td><td width="354" style="border:1px solid #DDDDDD;font-size:12px;line-height:22px;padding:3px 5px;text-align: left;">' . $context . '</td></tr>';
}
$tables .= '</tbody></table>';
return $tables;
}

下面是快递100和爱查快递api接口示例

 1 /** 快递100 https://www.kuaidi100.com/openapi/api_post.shtml
2 * @param $com 快递公司代码,不支持中文
3 * @param $nu 快递单号,请勿带特殊符号,不支持中文(大小写不敏感)
4 * @param $show 返回类型:如果不填,默认返回json字符串
5 0:返回json字符串,
6 1:返回xml对象,
7 2:返回html对象,
8 3:返回text文本。
9 * @return string
10 */
 function php100($com,$nu){
$AppKey= API_Sceret?API_Sceret:'a704e4fb5fcc8124';//请将XXXXXX替换成您在http://kuaidi100.com/app/reg.html申请到的KEY
$url ='http://api.kuaidi100.com/api?id='.$AppKey.'&com='.$com.'&nu='.$nu.'&show=2&muti=1&order=asc';
//请勿删除变量$powered 的信息,否则本站将不再为你提供快递接口服务。
$powered = '查询数据由:<a href=\"http://kuaidi100.com\" target=\"_blank\">KuaiDi100.Com (快递100)</a> 网站提供 ';
//优先使用curl模式发送数据
if (function_exists('curl_init') == 1){
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_HEADER,0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
curl_setopt ($curl, CURLOPT_TIMEOUT,5);
$con = curl_exec($curl);
curl_close ($curl);
} return 'document.write("' . $con .'<br/>' . $powered.'");';
}
爱查快递 http://api.ickd.cn/?id=[]&secret=[]&com=[]&nu=[]&type=[]&encode=[]&ord=[]&lang=[]
/*com 必须 快递公司代码(英文),所支持快递公司见如下列表
nu 必须 快递单号,长度必须大于5位
id 必须 授权KEY,申请请点击快递查询API申请方式
在新版中ID为一个纯数字型,此时必须添加参数secret(secret为一个小写的字符串)
secret 必选(新增) 该参数为新增加,老用户可以使用申请时填写的邮箱和接收到的KEY值登录http://api.ickd.cn/users/查看对应secret值
type 可选 返回结果类型,值分别为 html | json(默认) | text | xml
encode 可选 gbk(默认)| utf8
ord 可选 asc(默认)|desc,返回结果排序
lang 可选 en返回英文结果,目前仅支持部分快递(EMS、顺丰、DHL)*/
  function lookorder($com,$nu,$type)
{
$api_id = API_Id;
$api_sceret = API_Sceret;
$url2 = "http://api.ickd.cn/?com=" . $com . "&nu=" . trim($nu) . "&id=" . $api_id . "&type=" . $type . "&secret=" . $api_sceret . "&encode=utf8";
$con = file_get_contents($url2);
if ($type == "json") {
return $con;
} else {
return "document.write('" . $con . "');";
}
}