不言不语

您现在的位置是: 首页 >  PHP

PHP

php自定义快递查询API类(支持各种快递的查询)

2022-05-31PHP
无需输入快递公司,只要直接输入快递单号就可以自动识别快递单号所在快递公司,还是非常方便的,只要几行代码就可以完美的集成到你系统的功能中了!

无需输入快递公司,只要直接输入快递单号就可以自动识别快递单号所在快递公司,还是非常方便的,只要几行代码就可以完美的集成到你系统的功能中了!

直接把代码放出来

<?php


/**
 * Express.class.php 快递查询类
 *
 * @author 言语
 * @date 2017/09/27
 */

class Express {

    /*
    * 采集网页内容的方法
    */
    private function getContent($url){

        if(function_exists("file_get_contents")){
            $file_contents = file_get_contents($url);
        }else{
            $ch = curl_init();
            $timeout = 5;   // 设置5秒超时
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        }
        return $file_contents;

    }


    public function getOrder($order_no=''){

        $result = $this->getContent("http://www.kuaidi100.com/autonumber/autoComNum?text=".$order_no);
        $data = json_decode($result,true);

        return $data;

    }


    // http://www.kuaidi100.com/query?type=zhongtong&postid=453371918456&id=1&valicode=&temp=0.40349807080624434
    //  返回的数据结果参考官方文档:https://www.kuaidi100.com/openapi/api_post.shtml
    /**
     * 直接调用该方法,传入物流单号即可查询物流信息
     * @param string $order_no
     * @return bool|mixed
     */
    public function getLogisticsInfo($order_no=''){

        $result = $this->getOrder($order_no);
        $auto_arr = $result['auto'];

        if(count($auto_arr)>0){
            foreach ($auto_arr as $key => $value){
                $temp = $this->randFloat();
                $comCode = $value['comCode'];
                $url = "http://www.kuaidi100.com/query?type=$comCode&postid=$order_no&id=1&valicode=&temp=$temp";// $temp 随机数,防止缓存
                $json = $this->getContent($url);
                $data = json_decode($json,true);
                if($data['message']=='ok'){
                    return $data;
                }
            }
        }

        return false;

    }


    /**
     * 生成0~1随机小数
     * @param Int  $min
     * @param Int  $max
     * @return Float
     */
    function randFloat($min=0, $max=1){
        return $min + mt_rand()/mt_getrandmax() * ($max-$min);
    }


}

使用如下,只需要调用类中的getLogisticsInfo()方法,参数传入订单号即可

$e = new Express();
$data = $e->getLogisticsInfo("453371918456");

echo '<pre>';
var_dump($data);


返回的结果参数说明如下

111.png

得到的物流信息示例如下

php自定义快递查询API类(支持各种快递的查询)

文章评论