官方给的php代码如下:
$host = "https://ali-deliver.showapi.com";
$path = "/showapi_expInfo";
$method = "GET";
$appcode = "你自己的AppCode";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "com=zhongtong&nu=535962308717&receiverPhone=receiverPhone&senderPhone=senderPhone";
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
if (1 == strpos("$".$host, "https://"))
{
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
var_dump(curl_exec($curl));
我写的代码如下:
// 查看物流信息接口
// $lo_num物流单号,$ename物流公司英文简写
public function see_wulius($lo_num,$ename){
$host = "https://ali-deliver.showapi.com";
$path = "/showapi_expInfo";
$method = "GET";
$appcode = "be817881f15540abd3015830f45318fd";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "com=".$ename."&nu=".$lo_num;
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$".$host, "https://")){
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
return (curl_exec($curl));
}
注意 curl_setopt($curl, CURLOPT_HEADER, false); 这里应该用false,不要包体头,这样才会返回json格式数据。如果按照官方给的文档这里是true的话,返回结果是字符串。
为了减少用户请求,我没有采用缓存,而是直接存入数据库,这样永久保留数据,什么时候都可以查看物流信息。每次查看物流的时候先判断该表有没有这个物流信息,没有就调接口查询然后存进来,有的话根据状态和过期时间判断是否需要重新请求接口,请求一次接口就更新一次数据,过期时间也更新。