lgn21st
2/17/2015 - 12:57 PM

Yunbi PHP API

Yunbi PHP API

<?php
/**
 * Class Api_Btc_Yunbi
 */
class Api_Btc_Yunbi
{
	const ACCESS_KEY = '您在云币的公钥';
	const SECRET_KEY = '您在云币的私钥';

	/**
	 * 牌价
	 *
	 * @param string $coin 币种
	 * @return array|bool
	 */
	public function ticker($coin)
	{
	}

	/**
	 * 获取账号资产信息
	 */
	public function getAccountInfo()
	{
		if(!$result = $this->_request('/api/v2/members/me.json')){
			return false;
		}
		return $result;
	}

	/**
	 * 挂单
	 * @param $type string 买卖(buy/sell)
	 * @param float $price 价格
	 * @param float $amount 数量
	 * @return bool
	 */
	public function trade($type, $coin, $price, $amount)
	{
		if(!$result = $this->_request('/api/v2/orders.json', 'POST', array('market'=>$coin.'cny', 'price'=>$price, 'side'=>$type, 'volume'=>$amount))){
			return false;
		}
		return $result;
	}

	/**
	 * 请求API
	 * 
	 * @param string $url 接口地址
	 * @param string $method 请求方式(GET/POST)
	 * @param array $params 参数
	 * @return bool|array
	 */
	private function _request($url, $method = 'GET', $params = array()){
		static $ch = null;
		if(is_null($ch)){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		}
		$params['access_key'] = self::ACCESS_KEY;
		# tonce
		$mt = explode(' ', microtime());
		$params['tonce'] = $mt[1] . substr($mt[0], 2, 3);
		# 请求参数
		ksort($params);
		$param = http_build_query($params);
		# 签名
		$param.= '&signature='.hash_hmac('sha256', "$method|$url|$param", self::SECRET_KEY);
		# 请求方式
		if('POST' == $method){
			curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
		} else {
			$url .= '?'.$param;
		}
		curl_setopt($ch, CURLOPT_URL, 'https://yunbi.com'.$url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$result = curl_exec($ch);
		if(!$result = json_decode($result, true)){
			return false;
		}
		return $result;
	}
}

# 实例化
$api = new Api_Btc_Yunbi;

# 查询账号资产
$api->getAccountInfo();

# 以一元的价格,买0.01个比特币
$api->trade('buy', 'btc', '1', '0.01');

# 更多接口调用,可模拟 trade 函数实现。