PHP 快遞查詢介面,快遞鳥物流查詢 API 的二次封裝. 輕輕鬆鬆呼叫它

南宋X發表於2019-02-16

關於快遞鳥API的二次封裝

/****
**  快遞鳥
**    getOrderTracesByJson() 
**    ->$eBusinessID       //電商的ID        
**    ->$appKey             //電商加密私鑰,快遞鳥提供,注意保管,不要洩漏
**     ->$reqURL              //電商的ID
**  ->$shipperCode       //快遞商編號
**     ->$logisticCode       //快遞單號
****/

class NanSongKdApiSearch
{
        /**
     * Json方式 查詢訂單物流軌跡
     */
    public function getOrderTracesByJson($eBusinessID, $appKey, $reqURL, $shipperCode, $logisticCode){

        $requestData= "{`OrderCode`:``,`ShipperCode`:$shipperCode,`LogisticCode`:$logisticCode  }";

        $datas = array(
            `EBusinessID` => $eBusinessID,
            `RequestType` => `1002`,
            `RequestData` => urlencode($requestData) ,
            `DataType` => `2`,
        );
        $datas[`DataSign`] = $this->encrypt($requestData, $appKey);
        $result=$this->sendPost($reqURL, $datas);    
        
        //根據公司業務處理返回的資訊......
        
        return $result;
    }
     
    /**
     *  post提交資料 
     * @param  string $url 請求Url
     * @param  array $datas 提交的資料 
     * @return url響應返回的html
     */
    public 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(empty($url_info[`port`]))
        {
            $url_info[`port`]=80;    
        }
        $httpheader = "POST " . $url_info[`path`] . " HTTP/1.0
";
        $httpheader.= "Host:" . $url_info[`host`] . "
";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded
";
        $httpheader.= "Content-Length:" . strlen($post_data) . "
";
        $httpheader.= "Connection:close

";
        $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 == "
" || $header == "
")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);  
        
        return $gets;
    }

    /**
     * 電商Sign簽名生成
     * @param data 內容   
     * @param appkey Appkey
     * @return DataSign簽名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
}

相關文章