>php教程 >PHP源码 >淘宝api

淘宝api

PHP中文网
PHP中文网원래의
2016-05-25 17:10:311024검색

php代码

<?php
class HelloTop
{
	static private $instance = null;
	static public function instance()
	{
		if (static::$instance === null)
			static::$instance = new static;
		return static::$instance;
	}
	//不分析错误直接获取数据...
	static function factory(array $arr)
	{
		$top = static::instance();
		return $top->exec($arr)->analyze();
	}
	
	private $appSecret, $appKey, $url, $paramArr, $jsonData;
	protected function __construct()
	{
		$this->appKey = &#39;top.app.key&#39;;
		$this->appSecret = &#39;top.app.secret&#39;;
		$this->url = false ? &#39;http://gw.api.tbsandbox.com/router/rest&#39;
			: &#39;http://gw.api.taobao.com/router/rest&#39;;
		$this->paramArr = array(
			&#39;app_key&#39; => $this->appKey,
			&#39;format&#39; => &#39;json&#39;,
			&#39;v&#39; => &#39;2.0&#39;,
			&#39;sign_method&#39;=>&#39;md5&#39;,
			&#39;timestamp&#39; => date(&#39;Y-m-d H:i:s&#39;)
		);
	}
	//单例重置
	private function reset()
	{
		$this->errno = 0;
		$this->errmsg= null;
		$this->jsonData = null;
	}
	//执行
	public function exec(array $arr)
	{
		$this->reset();
		if (!array_key_exists(&#39;method&#39;, $arr) || !$arr[&#39;method&#39;])
			throw new Exception(&#39;没有方法??&#39;);
		$paramArr = array_merge($this->paramArr, $arr);
		
		$sign = $this->createSign($paramArr);
		$strParam = http_build_query($paramArr) . &#39;&sign=&#39; . $sign;
		
		$url = $this->url . &#39;?&#39; . $strParam;
		$ctx = stream_context_create(array(
		   &#39;http&#39; => array(
			   &#39;timeout&#39; => 5 //设置一个超时时间,单位为秒
			   )
		   )
		);
		$result = file_get_contents($url, 0, $ctx);
		$json = json_decode(preg_replace("/[\r\n]/", &#39;&#39;, $result), true); //desc的数据有问题
		$this->jsonData = array_key_exists(&#39;rsp&#39;, $json) ? $json[&#39;rsp&#39;] : $json;
		return $this;
	}
	
	//获取json数据
	public function data()
	{
		return $this->jsonData;
	}
	
	private $errno, $errmsg;
	//分析数据,错误返回false,自行使用 errmsg 方法获取错误提示
	public function analyze()
	{
		if (array_key_exists(&#39;error_response&#39;, $this->jsonData)){
			$this->errno = $this->jsonData[&#39;error_response&#39;][&#39;code&#39;];
			$this->errmsg= $this->jsonData[&#39;error_response&#39;][&#39;sub_msg&#39;];
			return false;
		}else{
			return $this->data();
		}
	}
	public function errmsg()
	{
		return $this->errmsg;
	}
	
	//签名函数
	protected function createSign ($paramArr) {
		$sign = $this->appSecret;
		ksort($paramArr);
		foreach ($paramArr as $key => $val)
			if ($key != &#39;&#39; && $val != &#39;&#39;) {
				$sign .= $key.$val;
			}
		$sign .= $this->appSecret;
		$sign  = strtoupper(md5($sign));
		return $sign;
	}
}
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.