手把手教你作關鍵詞匹配項目(搜索引擎)---- 第八天

第八天php

話說小帥帥自從走進了淘寶開放平臺這個迷霧森林,感受這迷霧森林好大,正當他無所適從的時候。json

一位悅耳動聽的聲音響起來了,甜甜的聲音說道:親,想經過這片森林嗎,我將指引你前進。api

小帥帥一聽,那種感受,身體不禁自主的跟隨這聲音而去,忽然一道強光閃過,啊.....session

小帥帥驚醒了。小帥帥一看時間,我滴個天,這麼晚了。就這樣小帥帥從業一來第一次遲到。app

其實小帥帥在平臺裏面琢磨了一個晚上,整個晚上其實也沒琢磨個啥出來。框架

正當要到公司的時候,手機的鈴聲響起來了,一看是於老大的電話,接通電話。less

於老大問候到:小帥帥,早啊, 你何時到公司丫。curl

小帥帥答到: 於老大,很差意思丫,昨天晚上研究那個淘寶開放平臺,研究太玩了,今早睡過頭了。不過我快到公司了....post

於老大一聽,很差意思責怪小帥帥啥,只好說道:辛苦你了,注意休息,學會勞逸結合...ui

小帥帥,回到: 好的,謝謝於老大的教誨,沒事就掛了哈。。( 0懼怕於老大的糖衣炮彈0 )

小帥帥回到公司後,於老大就給了一份整理後的Topclient給小帥帥,讓他去研究下,看樣子小帥帥仍是樂於研究代碼,讓他看開放平臺,還真看不出什麼。

淘寶寶貝API文檔:http://open.taobao.com/api/api_cat_detail.htm?spm=a219a.7386789.0.0.AjaroV&cat_id=4&category_id=102

Topclient來自Taobao SDK ,只是稍微修正,去掉了一些框架的依賴,源碼爲:

<?php

class TopClient
{
    public $appkey;

    public $secretKey;

    public $gatewayUrl = "http://gw.api.taobao.com/router/rest";

    public $format = "json";

    /** 是否打開入參check**/
    public $checkRequest = true;

    protected $signMethod = "md5";

    protected $apiVersion = "2.0";

    protected $sdkVersion = "top-sdk-php-20110929";

    protected function generateSign($params)
    {
        ksort($params);

        $stringToBeSigned = $this->secretKey;
        foreach ($params as $k => $v) {
            if ("@" != substr($v, 0, 1)) {
                $stringToBeSigned .= "$k$v";
            }
        }
        unset($k, $v);
        $stringToBeSigned .= $this->secretKey;

        return strtoupper(md5($stringToBeSigned));
    }

    protected function curl($url, $postFields = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


        if (is_array($postFields) && 0 < count($postFields)) {
            $postBodyString = "";
            $postMultipart = false;
            foreach ($postFields as $k => $v) {
                if ("@" != substr($v, 0, 1)) //判斷是否是文件上傳
                {
                    $postBodyString .= "$k=" . urlencode($v) . "&";
                } else //文件上傳用multipart/form-data,不然用www-form-urlencoded
                {
                    $postMultipart = true;
                }
            }
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
            }
        }
        $reponse = curl_exec($ch);

        if (curl_errno($ch)) {
            throw new Exception(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new Exception($reponse, $httpStatusCode);
            }
        }
        curl_close($ch);
        return $reponse;
    }

    protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt)
    {
        $localIp = isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : "CLI";

        $logData = "NAME:$apiName,KEY:$this->appkey,IP:$localIp,URL:$requestUrl,CODE:$errorCode,MSG:" . str_replace("\n", "", $responseTxt);

        $file = fopen('taobao.api.error.log','a+');
        fwrite($file,$logData);
        fclose($file);
    }

    public function execute($request, $session = null, $need_replace = false)
    {
        if ($this->checkRequest) {
            try {
                $request->check();
            } catch (Exception $e) {
                $result = new stdClass();
                $result->code = $e->getCode();
                $result->msg = $e->getMessage();
                return $result;
            }
        }
        //組裝系統參數
        $sysParams["v"] = $this->apiVersion;
        $sysParams["format"] = $this->format;
        $sysParams["method"] = $request->getApiMethodName();
        $sysParams["app_key"] = $this->appkey;
        $sysParams["timestamp"] = date("Y-m-d H:i:s");
        $sysParams["partner_id"] = $this->sdkVersion;
        $sysParams["sign_method"] = $this->signMethod;

        if (null != $session) {

            $sysParams["session"] = $session;
        }

        //獲取業務參數
        $apiParams = $request->getApiParas();

        //簽名
        $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams));

        //系統參數放入GET請求串
        $requestUrl = $this->gatewayUrl . "?";
        foreach ($sysParams as $sysParamKey => $sysParamValue) {
            $requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
        }

        $requestUrl = substr($requestUrl, 0, -1);

        //發起HTTP請求
        try {
            $resp = $this->curl($requestUrl, $apiParams);
        } catch (Exception $e) {
            $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), 'RETRY:' . $e->getMessage());
            $result = new stdClass();
            $result->code = $e->getCode();
            $result->msg = $e->getMessage();
            return $result;
        }

        //解析TOP返回結果
        $respWellFormed = false;
        if ("json" == $this->format) {
            if ($need_replace) {
                $resp = preg_replace('/[\r\n]+/', '', $resp);
            }
            $respObject = json_decode($resp);

            if (null !== $respObject) {
                $respWellFormed = true;
                foreach ($respObject as $propKey => $propValue) {
                    $respObject = $propValue;
                }
            }
        } else if ("xml" == $this->format) {
            $respObject = @simplexml_load_string($resp);
            if (false !== $respObject) {
                $respWellFormed = true;
            }
        }

        //返回的HTTP文本不是標準JSON或者XML,記下錯誤日誌
        if (false === $respWellFormed) {
            $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
            $result = new stdClass();
            $result->code = 0;
            $result->msg = "HTTP_RESPONSE_NOT_WELL_FORMED";
            return $result;
        }

        return $respObject;
    }
}

