<?php
namespace model;
use \model;
/**
 * Class 宜配接口
 * @package model
 */
class ypApi
{
	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',....]
	  * @author soul
	  * @copyright 2017/4/13
	  * @return array
	  */
	public function Get($url_path, $get_arr=[], $post_arr=[], $run = 0)
	{
		try {
			$run++;
			$url = $this->config['base_url'].$url_path;
			$get_arr['token'] =  $this->config['token'];
			$url = $url.'?'.http_build_query($get_arr);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60000);
			if(!empty($post_arr))
			{
				curl_setopt($ch, CURLOPT_POST, true);
				curl_setopt($ch, CURLOPT_POSTFIELDS, ['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) && (!isset($return['status']) || $return['status'])) return $return;

			if($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $run);
			errorLog(['url'=>$url, 'post'=>$post_arr, 'html'=>$html], 'ypapi');
			exitJson('ypapi:'.$html);
		}catch (Exception $e) {
			if($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $run);
			errorLog(['url'=>$url, 'post'=>$post_arr, 'html'=>$e->getMessage()], 'ypapi');
			exitJson('ypapi:'.$e->getMessage());
		}
	}
}