Your IP : 18.224.8.221


Current Path : /home/bitrix/ext_www/easy-comfort.com.ua/local/modules/webprofy.crm/lib/
Upload File :
Current File : /home/bitrix/ext_www/easy-comfort.com.ua/local/modules/webprofy.crm/lib/CrmSender.php

<?php
namespace Webprofy\CRM;

use Bitrix\Main\Web\HttpClient;

/**
 * Class CrmSender
 * @package Webprofy\CRM
 */
class CrmSender
{
	private $protocol = 'https://';
	private $portal;
	private $clientID;
	private $clientSecret;
	private $authCode;
	private $refreshCode;

	public function __construct()
	{
		$arAuth = SettingsTable::getData();
		if(!empty($arAuth)){
			$this->portal = $arAuth['PORTAL_URI'];
			$this->clientID = $arAuth['CLIENT_ID'];
			$this->clientSecret = $arAuth['CLIENT_SECRET'];
			$this->authCode = $arAuth['ACCESS_TOKEN'];
			$this->refreshCode = $arAuth['REFRESH_TOKEN'];

			$this->refreshToken();
		}
	}

	public function refreshToken()
	{
		$params = array(
			"grant_type" => "refresh_token",
			"client_id" => $this->clientID,
			"client_secret" => $this->clientSecret,
			"refresh_token" => $this->refreshCode,
		);

		$data = self::_query('get', '/oauth/token/', $params);

		if(!empty($data)){
			$arUpdate = array();

			if(isset($data['access_token'])){
				$this->authCode = $data['access_token'];
				$arUpdate['ACCESS_TOKEN'] = $data['access_token'];
			}

			if(isset($data['refresh_token'])){
				$this->refreshCode = $data['refresh_token'];
				$arUpdate['REFRESH_TOKEN'] = $data['refresh_token'];
			}

			return SettingsTable::updateSettings($arUpdate);
		}
	}

	protected function _query($requestMethod, $restMethod, $params = array())
	{
		$httpClient = new HttpClient();
		$httpClient->setTimeout(3);
		$httpClient->setHeader('Content-Type', 'application/json', true);

		if($requestMethod == 'post'){
			$arPostFields = array();
			$arPostFields['auth'] = $this->authCode;
			$arPostFields = array_merge($params, $arPostFields);
			$response = $httpClient->post($this->protocol . $this->portal . '/rest/' . $restMethod, $arPostFields);
		} else{
			$response = $httpClient->get('https://' . $this->portal . $restMethod . '?' . http_build_query($params));
		}

		$data = json_decode($response, true);

		if(!empty($data)){
			return $data;
		}

		return false;
	}

	public function getFirstToken($code)
	{
		$params = array(
			"grant_type" => "authorization_code",
			"client_id" => $this->clientID,
			"client_secret" => $this->clientSecret,
			"refresh_token" => $this->refreshCode,
			"code" => $code,
		);

		$data = self::_query('get', '/oauth/token/', $params);

		if(!empty($data)){
			$arUpdate = array();

			if(isset($data['access_token'])){
				$this->authCode = $data['access_token'];
				$arUpdate['ACCESS_TOKEN'] = $data['access_token'];
			}

			if(isset($data['refresh_token'])){
				$this->refreshCode = $data['refresh_token'];
				$arUpdate['REFRESH_TOKEN'] = $data['refresh_token'];
			}

			return SettingsTable::updateSettings($arUpdate);
		}
	}
}