1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
api.php
См. документацию.
1<?php
2
3namespace Sale\Handlers\Delivery\YandexTaxi\Api;
4
5use Bitrix\Main\Localization\Loc;
6use Bitrix\Main\Result;
7use Bitrix\Main\Error;
8use Bitrix\Main\Web\HttpClient;
9use Sale\Handlers\Delivery\YandexTaxi\Api\ApiResult\CancelInfoResult;
10use Sale\Handlers\Delivery\YandexTaxi\Api\ApiResult\Journal\EventBuilder;
11use Sale\Handlers\Delivery\YandexTaxi\Api\ApiResult\PhoneResult;
12use Sale\Handlers\Delivery\YandexTaxi\Api\ApiResult\PriceResult;
13use Sale\Handlers\Delivery\YandexTaxi\Api\ApiResult\SingleClaimResult;
14use Sale\Handlers\Delivery\YandexTaxi\Api\ApiResult\Tariff;
15use Sale\Handlers\Delivery\YandexTaxi\Api\ApiResult\TariffsResult;
16use Sale\Handlers\Delivery\YandexTaxi\Api\ClaimReader\ClaimReader;
17use Sale\Handlers\Delivery\YandexTaxi\Api\RequestEntity\Claim;
18use Sale\Handlers\Delivery\YandexTaxi\Api\RequestEntity\Estimation;
19use Sale\Handlers\Delivery\YandexTaxi\Api\RequestEntity\OfferEstimation;
20use Sale\Handlers\Delivery\YandexTaxi\Api\RequestEntity\TariffsOptions;
21use Sale\Handlers\Delivery\YandexTaxi\Api\Transport;
22use Sale\Handlers\Delivery\YandexTaxi\Common\Logger;
23
29final class Api
30{
31 private const SINGLE_POINT_API_VERSION = 1;
32 private const MULTI_POINT_API_VERSION = 2;
33
34 private const LOG_SOURCE = 'api';
35
37 private $transport;
38
40 private $claimReader;
41
43 private $eventBuilder;
44
46 private $logger;
47
55 public function __construct(
56 Transport\Client $transport,
57 ClaimReader $claimReader,
58 EventBuilder $eventBuilder,
59 Logger $logger
60 )
61 {
62 $this->transport = $transport;
63 $this->claimReader = $claimReader;
64 $this->eventBuilder = $eventBuilder;
65 $this->logger = $logger;
66 }
67
72 public function checkPrice(Estimation $estimation): PriceResult
73 {
74 $result = new PriceResult();
75
76 try
77 {
78 $response = $this->transport->request(
79 self::SINGLE_POINT_API_VERSION,
80 HttpClient::HTTP_POST,
81 'check-price',
82 null,
83 $estimation
84 );
85 }
86 catch (Transport\Exception $requestException)
87 {
88 return $this->respondTransportError($result);
89 }
90
91 $statusCode = $response->getStatus();
92 $body = $response->getBody();
93
94 if ($statusCode !== 200)
95 {
96 $this->logger->log(static::LOG_SOURCE, 'check_price', $response->toString());
97 return $this->respondStatusError($result, $statusCode, 'check_price');
98 }
99
100 if (
101 !isset($body['price'])
102 || !isset($body['currency_rules']['code'])
103 || (float)$body['price'] <= 0
104 )
105 {
106 return $result->addError(new Error(Loc::getMessage('SALE_YANDEX_TAXI_RATE_CALCULATE_ERROR')));
107 }
108
109 $result
110 ->setPrice((float)$body['price'])
111 ->setCurrency((string)$body['currency_rules']['code'])
112 ;
113
114 if (isset($body['eta']))
115 {
116 $result->setEta((int)$body['eta']);
117 }
118
119 return $result;
120 }
121
126 public function offersCalculate(OfferEstimation $estimation): Result
127 {
128 $result = new PriceResult();
129
130 try
131 {
132 $response = $this->transport->request(
133 self::MULTI_POINT_API_VERSION,
134 HttpClient::HTTP_POST,
135 'offers/calculate',
136 null,
137 $estimation
138 );
139 }
140 catch (Transport\Exception $requestException)
141 {
142 return $this->respondTransportError($result);
143 }
144
145 $statusCode = $response->getStatus();
146 $body = $response->getBody();
147
148 if ($statusCode !== 200)
149 {
150 $this->logger->log(static::LOG_SOURCE, 'offers/calculate', $response->toString());
151 return $this->respondStatusError($result, $statusCode, 'offers/calculate');
152 }
153
154 if (
155 !isset($body['offers'])
156 || !is_array($body['offers'])
157 )
158 {
159 return $result->addError(new Error(Loc::getMessage('SALE_YANDEX_TAXI_RATE_CALCULATE_ERROR')));
160 }
161
162 $maxOfferByPrice = null;
163
164 foreach ($body['offers'] as $offer)
165 {
166 if (
167 !isset($offer['price']['total_price_with_vat'])
168 || !isset($offer['price']['currency'])
169 || !isset($offer['payload'])
170 || (float)$offer['price']['total_price_with_vat'] < 0
171 )
172 {
173 continue;
174 }
175
176 if (is_null($maxOfferByPrice))
177 {
178 $maxOfferByPrice = $offer;
179
180 continue;
181 }
182
183 if ((float)$offer['price']['total_price_with_vat'] > (float)$maxOfferByPrice['price']['total_price_with_vat'])
184 {
185 $maxOfferByPrice = $offer;
186 }
187 }
188
189 if (is_null($maxOfferByPrice))
190 {
191 return $result->addError(new Error(Loc::getMessage('SALE_YANDEX_TAXI_RATE_CALCULATE_ERROR')));
192 }
193
194 $result
195 ->setPrice((float)$maxOfferByPrice['price']['total_price_with_vat'])
196 ->setCurrency((string)$maxOfferByPrice['price']['currency'])
197 ->setData(['offerPayload' => (string)$maxOfferByPrice['payload']])
198 ;
199
200 return $result;
201 }
202
207 public function getTariffs(TariffsOptions $tariffsOptions): TariffsResult
208 {
209 $result = new TariffsResult();
210
211 try
212 {
213 $response = $this->transport->request(
214 self::SINGLE_POINT_API_VERSION,
215 HttpClient::HTTP_POST,
216 'tariffs',
217 null,
218 $tariffsOptions
219 );
220 }
221 catch (Transport\Exception $requestException)
222 {
223 return $this->respondTransportError($result);
224 }
225
226 $statusCode = $response->getStatus();
227 $body = $response->getBody();
228
229 if ($statusCode !== 200)
230 {
231 $this->logger->log(static::LOG_SOURCE, 'tariffs', $response->toString());
232 return $this->respondStatusError($result, $statusCode, 'tariffs');
233 }
234
235 if (isset($body['available_tariffs']) && is_array($body['available_tariffs']))
236 {
237 foreach ($body['available_tariffs'] as $tariff)
238 {
239 if (!isset($tariff['name']))
240 {
241 continue;
242 }
243
244 $tariffObject = new Tariff($tariff['name']);
245
246 if (isset($tariff['supported_requirements']) && is_array($tariff['supported_requirements']))
247 {
248 foreach ($tariff['supported_requirements'] as $supportedRequirement)
249 {
250 if (!isset($supportedRequirement['name']))
251 {
252 continue;
253 }
254
255 if ($supportedRequirement['name'] === 'cargo_options')
256 {
257 if (isset($supportedRequirement['options']) && is_array($supportedRequirement['options']))
258 {
259 foreach ($supportedRequirement['options'] as $option)
260 {
261 if (isset($option['value']) && !empty($option['value']))
262 {
263 $tariffObject->addSupportedRequirement($option['value']);
264 }
265 }
266 }
267 }
268 else
269 {
270 $tariffObject->addSupportedRequirement($supportedRequirement['name']);
271 }
272 }
273 }
274
275 $result->addTariff($tariffObject);
276 }
277 }
278
279 return $result;
280 }
281
286 public function createClaim(Claim $claim): SingleClaimResult
287 {
288 $result = new SingleClaimResult();
289
290 try
291 {
292 $response = $this->transport->request(
293 self::MULTI_POINT_API_VERSION,
294 HttpClient::HTTP_POST,
295 'claims/create',
296 ['request_id' => uniqid('', true)],
297 $claim
298 );
299 }
300 catch (Transport\Exception $requestException)
301 {
302 return $this->respondTransportError($result);
303 }
304
305 $statusCode = $response->getStatus();
306 $body = $response->getBody();
307
308 if ($statusCode !== 200)
309 {
310 $this->logger->log(static::LOG_SOURCE, 'create_claim', $response->toString());
311 return $this->respondStatusError($result, $statusCode, 'create');
312 }
313
314 $claimReadResult = $this->claimReader->readFromArray($body);
315 if ($claimReadResult->isSuccess())
316 {
317 return $result->setClaim($claimReadResult->getClaim());
318 }
319
320 return $result;
321 }
322
328 public function acceptClaim(string $claimId, int $version): Result
329 {
330 $result = new Result();
331
332 try
333 {
334 $response = $this->transport->request(
335 self::SINGLE_POINT_API_VERSION,
336 HttpClient::HTTP_POST,
337 'claims/accept',
338 ['claim_id' => $claimId],
339 ['version' => $version]
340 );
341 }
342 catch (Transport\Exception $requestException)
343 {
344 return $this->respondTransportError($result);
345 }
346
347 $statusCode = $response->getStatus();
348
349 if ($statusCode !== 200)
350 {
351 $this->logger->log(static::LOG_SOURCE, 'accept_claim', $response->toString());
352 return $this->respondStatusError($result, $statusCode, 'accept');
353 }
354
355 return $result;
356 }
357
364 public function cancelClaim(string $claimId, int $version, string $cancelState): Result
365 {
366 $result = new Result();
367
368 try
369 {
370 $response = $this->transport->request(
371 self::SINGLE_POINT_API_VERSION,
372 HttpClient::HTTP_POST,
373 'claims/cancel',
374 ['claim_id' => $claimId],
375 [
376 'version' => $version,
377 'cancel_state' => $cancelState,
378 ]
379 );
380 }
381 catch (Transport\Exception $requestException)
382 {
383 return $this->respondTransportError($result);
384 }
385
386 $statusCode = $response->getStatus();
387
388 if ($statusCode !== 200)
389 {
390 $this->logger->log(static::LOG_SOURCE, 'cancel_claim', $response->toString());
391 return $this->respondStatusError($result, $statusCode, 'cancel');
392 }
393
394 return $result;
395 }
396
401 public function getCancelInfo(string $claimId): CancelInfoResult
402 {
403 $result = new CancelInfoResult();
404
405 try
406 {
407 $response = $this->transport->request(
408 self::MULTI_POINT_API_VERSION,
409 HttpClient::HTTP_POST,
410 'claims/cancel-info',
411 ['claim_id' => $claimId]
412 );
413 }
414 catch (Transport\Exception $requestException)
415 {
416 return $this->respondTransportError($result);
417 }
418
419 $statusCode = $response->getStatus();
420 $body = $response->getBody();
421
422 if ($statusCode !== 200)
423 {
424 $this->logger->log(static::LOG_SOURCE, 'cancel_info', $response->toString());
425 return $this->respondStatusError($result, $statusCode, 'cancel_info');
426 }
427
428 if (empty($body['cancel_state']))
429 {
430 return $result->addError(new Error(Loc::getMessage('SALE_YANDEX_TAXI_CANCELLATION_FATAL_ERROR')));
431 }
432
433 return $result->setCancelState($body['cancel_state']);
434 }
435
440 public function getClaim(string $claimId): SingleClaimResult
441 {
442 $result = new SingleClaimResult();
443
444 try
445 {
446 $response = $this->transport->request(
447 self::MULTI_POINT_API_VERSION,
448 HttpClient::HTTP_POST,
449 'claims/info',
450 ['claim_id' => $claimId]
451 );
452 }
453 catch (Transport\Exception $requestException)
454 {
455 return $this->respondTransportError($result);
456 }
457
458 $statusCode = $response->getStatus();
459 $body = $response->getBody();
460
461 if ($statusCode !== 200)
462 {
463 $this->logger->log(static::LOG_SOURCE, 'get_claim', $response->toString());
464 return $this->respondStatusError($result, $statusCode, 'info');
465 }
466
467 $claimReadResult = $this->claimReader->readFromArray($body);
468 if ($claimReadResult->isSuccess())
469 {
470 return $result->setClaim($claimReadResult->getClaim());
471 }
472
473 return $result;
474 }
475
480 public function getPhone(string $claimId): PhoneResult
481 {
482 $result = new PhoneResult();
483
484 try
485 {
486 $response = $this->transport->request(
487 self::MULTI_POINT_API_VERSION,
488 HttpClient::HTTP_POST,
489 'driver-voiceforwarding',
490 null,
491 ['claim_id' => $claimId]
492 );
493 }
494 catch (Transport\Exception $requestException)
495 {
496 return $this->respondTransportError($result);
497 }
498
499 $statusCode = $response->getStatus();
500 $body = $response->getBody();
501
502 if ($statusCode !== 200)
503 {
504 $this->logger->log(static::LOG_SOURCE, 'get_phone', $response->toString());
505 return $this->respondStatusError($result, $statusCode, 'driver-voiceforwarding');
506 }
507
508 if (isset($body['phone']))
509 {
510 $result->setPhone($body['phone']);
511 }
512 if (isset($body['ext']))
513 {
514 $result->setExt($body['ext']);
515 }
516 if (isset($body['ttl_seconds']))
517 {
518 $result->setTtlSeconds($body['ttl_seconds']);
519 }
520
521 return $result;
522 }
523
528 public function getJournalRecords($cursor): ApiResult\Journal\Result
529 {
530 $result = new ApiResult\Journal\Result();
531
532 try
533 {
534 $response = $this->transport->request(
535 self::MULTI_POINT_API_VERSION,
536 HttpClient::HTTP_POST,
537 'claims/journal',
538 null,
539 is_null($cursor) ? new \stdClass() : ['cursor' => $cursor]
540 );
541 }
542 catch (Transport\Exception $requestException)
543 {
544 return $this->respondTransportError($result);
545 }
546
547 $statusCode = $response->getStatus();
548 $body = $response->getBody();
549
550 if ($statusCode !== 200)
551 {
552 $this->logger->log(static::LOG_SOURCE, 'get_journal_records_1', $response->toString());
553 return $this->respondStatusError($result, $statusCode, 'journal');
554 }
555
556 if (!is_array($body) || !isset($body['cursor']) || !isset($body['events']))
557 {
558 $this->logger->log(static::LOG_SOURCE, 'get_journal_records_2', $response->toString());
559
560 return $result->addError(new Error(Loc::getMessage('SALE_YANDEX_TAXI_NETWORK_ERROR_UNEXPECTED_ERROR')));
561 }
562
563 $result->setCursor($body['cursor']);
564
565 if (is_array($body['events']))
566 {
567 foreach ($body['events'] as $event)
568 {
569 $event = $this->eventBuilder->build($event);
570 if (is_null($event))
571 {
572 continue;
573 }
574
575 $result->addEvent($event);
576 }
577 }
578
579 return $result;
580 }
581
588 private function respondStatusError($result, int $statusCode, string $method)
589 {
590 $error = Loc::getMessage('SALE_YANDEX_TAXI_NETWORK_ERROR_UNEXPECTED_ERROR');
591
592 if ($statusCode == 401)
593 {
594 $error = Loc::getMessage('SALE_YANDEX_TAXI_AUTHENTICATION_ERROR');
595 }
596 elseif ($statusCode == 404)
597 {
598 $error = Loc::getMessage('SALE_YANDEX_TAXI_ORDER_NOT_FOUND_ERROR');
599 }
600 elseif ($statusCode == 409)
601 {
602 $error = Loc::getMessage('SALE_YANDEX_TAXI_OPERATION_REJECTED');
603 }
604
605 return $result->addError(new Error($error));
606 }
607
612 private function respondTransportError($result)
613 {
614 return $result->addError(new Error(Loc::getMessage('SALE_YANDEX_TAXI_NETWORK_ERROR')));
615 }
616
620 public function getTransport(): Transport\Client
621 {
622 return $this->transport;
623 }
624}
$result
Определения get_property_values.php:14
trait Error
Определения error.php:11
$event
Определения prolog_after.php:141
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$option
Определения options.php:1711
$response
Определения result.php:21
$method
Определения index.php:27
$error
Определения subscription_card_product.php:20