欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

淘宝api

程序员文章站 2022-05-15 22:25:31
...
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 = 'top.app.key';
		$this->appSecret = 'top.app.secret';
		$this->url = false ? 'http://gw.api.tbsandbox.com/router/rest'
			: 'http://gw.api.taobao.com/router/rest';
		$this->paramArr = array(
			'app_key' => $this->appKey,
			'format' => 'json',
			'v' => '2.0',
			'sign_method'=>'md5',
			'timestamp' => date('Y-m-d H:i:s')
		);
	}
	//单例重置
	private function reset()
	{
		$this->errno = 0;
		$this->errmsg= null;
		$this->jsonData = null;
	}
	//执行
	public function exec(array $arr)
	{
		$this->reset();
		if (!array_key_exists('method', $arr) || !$arr['method'])
			throw new Exception('没有方法??');
		$paramArr = array_merge($this->paramArr, $arr);
		
		$sign = $this->createSign($paramArr);
		$strParam = http_build_query($paramArr) . '&sign=' . $sign;
		
		$url = $this->url . '?' . $strParam;
		$ctx = stream_context_create(array(
		   'http' => array(
			   'timeout' => 5 //设置一个超时时间,单位为秒
			   )
		   )
		);
		$result = file_get_contents($url, 0, $ctx);
		$json = json_decode(preg_replace("/[\r\n]/", '', $result), true); //desc的数据有问题
		$this->jsonData = array_key_exists('rsp', $json) ? $json['rsp'] : $json;
		return $this;
	}
	
	//获取json数据
	public function data()
	{
		return $this->jsonData;
	}
	
	private $errno, $errmsg;
	//分析数据,错误返回false,自行使用 errmsg 方法获取错误提示
	public function analyze()
	{
		if (array_key_exists('error_response', $this->jsonData)){
			$this->errno = $this->jsonData['error_response']['code'];
			$this->errmsg= $this->jsonData['error_response']['sub_msg'];
			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 != '' && $val != '') {
				$sign .= $key.$val;
			}
		$sign .= $this->appSecret;
		$sign  = strtoupper(md5($sign));
		return $sign;
	}
}
相关标签: 淘宝api