淘宝开放平台SDK简洁版

之前做淘宝开放平台开发时候留的一个简单版的sdk(也就是一个class……)。share一下

调用:

$taobao = new taobao(key,secret_key);

$taobao->method = 'taobao.xxx.xx';
$taobao->fields = 'xxxxxxxxx';
$taobao->nick = 'xxxx';
//或者: $taobao->setnick('xxxx');
$rowset = $taobao->execute();

每个接口需要什么参数,自己完善。当初俺就这么熬过来的:)

完整代码(缓存部分自己完善):

class taobao {
    private $param = array();
    public $url = '';

    private $public_key = '';
    private $secret_key = '';

    public $error = '';

    public function __construct($a,$s) {
        $this->public_key = $a;
        $this->secret_key = $s;
    }

    public function __set($key,$val) {
        $this->param[$key] = $val;
    }

    public function __call($m,$args) {
        if (substr($m,0,3) == 'set') {
            $this->param[substr($m,3)] = $args;
            return true;
        }

        return false;
    }

    /**
     * 通过淘宝API获取数据
     *
     * @param int $cache_expire 大于0的数字,将缓存该值同时为缓存过期时间
     * @return json
     */
    public function execute($cache_expire=0) {
        $api = 'http://gw.api.taobao.com/router/rest';
        $this->param['parent_id'] = 'top-apitools';
        $this->param['format'] = 'json';
        $this->param['timestamp'] = date('Y-m-d H:i:s');
        $this->param['app_key'] = $this->public_key;
        $this->param['v'] = '2.0';
        $this->param['sign_method'] = 'hmac';
        $secret_key = $this->secret_key;

        ksort($this->param);

        // 拼凑字符串
        $str = '';
        foreach ($this->param as $k=>$v) $str .= $k.$v;

        $this->param['sign'] = strtoupper(bin2hex(mhash(1,$str,$secret_key)));

                $this->url = $api.'?'.http_build_query($this->param);

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$api);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$this->param);
        $ret = curl_exec($ch);
        curl_close($ch);
        $ret = @json_decode($ret,1);

        $this->param = array();

        if (isset($ret['error_response'])) {
            $this->error = $ret['error_response']['sub_msg'];
            $this->errno = $ret['error_response']['code'];
            return false;
        } else {
            return $ret;
        }
    }
}
去打赏

您的支持将鼓励我们继续创作!

[微信] 扫描二维码打赏

发表评论

电子邮件地址不会被公开。