淘寶寶貝請求類:

<?php

/**
 * TOP API: taobao.item.get request
 *
 * @author auto create
 * @since 1.0, 2011-09-29 15:36:21
 */
class ItemGetRequest
{
    /**
     * 須要返回的商品對象字段。可選值:Item商品結構體中全部字段都可返回;多個字段用「,」分隔。若是想返回整個子對象,那字段爲item_img,若是是想返回子對象裏面的字段,那字段爲item_img.url。新增返回字段:second_kill(是否秒殺商品)、auto_fill(代充商品類型),props_name(商品屬性名稱)
     **/
    private $fields;

    /**
     * 商品數字ID
     **/
    private $numIid;

    private $apiParas = array();

    public function setFields($fields)
    {
        $this->fields = $fields;
        $this->apiParas["fields"] = $fields;
    }

    public function getFields()
    {
        return $this->fields;
    }

    public function setNumIid($numIid)
    {
        $this->numIid = $numIid;
        $this->apiParas["num_iid"] = $numIid;
    }

    public function getNumIid()
    {
        return $this->numIid;
    }

    public function getApiMethodName()
    {
        return "taobao.item.get";
    }

    public function getApiParas()
    {
        return $this->apiParas;
    }

    public function check()
    {
        RequestCheckUtil::checkNotNull($this->fields, "fields");
        RequestCheckUtil::checkNotNull($this->numIid, "numIid");
        RequestCheckUtil::checkMinValue($this->numIid, 1, "numIid");
    }
}

數據完整性檢測類

<?php
/**
 * API入參靜態檢查類
 * 能夠對API的參數類型、長度、最大值等進行校驗
 *
 **/
class RequestCheckUtil
{
    /**
     * 校驗字段 fieldName 的值$value非空
     *
     **/
    public static function checkNotNull($value,$fieldName) {
        
        if(self::checkEmpty($value)){
            throw new Exception("client-check-error:Missing Required Arguments: " .$fieldName , 40);
        }
    }

    /**
     * 檢驗字段fieldName的值value 的長度
     *
     **/
    public static function checkMaxLength($value,$maxLength,$fieldName){        
        if(!self::checkEmpty($value) && strlen($value) > $maxLength){
            throw new Exception("client-check-error:Invalid Arguments:the length of " .$fieldName . " can not be larger than " . $maxLength . "." , 41);
        }
    }

    /**
     * 檢驗字段fieldName的值value的最大列表長度
     *
     **/
    public static function checkMaxListSize($value,$maxSize,$fieldName) {    

        if(self::checkEmpty($value))
            return ;

        $list=split(",",$value);
        if(count($list) > $maxSize){
                throw new Exception("client-check-error:Invalid Arguments:the listsize(the string split by \",\") of ". $fieldName . " must be less than " . $maxSize . " ." , 41);
        }
    }

    /**
     * 檢驗字段fieldName的值value 的最大值
     *
     **/
    public static function checkMaxValue($value,$maxValue,$fieldName){    

        if(self::checkEmpty($value))
            return ;

        self::checkNumeric($value,$fieldName);

        if($value > $maxValue){
                throw new Exception("client-check-error:Invalid Arguments:the value of " . $fieldName . " can not be larger than " . $maxValue ." ." , 41);
        }
    }

    /**
     * 檢驗字段fieldName的值value 的最小值
     *
     **/
    public static function checkMinValue($value,$minValue,$fieldName) {
        
        if(self::checkEmpty($value))
            return ;

        self::checkNumeric($value,$fieldName);
        
        if($value < $minValue){
                throw new Exception("client-check-error:Invalid Arguments:the value of " . $fieldName . " can not be less than " . $minValue . " ." , 41);
        }
    }

    /**
     * 檢驗字段fieldName的值value是不是number
     *
     **/
    protected static function checkNumeric($value,$fieldName) {
        if(!is_numeric($value))
            throw new Exception("client-check-error:Invalid Arguments:the value of " . $fieldName . " is not number : " . $value . " ." , 41);
    }

    /**
     * 校驗$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     *    
     *
     **/
    public static function checkEmpty($value) {
        if(!isset($value))
            return true ;
        if($value === null )
            return true;
        if(trim($value) === "")
            return true;
        
        return false;
    }
}

來自Taobao SDK,非原創。稍微修訂。

小帥帥拿着一看,又是天書,悲劇了。。 繼續研究吧。。

就這樣小帥帥又躲深山去修煉九陰真經了。

相關文章
相關標籤/搜索