首页 > php教程 > PHP源码 > 正文

淘宝api

PHP中文网
发布: 2016-05-25 17:10:31
原创
1300人浏览过

php代码

家作
家作

淘宝推出的家装家居AI创意设计工具

家作 37
查看详情 家作
<?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;
	}
}
登录后复制
淘宝
淘宝

淘宝是一个好逛、丰富、有趣的消费生活社区,每天有亿万消费者来淘宝“逛街”:发现好物、找到乐趣、表达体验……淘宝能满足人们生活中的各种需求,有需要的小伙伴快来保存下载体验吧!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号