Your IP : 18.221.84.179


Current Path : /home/bitrix/ext_www/ballu.in.ua/local/modules/rusklimat.exchange/classes/general/
Upload File :
Current File : /home/bitrix/ext_www/ballu.in.ua/local/modules/rusklimat.exchange/classes/general/connect.php

<?php
/*
 * RusKlimat CatalogModule
 * Класс для подключения работы со шлюзом
 * 
 * @author  Alex
 * @date   04/12/2017
*/


IncludeModuleLangFile(__FILE__);

class RusklimatConnect
{
	protected $api_address = array(
		"price" => "crm/price/", //Цены на товары для сайта-подписчика.

		"xmlidlist" => "nsi/nomenclature/xmlIdList/", // все активные товары
		"available"	=> "crm/invisible/", 		// доступность товаров
		"properties" => "nsi/nomenclature/properties/",
		"units" => "nsi/nomenclature/baseUnits/", // Единицы измерения
		//Описание свойств товаров 
		//GET - параметры:
		//limit
		//offset
		//guid – GUID свойства (берется в характеристиках номенклатуры из Характеристика@ПередаваемаяЗапись -> ИдентификаторВБазе)
		"invisible_full" => "crm/invisible/", 	// http://api.rusklimat.ru/v0/crm/invisible/region/54c02fcd-7441-11e6-9430-9cb654954508 крываемый товар по региону
		"invisible_region" => "crm/invisible/getAll", 	// http://api.rusklimat.ru/v0/crm/invisible/region/54c02fcd-7441-11e6-9430-9cb654954508 крываемый товар по региону
		"prepay" => "crm/goods/prepay/getAll", // компбинации предоплаты в регионах
		"preorder" => "crm/goods/orderInRegion/getAll", // компбинации подзаказ в регионах, где показываем наличие
		"export_yandex" => "crm/goods/exportYandex/getAll", // комбинация вывода в YML по регионам

		"priceBush" => "crm/priceBush/", // - кусты
		"citybush" => "crm/priceBush/bindings/", // - привязка куста к городу

		"globusregions" => "crm/globus/regions/", // - список городов и регионов
		"paymentTip" => "crm/globus/paymentTip/", // - подключаемые типы оплат
		"warehouse" => "crm/globus/warehouse/", // - склады
		"warehousepumplink" => "crm/globus/warehouseConsist/", // - связь склада с депом и складом в pump
		"quotasConsist" => "crm/globus/quotasConsist/", // - список сквозных квот
		"deliveryTariff" => "crm/globus/deliveryTariff/", // - тарифы доставки
		"deliveryTariffIntercity" => "crm/globus/deliveryTariffIntercity/", // - тарифы доставки между городами
		"siteInfo" => "crm/globus/siteInfo/", // - телефоны, время работы, почта для отображения на сайте
		"workSchedule" => "crm/globus/workSchedule/", // – время работы складов для самовывоза
		"deliveryInterval" => "crm/globus/deliveryInterval/", // – время работы приема заказов в городах

		"nomenclature" => "nsi/nomenclature", // – товары, выгружаемые на сайт
		"catalog" => "nsi/catalog", // – каталог товаров
		"createOrder"=>'crm/order/create', 	// создание заказа
		"importZapros"=>'crm/web-form/send', 	// отправка запроса
		"ostatki_make" => "pump/remains/make", //подготовка срезов по остаткам. Содержит объекты виртуальных складов с привязкой их к городам.
		"ostatki_wh" => "pump/remains/warehouse/", //содержимое виртуального склада. Передает всю номенклатуру, подключенную к сайту. Ключ – id товара, значение [Остатки филиала, остатки ррц/фрц]
		"file_get" => "nsi/files/download/", // загрузка конкретного файла

		"file_info" => "nsi/files/", //- список описаний файлов
			//	GET - параметры:
			//	limit
			//	offset
			//	guid – GUID файла
		"conditions" => "crm/actions/conditions",	// - описание условий применений акций
		"schedule" => "crm/actions/schedule",	// - расписание работы акций по дням недели
		"gifts" => "crm/actions/gifts",	// - подарки по акциям
		"goodsApplying" => "crm/actions/goodsApplying",	// – товары, участвующие в акциях
		"goodsException" => "crm/actions/goodsException",	// - товары, не участвующие в акциях
		"displacement" => "crm/actions/displacement",	// - заменяемые товары
		"timeToBuy" => "crm/actions/timeToBuy",	// - время действия акций
		"actions" => "crm/actions", // - список акций
		"actions_regions" => "crm/actions/regions", 	// regions - привязка акций к кустам
		"actions_download" => "crm/actions/download/", // – скачивание баннеров акций. Сейчас умеет только обрабатывать jpg и png
		"actionstimetobuy" => "crm/actions/timeToBuy/", //акция "успей купить"
	);
	
