<?php
/*
*宜配公共接口
*/
class LibYpApi
{
	protected $config = null;

	function __construct()
	{
		$this->config = mvc::$cfg['YPAPI'];
	}
	
	/**
	  * @method 发送短信
	  * @http  POST
	  * @param  $url_path           string [必填] action/method
	  * @param  $get_arr            array  [可选] ['name'=>'soul',....]
	  * @param  $post_arr           array  [可选] ['name'=>'soul',....]
	  * @param  $onlyRes            bool   [可选] 直接返回原始结果？
	  * @author soul
	  * @copyright 2017/4/13
	  * @return array
	  */
	public function Get($url_path, $get_arr=[], $post_arr=[], $onlyRes = false, $run = 0)
	{
		try {
			$run++;
			$url = $this->config['base_url'].$url_path;
			if($get_arr) $url = $url.'?'.http_build_query($get_arr);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
			curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
			if(empty($post_arr)) $post_arr = [];
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, ['token'=>$this->config['token'], 'data'=>json_encode($post_arr)]);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$ssl = substr($url, 0, 8) == "https://" ? true : false;
			if($ssl)
			{
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			}
			$html = curl_exec($ch);
			curl_close($ch);
			//处理错误提示
			$return = json_decode($html, true);
			if(is_array($return)){
				if($onlyRes) return $return;
				return LibFc::ReturnData($return['status'],$return['data'], $return['code']);
			}else{
				if($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $onlyRes, $run);
				LibLog::write("PJLAPI请求出错:".$url.'=>'.json_encode($post_arr, JSON_UNESCAPED_UNICODE).'=>'.$html);
				return LibFc::ReturnData(false, $url_path.'接口请求异常'.$html);
			}
		}catch (Exception $e) {
			if($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $onlyRes, $run);
			LibLog::write("PJLAPI请求出错:".$url.'=>'.json_encode($post_arr, JSON_UNESCAPED_UNICODE).'=>'.$e->getMessage());
			return LibFc::ReturnData(false, $url_path.'接口请求异常');
		}
	}
}