Home >php教程 >PHP源码 >简单实现淘宝API调用

简单实现淘宝API调用

PHP中文网
PHP中文网Original
2016-05-25 17:03:572541browse

简单实现淘宝API调用

简单实现了淘宝API的调用的类,暂时没有考虑session,可以参照淘宝api实现各种功能,比如获取宝贝详情、图片链接等。欢迎提建议

<?php
 
class TaobaoApi {
    /*
     * 定义并初始化参数数组,某些固定参数可写在这个位置
     */
 
    protected $_param = array(&#39;app_key&#39; => &#39;21572060&#39;, &#39;v&#39; => &#39;2.0&#39;,
        &#39;sign_method&#39; => &#39;md5&#39;, &#39;format&#39; => &#39;xml&#39;);
    /*
     * Sign值存储变量
     */
    protected $_sign;
    /*
     * 应用密码存储变量
     */
    public $secret = &#39;your secret&#39;;
    /*
     * 请求URL存储变量
     */
    protected $_url;
 
    public function run() {
        $this->createSign();
        $this->createRequestUrl();
        return $this->requestData();
    }
 
    /*
     * 通过魔法赋值向参数数组写入数据
     * @param string $name 数组名
     * @param string $value 数组键值
     */
 
    public function __set($name, $value) {
        $this->_param[$name] = $value;
    }
 
    /*
     * 组建Sign
     * @global $this->_param 参数数组
     * @global $this->secret 应用密钥
     */
 
    protected function createSign() {
        $this->_param[&#39;timestamp&#39;] = date(&#39;Y-m-d H:i:s&#39;);
        ksort($this->_param, SORT_STRING); //数组按键值排序
        $tmp = &#39;&#39;;
        foreach ($this->_param as $key => $value) {
            $tmp.= $key . $value;
        }
        $this->_sign = strtoupper(md5($this->secret . $tmp . $this->secret));
    }
 
    /*
     * 由参数和Sign值组合成请求URL
     * @global $this->_param
     * @global $this->url
     */
 
    protected function createRequestUrl() {
        $this->_param[&#39;timestamp&#39;] = urlencode($this->_param[&#39;timestamp&#39;]);
        $this->_url = &#39;http://gw.api.taobao.com/router/rest?sign=&#39; . $this->_sign;
        foreach ($this->_param as $key => $value) {
            $this->_url.=&#39;&&#39; . $key . &#39;=&#39; . $value;
        }
    }
 
    /*
     * 获取数据
     */
 
    protected function requestData() {
        return file_get_contents($this->_url);
    }
 
}
 
$a = new TaobaoApi();
//下面只要写入淘宝API规定必须传入的参数
$a->method = &#39;taobao.item.get&#39;;
$a->fields = &#39;desc,nick&#39;;
$a->app_key = &#39;your key&#39;;
$a->secret = &#39;your secret&#39;;
$a->num_iid = 16096610668;
//默认以xml方式输出
echo $a->run();
?>

                   

以上就是简单实现淘宝API调用的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn