1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
restclient.php
См. документацию.
1<?php
2
3namespace Bitrix\Sale\Services\Base;
4
5use Bitrix\Main\Error;
6use Bitrix\Main\License\UrlProvider;
7use Bitrix\Main\Loader;
8use Bitrix\Main\ModuleManager;
9use Bitrix\Sale\Result;
10use Bitrix\Main\Context;
11use Bitrix\Main\Web\Json;
12use Bitrix\Main\Config\Option;
13use Bitrix\Main\Text\Encoding;
14use Bitrix\Main\Web\HttpClient;
15use Bitrix\Main\Localization\Loc;
16use Bitrix\Sale\ResultSerializable;
17
18Loc::loadMessages(__FILE__);
19
21{
22 const REST_URI = '/rest/';
23 const REGISTER_URI = '/oauth/register/';
24 const SCOPE = 'sale';
25 const SERVICE_ACCESS_OPTION = 'saleservices_access';
26
31
32 const UNSUCCESSFUL_CALL_OPTION = 'sale_hda_last_unsuccessful_call';
33 const UNSUCCESSFUL_CALL_TRYINGS = 3; //times
35
36 protected $httpTimeout = 5;
37 protected $streamTimeout = 10;
38 protected $accessSettings = null;
39 protected $serviceHost = 'https://saleservices.';
40
41 protected $version = 5;
42
52 protected function call($methodName, $additionalParams = null, $licenseCheck = false, $clearAccessSettings = false)
53 {
55
56 if(!self::isServerAlive() && !defined('SALE_SRVS_RESTCLIENT_DISABLE_SRV_ALIVE_CHECK'))
57 {
58 $result->addError(
59 new Error(
60 Loc::getMessage('SALE_SRV_BASE_REST_CONNECT_ERROR').' '.$this->getServiceHost(),
61 self::ERROR_SERVICE_UNAVAILABLE
62 )
63 );
64 return $result;
65 }
66
67 if ($clearAccessSettings)
68 {
69 $this->clearAccessSettings();
70 $this->accessSettings = null;
71 }
72
73 if (is_null($this->accessSettings))
74 {
75 $this->accessSettings = $this->getAccessSettings();
76 }
77
78 if (!$this->accessSettings)
79 {
80 $urlProvider = new UrlProvider();
81 $result->addError(new Error(Loc::getMessage(
82 'SALE_SRV_BASE_REST_ACCESS_SETTINGS_ERROR_MSGVER_1',
83 ['#TECH_DOMAIN#' => $urlProvider->getTechDomain()],
84 )));
85
86 return $result;
87 }
88
89 if (!is_array($additionalParams))
90 $additionalParams = array();
91
92 $additionalParams['version'] = $this->version;
93 $additionalParams['client_id'] = $this->accessSettings['client_id'];
94 $additionalParams['client_secret'] = $this->accessSettings['client_secret'];
95 $additionalParams['lang'] = LANGUAGE_ID;
96
97 if ($licenseCheck)
98 {
99 $additionalParams = static::signLicenseRequest($additionalParams, static::getLicense());
100 }
101
102 $host = $this->getServiceHost();
103 $http = new HttpClient([
104 'socketTimeout' => $this->httpTimeout,
105 'streamTimeout' => $this->streamTimeout,
106 ]);
107 $postResult = @$http->post(
108 $host.static::REST_URI.$methodName,
109 $additionalParams
110 );
111
112 try
113 {
114 $answer = $this->prepareAnswer($postResult);
115 }
116 catch(\Exception $e)
117 {
118 $answer = false;
119 }
120
121 if (!is_array($answer))
122 {
123 $result->addError(new Error(Loc::getMessage('SALE_SRV_BASE_REST_ANSWER_ERROR').' '.$this->getServiceHost().'. (Status: "'.$http->getStatus().'", Result: "'.$postResult.'")', static::ERROR_SERVICE_UNAVAILABLE));
125 return $result;
126 }
127
128 if(self::getLastUnSuccessCount() > 0)
129 $this->setLastUnSuccessCallInfo(true);
130
131 if (array_key_exists('error', $answer))
132 {
133 if ($answer['error'] === 'verification_needed')
134 {
135 if($licenseCheck)
136 {
137 $result->addError(new Error($answer['error'].". ".$answer['error_description'], self::ERROR_WRONG_LICENSE));
138 return $result;
139 }
140 else
141 {
142 return $this->call($methodName, $additionalParams, true);
143 }
144 }
145 else if (($answer['error'] === 'ACCESS_DENIED' || $answer['error'] === 'Invalid client' || $answer['error'] === 'NO_AUTH_FOUND')
146 && !$clearAccessSettings)
147 {
148 return $this->call($methodName, $additionalParams, true, true);
149 }
150
151 $result->addError(new Error($answer['error'].". ".$answer['error_description']));
152 return $result;
153 }
154
155 if ($answer['result'] == false)
156 $result->addError(new Error('Nothing found', static::ERROR_NOTHING_FOUND));
157
158 if (is_array($answer['result']))
159 $result->addData($answer['result']);
160
161 return $result;
162 }
163
168 public function getServiceHost()
169 {
170 $urlProvider = new UrlProvider();
171 if(!defined('SALE_SRVS_RESTCLIENT_SRV_HOST'))
172 {
173 $result = $this->serviceHost . $urlProvider->getTechDomain();
174 }
175 else
176 {
177 $result = SALE_SRVS_RESTCLIENT_SRV_HOST;
178 }
179
180 return $result;
181 }
182
188 protected function prepareAnswer($result)
189 {
190 return Json::decode($result);
191 }
192
197 protected function register()
198 {
199 $result = new Result();
200 $httpClient = new HttpClient();
201
202 $queryParams = array(
203 "scope" => static::SCOPE,
204 "redirect_uri" => static::getRedirectUri(),
205 );
206
207 $queryParams = static::signLicenseRequest($queryParams, static::getLicense());
208 $host = $this->getServiceHost();
209 $postResult = $httpClient->post($host.static::REGISTER_URI, $queryParams);
210
211 if ($postResult === false)
212 {
213 $result->addError(new Error(implode("\n", $httpClient->getError()), static::ERROR_SERVICE_UNAVAILABLE));
214 return $result;
215 }
216
217 try
218 {
219 $jsonResult = Json::decode($postResult);
220 }
221 catch(\Exception $e)
222 {
223 $result->addError(new Error($e->getMessage()));
224 return $result;
225 }
226
227 if (!empty($jsonResult["error"]))
228 {
229 $result->addError(new Error($jsonResult["error"], static::ERROR_WRONG_LICENSE));
230 }
231 else
232 {
233 $result->addData($jsonResult);
234 }
235
236 return $result;
237 }
238
239 public static function signLicenseRequest(array $request, $licenseKey)
240 {
241 if (Loader::includeModule('bitrix24'))
242 {
243 $request['BX_TYPE'] = 'B24';
244 $request['BX_LICENCE'] = defined('BX24_HOST_NAME') ? BX24_HOST_NAME : '';
245 $request['BX_HASH'] = \CBitrix24::RequestSign(md5(implode("|", $request)));
246 }
247 else
248 {
249 $request['BX_TYPE'] = ModuleManager::isModuleInstalled('intranet') ? 'CP' : 'BSM';
250 $request['BX_LICENCE'] = md5("BITRIX".$licenseKey."LICENCE");
251 $request['BX_HASH'] = md5(md5(implode("|", $request)).md5($licenseKey));
252 }
253
254 return $request;
255 }
256
262 protected static function setAccessSettings(array $params)
263 {
264 Option::set('sale', static::SERVICE_ACCESS_OPTION, serialize($params));
265 }
266
271 protected function getAccessSettings()
272 {
273 $accessSettings = Option::get('sale', static::SERVICE_ACCESS_OPTION);
274
275 if($accessSettings != '')
276 {
277 $accessSettings = unserialize($accessSettings, ['allowed_classes' => false]);
278
280 return $accessSettings;
281 else
282 $this->clearAccessSettings();
283 }
284
286 $result = $this->register();
287
288 if($result->isSuccess())
289 {
290 $accessSettings = $result->getData();
292 return $accessSettings;
293 }
294 else
295 {
296 return array();
297 }
298 }
299
304 public function clearAccessSettings()
305 {
306 Option::set('sale', static::SERVICE_ACCESS_OPTION, null);
307 }
308
313 protected static function getRedirectUri()
314 {
315 $request = Context::getCurrent()->getRequest();
316
317 $host = $request->getHttpHost();
318 $isHttps = $request->isHttps();
319
320 return ($isHttps ? 'https' : 'http').'://'.$host."/";
321 }
322
327 protected static function getLicenseHash()
328 {
329 return md5(static::getLicense());
330 }
331
332 protected static function getLicense()
333 {
334 return LICENSE_KEY;
335 }
336
337 protected static function getLastUnSuccessCallInfo()
338 {
339 $result = Option::get('sale', static::UNSUCCESSFUL_CALL_OPTION, "");
340
341 if($result <> '')
342 $result = unserialize($result, ['allowed_classes' => false]);
343
344 return is_array($result) ? $result : array();
345 }
346
350 protected static function setLastUnSuccessCallInfo($reset = false)
351 {
352 static $alreadySetted = false;
353
354 if($alreadySetted && !$reset)
355 return;
356
357 $data = "";
358
359 if (!$reset)
360 {
361 $alreadySetted = true;
362 $last = static::getLastUnSuccessCallInfo();
363
364 $lastCount = (int)($last['COUNT'] ?? 0);
365
366 $data = serialize([
367 'COUNT' => $lastCount > 0 ? $lastCount + 1 : 1,
368 'TIMESTAMP' => time()
369 ]);
370 }
371
372 Option::set('sale', static::UNSUCCESSFUL_CALL_OPTION, $data);
373 }
374
375
380 public static function isServerAlive()
381 {
382 $last = static::getLastUnSuccessCallInfo();
383
384 if(empty($last))
385 return true;
386
387 if(time() - intval($last['TIMESTAMP']) >= self::UNSUCCESSFUL_CALL_WAIT_INTERVAL)
388 return true;
389
390 if(intval($last['COUNT']) <= self::UNSUCCESSFUL_CALL_TRYINGS)
391 return true;
392
393 return false;
394 }
395
399 protected function getLastUnSuccessCount()
400 {
401 $last = static::getLastUnSuccessCallInfo();
402 $count = (int)($last['COUNT'] ?? 0);
403
404 return max(0, $count);
405 }
406}
$count
Определения admin_tab.php:4
if(!Loader::includeModule('catalog')) if(!AccessController::getCurrent() ->check(ActionDictionary::ACTION_PRICE_EDIT)) if(!check_bitrix_sessid()) $request
Определения catalog_reindex.php:36
Определения error.php:15
static signLicenseRequest(array $request, $licenseKey)
Определения restclient.php:239
static setLastUnSuccessCallInfo($reset=false)
Определения restclient.php:350
const UNSUCCESSFUL_CALL_OPTION
Определения restclient.php:32
const SERVICE_ACCESS_OPTION
Определения restclient.php:25
static setAccessSettings(array $params)
Определения restclient.php:262
static getLicenseHash()
Определения restclient.php:327
const UNSUCCESSFUL_CALL_TRYINGS
Определения restclient.php:33
const ERROR_SERVICE_UNAVAILABLE
Определения restclient.php:29
static getLastUnSuccessCallInfo()
Определения restclient.php:337
static getRedirectUri()
Определения restclient.php:313
call($methodName, $additionalParams=null, $licenseCheck=false, $clearAccessSettings=false)
Определения restclient.php:52
const UNSUCCESSFUL_CALL_WAIT_INTERVAL
Определения restclient.php:34
$data['IS_AVAILABLE']
Определения .description.php:13
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
const LICENSE_KEY($show_sql_stat=='Y')
Определения start.php:84
$host
Определения mysql_to_pgsql.php:32
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799