forked from nikserg/crm-certificate-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.php
638 lines (602 loc) · 22 KB
/
Client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<?php
namespace nikserg\CRMCertificateAPI;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use nikserg\CRMCertificateAPI\exceptions\BooleanResponseException;
use nikserg\CRMCertificateAPI\exceptions\InvalidRequestException;
use nikserg\CRMCertificateAPI\exceptions\NotFoundException;
use nikserg\CRMCertificateAPI\exceptions\ServerException;
use nikserg\CRMCertificateAPI\exceptions\TransportException;
use nikserg\CRMCertificateAPI\models\request\ChangeStatus;
use nikserg\CRMCertificateAPI\models\request\CheckSnils;
use nikserg\CRMCertificateAPI\models\request\Egrul as EgrulRequest;
use nikserg\CRMCertificateAPI\models\request\CheckPassport;
use nikserg\CRMCertificateAPI\models\request\CustomerFormDocuments;
use nikserg\CRMCertificateAPI\models\request\DetectPlatforms as DetectPlatformsRequest;
use nikserg\CRMCertificateAPI\models\request\PartnerFullPrice as PartnerFullPriceRequest;
use nikserg\CRMCertificateAPI\models\request\PartnerPlatforms as PartnerPlatformsRequest;
use nikserg\CRMCertificateAPI\models\request\PartnerProducts as PartnerProductsRequest;
use nikserg\CRMCertificateAPI\models\request\PartnerStores as PartnerStoresRequest;
use nikserg\CRMCertificateAPI\models\request\SendCheckRef;
use nikserg\CRMCertificateAPI\models\request\SendCustomerForm as SendCustomerFormRequest;
use nikserg\CRMCertificateAPI\models\request\SendCustomerFormData;
use nikserg\CRMCertificateAPI\models\response\BooleanResponse;
use nikserg\CRMCertificateAPI\models\response\Esia\Egrul as EgrulResponse;
use nikserg\CRMCertificateAPI\models\response\GetCustomerForm;
use nikserg\CRMCertificateAPI\models\response\GetOpportunity;
use nikserg\CRMCertificateAPI\models\response\models\Store;
use nikserg\CRMCertificateAPI\models\response\PassportCheck;
use nikserg\CRMCertificateAPI\models\response\SnilsCheck;
use nikserg\CRMCertificateAPI\models\response\models\DetectPlatformVariantPlatform;
use nikserg\CRMCertificateAPI\models\response\models\PartnerPlatform;
use nikserg\CRMCertificateAPI\models\response\models\PartnerProduct;
use nikserg\CRMCertificateAPI\models\response\DetectPlatformVariant;
use nikserg\CRMCertificateAPI\models\response\ReferralUser;
use nikserg\CRMCertificateAPI\models\response\SendCustomerForm as SendCustomerFormResponse;
use Psr\Http\Message\ResponseInterface;
/**
* Клиент для связи с CRM
*
* @package nikserg\CRMCertificateAPI
*/
class Client
{
/**
* @var string
*/
protected $apiKey;
/**
* @var string
*/
protected $url;
/**
* @var \GuzzleHttp\Client
*/
protected $guzzle;
/**
* @param string $apiKey
* @param string $url
*/
public function __construct($apiKey, $url = 'https://crm.uc-itcom.ru/index.php')
{
$this->apiKey = $apiKey;
$this->url = trim($url, " /");
$this->guzzle = new \GuzzleHttp\Client([
RequestOptions::VERIFY => false,
RequestOptions::HTTP_ERRORS => false,
]);
}
/**
* @param $method
* @param $endpoint
* @param array $options
* @return ResponseInterface
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
* @throws InvalidRequestException
*/
protected function request($method, $endpoint, $options = [])
{
$options[RequestOptions::QUERY]['key'] = $this->apiKey;
try {
$response = $this->guzzle->request($method, "$this->url/gateway/itkExchange/$endpoint", $options);
} catch (GuzzleException $e) {
throw new TransportException("Ошибка запроса; {$e->getMessage()}");
}
switch ($response->getStatusCode()) {
case 200:
case 204:
return $response;
case 400:
throw new InvalidRequestException("$endpoint: Неверный формат запроса");
case 404:
throw new NotFoundException("$endpoint: Сущность или точка АПИ не найдены");
case 500:
throw new ServerException("$endpoint: Ошибка сервера \n" . $response->getBody()->getContents());
default:
throw new TransportException("$endpoint: Неожиданный код ответа {$response->getStatusCode()}");
}
}
/**
* @param $method
* @param $endpoint
* @param $data
* @param array $options
* @return mixed
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
* @throws InvalidRequestException
*/
protected function requestJson($method, $endpoint, $data, $options = [])
{
$options[RequestOptions::QUERY]['key'] = $this->apiKey;
$options[RequestOptions::JSON] = $data;
try {
$response = $this->guzzle->request($method, "$this->url/gateway/itkExchange/$endpoint", $options);
} catch (GuzzleException $e) {
throw new TransportException("Ошибка запроса; {$e->getMessage()}");
}
try {
$data = $this->getJsonBody($response);
switch ($response->getStatusCode()) {
case 200:
return $data;
case 400:
throw new InvalidRequestException("$endpoint: " . $data->error->message ?? $data->message ?? "Неверный формат запроса");
case 404:
throw new NotFoundException("$endpoint: " . $data->error->message ?? $data->message ?? "Сущность или точка АПИ не найдены");
case 500:
throw new ServerException("$endpoint: " . $data->error->message ?? $data->message ?? "Неожиданная ошибка сервера");
default:
throw new TransportException("$endpoint: " . $data->error->message ?? $data->message ?? "Неожиданный код ответа {$response->getStatusCode()}");
}
} catch (TransportException $e) {
throw new TransportException('Ошибка во время отправки запроса ' . print_r([
$method,
$this->url . $endpoint,
$options,
$data,
], true) . ': ' . $e->getMessage(), $e->getCode(), $e);
}
}
/**
* @param ResponseInterface $response
* @return mixed
* @throws TransportException
*/
private function getJsonBody(ResponseInterface $response)
{
$body = $response->getBody();
if (strlen($body) === 0) {
throw new TransportException('Пустое тело ответа на JSON запрос. Код ответа ' . $response->getStatusCode());
}
$json = json_decode($body);
$jsonErrorCode = json_last_error();
$jsonErrorMessage = json_last_error_msg();
if ($jsonErrorCode !== JSON_ERROR_NONE) {
throw new TransportException("$jsonErrorMessage: $body", $jsonErrorCode);
}
return $json;
}
/**
* Отправить запрос на создание заявки на сертификат
*
* @param SendCustomerFormRequest $customerForm
* @return SendCustomerFormResponse
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function sendCustomerForm(SendCustomerFormRequest $customerForm)
{
$result = $this->requestJson('POST', 'pushCustomerForm', $customerForm);
return $this->fill(SendCustomerFormResponse::class, $result);
}
/**
* Получить информацию о заявке на сертификат
*
* @param int $customerFormCrmId
* @return GetCustomerForm
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getCustomerForm($customerFormCrmId)
{
$result = $this->getJsonBody($this->request('GET', 'pullCustomerForm', [
RequestOptions::QUERY => [
'id' => $customerFormCrmId,
],
]));
return $this->fill(GetCustomerForm::class, $result);
}
/**
* Получить информацию о сделки
*
* @param $opportunityCrmId
* @return GetOpportunity
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getOpportunity($opportunityCrmId)
{
$result = $this->getJsonBody($this->request('GET', 'pullOpportunity', [
RequestOptions::QUERY => [
'id' => $opportunityCrmId,
],
]));
return $this->fill(GetOpportunity::class, $result);
}
/**
* Изменить статус заявки
*
* @param ChangeStatus $changeStatus
* @return BooleanResponse
* @throws BooleanResponseException
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function changeStatus(ChangeStatus $changeStatus)
{
$result = $this->requestJson('POST', 'pushCustomerFormStatus', $changeStatus);
$response = new BooleanResponse();
$response->status = $result->status;
$response->message = $result->message ?? null;
if (!$response->status) {
throw new BooleanResponseException('Ошибка при обновлении статуса в CRM ' . print_r($response, true));
}
return $response;
}
/**
* Удалить заявку на сертификат
*
* @param int $customerFormCrmId
* @return BooleanResponse
* @throws BooleanResponseException
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function deleteCustomerForm($customerFormCrmId)
{
$result = $this->getJsonBody($this->request('GET', 'deleteCustomerForm', [
RequestOptions::QUERY => [
'id' => $customerFormCrmId,
],
]));
$response = new BooleanResponse();
$response->status = $result->status;
$response->message = $result->message ?? null;
if (!$response->status) {
throw new BooleanResponseException('Ошибка при удалении заявки в CRM ' . print_r($response, true));
}
return $response;
}
/**
* Получить заявление на выпуск сертификата
*
* @param int $customerFormCrmId
* @param string $format
* @return string
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getCustomerFormClaim($customerFormCrmId, $format = 'pdf')
{
$result = $this->request('GET', 'union', [
RequestOptions::QUERY => [
'id' => $customerFormCrmId,
'format' => $format,
],
]);
return $result->getBody()->getContents();
}
/**
* Получить заявление на выпуск сертификата
*
* @param int $customerFormCrmId
* @param string $format
* @return string
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getCustomerFormCertificateBlank($customerFormCrmId, $format = 'pdf')
{
$result = $this->request('GET', 'certificateBlank', [
RequestOptions::QUERY => [
'id' => $customerFormCrmId,
'format' => $format,
],
]);
return $result->getBody()->getContents();
}
/**
* Выписка ЕГРЮЛ
*
* @param EgrulRequest $request
* @return EgrulResponse
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function egrul(EgrulRequest $request)
{
return new EgrulResponse($this->requestJson('GET', 'egrul', $request));
}
/**
* Отправить данные бланка заявки на сертификат
*
* @param int $crmCustomerFormId
* @param SendCustomerFormData $customerFormData
* @return SendCustomerFormResponse
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function sendCustomerFormData($crmCustomerFormId, SendCustomerFormData $customerFormData)
{
$result = $this->requestJson('POST', 'pushCustomerFormData', [
'id' => $crmCustomerFormId,
'formData' => $customerFormData,
]);
return $this->fill(SendCustomerFormResponse::class, $result);
}
/**
* Расширенная проверка паспортных данных
*
* @param CheckPassport $request
* @return PassportCheck
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function checkPassport(CheckPassport $request)
{
$result = $this->requestJson('GET', 'checkPassport', $request);
return $this->fill(PassportCheck::class, $result);
}
/**
* Проверка СНИЛС данных
*
* @param CheckSnils $request
* @return SnilsCheck
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function checkSnils(CheckSnils $request)
{
$result = $this->requestJson('GET', 'checkSnils', $request);
return $this->fill(SnilsCheck::class, $result);
}
/**
* Получение информации о реферальном пользователе
*
* @param SendCheckRef $sendCheckRef
* @return ReferralUser|null - null если реферальный пользователь не найден
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getReferralUser(SendCheckRef $sendCheckRef)
{
$result = $this->requestJson('POST', 'getRefUserInfo', $sendCheckRef);
if ($result === null) {
return null;
}
return $this->fill(ReferralUser::class, $result);
}
/**
* Определить варианты площадок для переданного списка ОИДов
*
* @param DetectPlatformsRequest $request
* @return DetectPlatformVariant[]
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function detectPlatforms(DetectPlatformsRequest $request)
{
$result = $this->requestJson('POST', 'detectPlatforms', $request);
if (empty($result->variants)) {
return [];
}
$return = [];
foreach ($result->variants as $variant) {
$variantModel = new DetectPlatformVariant();
$variantModel->platforms = [];
foreach ($variant->platforms as $value => $name) {
$platform = new DetectPlatformVariantPlatform();
$platform->value = $value;
$platform->name = $name;
$variantModel->platforms[] = $platform;
}
$variantModel->price = $variant->price;
$variantModel->excluded = $variant->excluded;
$return[] = $variantModel;
}
return $return;
}
/**
* @param CustomerFormDocuments $documents
* @return bool
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function pushCustomerFormDocuments(CustomerFormDocuments $documents)
{
$multipart = [
[
'name' => 'customerFormId',
'contents' => $documents->customerFormId,
],
];
if ($documents->signedClaim) {
$multipart[] = [
'name' => 'signedClaim',
'filename' => 'claim.pdf.sig',
'contents' => $documents->signedClaim,
];
}
if ($documents->signedBlank) {
$multipart[] = [
'name' => 'signedBlank',
'filename' => 'blank.pdf.sig',
'contents' => $documents->signedBlank,
];
}
$this->request('POST', 'pushCustomerFormDocuments', [
RequestOptions::MULTIPART => $multipart,
]);
return true;
}
/**
* Получает платформы, доступные партнеру переданному в запросе
*
* @param PartnerPlatformsRequest $request
* @return PartnerPlatform[]
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getPartnerPlatformsAll(PartnerPlatformsRequest $request)
{
$result = $this->requestJson('POST', 'getPartnerPlatforms', $request);
return $this->fillList(PartnerPlatform::class, $result->platforms);
}
/**
* Получает продукты, настроенные для партнера переданного в запросе
*
* @param PartnerProductsRequest $request
* @return PartnerProduct[]
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getPartnerProductsAll(PartnerProductsRequest $request)
{
$result = $this->requestJson('POST', 'getPartnerProducts', $request);
return $this->fillList(PartnerProduct::class, $result->products);
}
/**
* Отдает сумму по выбранным продуктам и плаформам для партнера
*
* @param PartnerFullPriceRequest $fullPriceRequest
* @return float
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getPartnerFullPrice(PartnerFullPriceRequest $fullPriceRequest)
{
$result = $this->requestJson('POST', 'getPartnerFullPrice', $fullPriceRequest);
return $result->price;
}
/**
* Отдает список точек/складов/трансферов партнера
*
* @param PartnerStoresRequest $partnerStores
* @return Store[]
* @throws InvalidRequestException
* @throws NotFoundException
* @throws ServerException
* @throws TransportException
*/
public function getPartnerStores(PartnerStoresRequest $partnerStores)
{
$result = $this->requestJson('POST', 'getPartnerStores', $partnerStores);
return $this->fillList(Store::class, $result->stores);
}
public function fill($class, $attributes)
{
$model = new $class;
foreach ($attributes as $attribute => $value) {
$model->$attribute = $value;
}
return $model;
}
public function fillList($class, $list)
{
$models = [];
foreach ($list as $item) {
$models[] = $this->fill($class, $item);
}
return $models;
}
#region urls
/**
* Ссылка для скачивания сертификата
*
* @param $customerFormId
* @param $token
* @return string
*/
public function certificateDownloadUrl($customerFormId, $token)
{
return $this->url . '/customerForms/external/downloadCertificate?token=' . $token . '&customerFormId=' . $customerFormId;
}
/**
* Ссылка для скачивания реализации
*
* @param $customerFormId
* @param $token
* @return string
*/
public function realizationDownloadUrl($customerFormId, $token)
{
return $this->url . '/customerForms/external/downloadFirstRealization?token=' . $token . '&customerFormId=' . $customerFormId;
}
/**
* Индивидуальная ссылка для редактирования
*
* @param $token
* @return string
*/
public function editUrl($token)
{
return $this->url . '/customerForms/external?token=' . $token;
}
/**
* Индивидуальная ссылка для генерации
*
* @param $token
* @param $generatonToken
* @param bool $iframe Выводить отображение для фрейма
* @return string
*/
public function generationUrl($token, $generatonToken, $iframe = false)
{
$return = $this->url . '/customerForms/external/generate?token=' . $token . '&generationToken=' . $generatonToken;
if ($iframe) {
$return .= '&iframe=1';
}
return $return;
}
/**
* Ссылка на фрейм
*
* @param $customerFormId
* @param $token
* @return string
*/
public function customerFormFrameUrl($customerFormId, $token)
{
return $this->url . '/customerForms/external/step1?token=' . $token . '&customerFormId=' . $customerFormId;
}
/**
* Ссылка для записи сертификата на носитель
*
* @param $customerFormId
* @param $token
* @return string
*/
public function certificateWriteUrl($customerFormId, $token)
{
return $this->url . '/customerForms/external/writeCertificate?token=' . $token . '&customerFormId=' . $customerFormId;
}
#endregion urls
}