	protected $api_url = "";
	protected $api_key = "";
	protected $last_http_header = array();
	
	
	public function __construct(){
		
		$this->api_url = COption::GetOptionString("rusklimat.exchange", "RK_EXCHANGE_MAIN_SERVER_API_URL");
		$this->api_key = COption::GetOptionString("rusklimat.exchange", "RK_EXCHANGE_MAIN_SERVER_API_KEY");

		if(empty($this->api_url) || empty($this->api_key))
			throw new Exception('Empty api_url or api_key setting module Rusklimat');
	
	}
	
	/*
	 * Получить адрес по имени
	 */
	public function getAddress($addressName = "")
	{
		if (empty($addressName))
            throw new Exception('Empty Api address name from getAddress function');
		
		return $this->api_address[$addressName];
	}
	
	/*
	 * получение данных со шлюза
	 */
	// $direct - если указан путь напрямую, а не из массива $api_address
	// $api_url_custom - указывается если идет обращение не к стандартному URL-адресу шлюза, пример в exchange_wh.php
    public function getRest($address = "", $data = array(), $method = "GET", $direct = false, $api_url_custom = false)
    {
		$url = ""; // куда обращаемся
		$opts = ""; // Параметры подключения
		$service = ""; // к какому методу обращаемся
		
		if (empty($address))
            throw new Exception('Empty Api address name from getRest function');
		if (!array_key_exists($address, $this->api_address) && $direct === false)
            throw new Exception('Wrong Api address name from getRest function');
		
		if($direct === false)
			$service = $this->api_address[$address];
		else
			$service = $address;
		
		if($api_url_custom)
			$url = $api_url_custom . $service;
		else
			$url = $this->api_url . $service;
		
		$opts = array(
			'http' =>
				array(
					'method'  => $method,
					'header'  => "Authorization: ".$this->api_key,
				)
		);
		
		// добавляем параметры
		if(!empty($data) && $method != "GET"){
			$opts['http']['content'] = http_build_query($data);
		} elseif(!empty($data) && $method == "GET") {
			$url .= "?" . http_build_query($data);
		}

		$context = stream_context_create($opts);
		
		try {
			$result = file_get_contents($url, false, $context);
		} catch (Exception $e) {
			throw new Exception('Error: file_get_contents response False - '. $e->GetMessage() . ' | from getRest function');
		}
		
		$responce = json_decode($result, true);
		
		if(!empty($responce["data"]["message"])) // если есть сообщение об ошибке
			throw new Exception('Error: ' . $responce["data"]["message"] . ' | from getRest function');
		
		return $responce;
    }
	
	/*
	 * Получить файл
	 */
	public function getRestFile($address){
		
		if (empty($address))
            throw new Exception('Empty Api address name from getRestFile function');
		
		$url = $this->api_url.$address;
		
		$opts = array('http' =>
			array(
				'method'  => "POST",
				'header'  => "Authorization: ".$this->api_key,
			)
		);

		$context  = stream_context_create($opts);
		
		$result = file_get_contents($url, false, $context);
		
		$this->setLastHttpHeader($http_response_header);

		if($result !== false)
			return $result;
		else
			return "error";
	}
	
	/*
	 * Установить последний http ответ
	 */
	protected function setLastHttpHeader($responsive)
	{
		if (empty($responsive))
            throw new Exception('Empty $responsive from setLastHttpHeader function');
		
		$this->last_http_header = $responsive;
	}
	
	/*
	 * Получить последний http ответ
	 */
	public function getLastHttpHeader()
	{
		if(!empty($this->last_http_header))
			return $this->last_http_header;
		else
			return "Error: empty last_http_header";
	}
	
}