Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
smsassistentby.php
1<?php
3
12
16
18
19Loc::loadMessages(__FILE__);
20
22{
23 use Sender\Traits\RussianProvider;
24
25 public const ID = 'smsastby';
26
27 const JSON_API_URL = 'https://userarea.sms-assistent.by/api/v1/json';
28 const PLAIN_API_URL = 'https://userarea.sms-assistent.by/api/v1/%s/plain';
29
30 public function getId()
31 {
32 return static::ID;
33 }
34
35 public function getName()
36 {
37 return Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSASTBY_NAME');
38 }
39
40 public function getShortName()
41 {
42 return 'sms-assistent.by';
43 }
44
45 public function getFromList()
46 {
47 $from = $this->getOption('from_list');
48 return is_array($from) ? $from : [];
49 }
50
51 public function isRegistered()
52 {
53 return (
54 $this->getOption('user') !== null
55 &&
56 $this->getOption('password') !== null
57 );
58 }
59
60 public function register(array $fields)
61 {
62 $params = array(
63 'user' => $fields['account_user'],
64 'password' => $fields['account_password'],
65 );
66
67 $result = $this->callPlainApi('credits', $params);
68 if ($result->isSuccess())
69 {
70 $this->disableDemo();
71 $this->setOption('user', $params['user']);
72 $this->setOption('password', $params['password']);
73 }
74
75 return $result;
76 }
77
78 public function registerDemo(array $fields)
79 {
80 $params = [
81 'info' => [
82 'simple' => true,
83 'user_uuid' => 'wsTKC5KdazmEjBNU8i5fqacddtOeqQBtRc45lcvO6WA=',
84 "diler_uuid" => 'obUrbkWuyW0nYL9D2rR6s3EPMm1QHg9h/KWtO8jFIug=',
85 'email' => $fields['email'],
86 'tel' => '+'.\NormalizePhone($fields['tel']),
87 'unp' => $fields['unp']
88 ]
89 ];
90
91 $result = $this->callJsonApi('demo', $params);
92
93 if ($result->isSuccess())
94 {
95 $this->enableDemo();
96 $this->setOption('demo_email', $fields['email']);
97 $this->setOption('demo_tel', '+'.\NormalizePhone($fields['tel']));
98 $this->setOption('demo_unp', $fields['unp']);
99 }
100
101 return $result;
102 }
103
109 public function getOwnerInfo()
110 {
111 return array(
112 'user' => $this->getOption('user'),
113 );
114 }
115
119 public function getDemoInfo()
120 {
121 return array(
122 'email' => $this->getOption('demo_email'),
123 'tel' => $this->getOption('demo_tel'),
124 'unp' => $this->getOption('demo_unp'),
125 );
126 }
127
128 public function getExternalManageUrl()
129 {
130 return 'https://userarea.sms-assistent.by/';
131 }
132
133 public function sendMessage(array $messageFields)
134 {
135 if (!$this->canUse())
136 {
137 $result = new SendMessage();
138 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSASTBY_CAN_USE_ERROR')));
139 return $result;
140 }
141
142 $message = [
143 'recipient' => $messageFields['MESSAGE_TO'],
144 'message' => $this->prepareMessageBodyForSend($messageFields['MESSAGE_BODY']),
145 'validity_period' => 24,
146 'webhook_url' => $this->getCallbackUrl()
147 ];
148
149 if (ModuleManager::isModuleInstalled('bitrix24'))
150 {
151 $message['Vendor'] = 'Bitrix24';
152 }
153
154 if ($messageFields['MESSAGE_FROM'])
155 {
156 $message['sender'] = $messageFields['MESSAGE_FROM'];
157 }
158
159 $result = new SendMessage();
160 $apiResult = $this->callPlainApi('send_sms', $message);
161 $result->setServiceRequest($apiResult->getHttpRequest());
162 $result->setServiceResponse($apiResult->getHttpResponse());
163 $resultData = $apiResult->getData();
164
165 if (!$apiResult->isSuccess())
166 {
167 $result->addErrors($apiResult->getErrors());
168 }
169 else
170 {
171 $smsId = $resultData['response'];
172
173 if ($smsId <= 0)
174 {
175 $result->addError(new Error($this->getErrorMessage(-1000)));
176 }
177 else
178 {
179 $result->setExternalId($smsId);
180 $result->setAccepted();
181 }
182 }
183
184 return $result;
185 }
186
187 /* reserved method */
188 private function sendMessageBulk(array $messageFields)
189 {
190 if (!$this->canUse())
191 {
192 $result = new SendMessage();
193 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSASTBY_CAN_USE_ERROR')));
194 return $result;
195 }
196
197 $message = [
198 'recepient' => $messageFields['MESSAGE_TO'],
199 'sms_text' => $this->prepareMessageBodyForSend($messageFields['MESSAGE_BODY']),
200 ];
201
202 if ($messageFields['MESSAGE_FROM'])
203 {
204 $message['sender'] = $messageFields['MESSAGE_FROM'];
205 }
206
207 $result = new SendMessage();
208 $apiResult = $this->callJsonApi('sms_send', [
209 'message' => [
210 'default' => [
211 'validity_period' => 24
212 ],
213 'msg' => [
214 $message
215 ]
216 ]
217 ]);
218 $resultData = $apiResult->getData();
219
220 if (!$apiResult->isSuccess())
221 {
222 $result->addErrors($apiResult->getErrors());
223 }
224 else
225 {
226 $smsData = current($resultData['message']['msg']);
227
228 if (!$smsData)
229 {
230 $result->addError(new Error($this->getErrorMessage(-1000)));
231 }
232 else
233 {
234 if (isset($smsData['sms_id']))
235 {
236 $result->setExternalId($smsData['sms_id']);
237 }
238
239 if ($smsData['error_code'] > 0)
240 {
241 $result->addError(new Error($this->getErrorMessage($smsData['error_code'])));
242 }
243 else
244 {
245 $result->setAccepted();
246 }
247 }
248 }
249
250 return $result;
251 }
252
253 public function getMessageStatus(array $messageFields)
254 {
255 $result = new MessageStatus();
256 $result->setId($messageFields['ID']);
257 $result->setExternalId($messageFields['EXTERNAL_ID']);
258
259 if (!$this->canUse())
260 {
261 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSASTBY_CAN_USE_ERROR')));
262 return $result;
263 }
264
265 $params = array(
266 'status' => [
267 'msg' => [
268 [
269 'sms_id' => $result->getExternalId()
270 ]
271 ]
272 ]
273 );
274
275 $apiResult = $this->callJsonApi('statuses', $params);
276 if (!$apiResult->isSuccess())
277 {
278 $result->addErrors($apiResult->getErrors());
279 }
280 else
281 {
282 $resultData = $apiResult->getData();
283 $smsData = current($resultData['status']['msg']);
284
285 if (!$smsData)
286 {
287 $result->addError(new Error($this->getErrorMessage(-1000)));
288 }
289
290 $result->setStatusText($smsData['sms_status']);
291 $result->setStatusCode(self::resolveStatus($smsData['sms_status']));
292 }
293
294 return $result;
295 }
296
297 public static function resolveStatus($serviceStatus)
298 {
299 $status = parent::resolveStatus($serviceStatus);
300
301 switch ($serviceStatus)
302 {
303 case 'Queued':
304 return MessageService\MessageStatus::ACCEPTED;
305 break;
306 case 'Sent':
307 return MessageService\MessageStatus::SENT;
308 break;
309 case 'Delivered':
310 return MessageService\MessageStatus::DELIVERED;
311 break;
312 case 'Expired':
313 case 'Rejected':
314 case 'Unknown':
315 case 'Failed':
316 return MessageService\MessageStatus::UNDELIVERED;
317 break;
318 }
319
320 return $status;
321 }
322
323 public function sync()
324 {
325 if ($this->isRegistered())
326 {
327 $this->loadFromList();
328 }
329 return $this;
330 }
331
332 private function callPlainApi($command, array $params = []): Sender\Result\HttpRequestResult
333 {
334 $url = sprintf(self::PLAIN_API_URL, $command);
335
336 $httpClient = new HttpClient(array(
337 "socketTimeout" => $this->socketTimeout,
338 "streamTimeout" => $this->streamTimeout,
339 "waitResponse" => true,
340 ));
341 $httpClient->setHeader('User-Agent', 'Bitrix24');
342 $httpClient->setCharset('UTF-8');
343
344 $isUtf = Application::getInstance()->isUtfMode();
345
346 if (!isset($params['user']))
347 {
348 $params['user'] = $this->getOption('user');
349 }
350
351 if (!isset($params['password']))
352 {
353 $params['password'] = $this->getOption('password');
354 }
355
356 if (!$isUtf)
357 {
358 $params = \Bitrix\Main\Text\Encoding::convertEncoding($params, SITE_CHARSET, 'UTF-8');
359 }
360
361 $result = new Sender\Result\HttpRequestResult();
362 $result->setHttpRequest(new MessageService\DTO\Request([
363 'method' => HttpClient::HTTP_POST,
364 'uri' => $url,
365 'headers' => method_exists($httpClient, 'getRequestHeaders') ? $httpClient->getRequestHeaders()->toArray() : [],
366 'body' => $params,
367 ]));
368 $answer = [];
369
370 if ($httpClient->query(HttpClient::HTTP_POST, $url, $params) && $httpClient->getStatus() == '200')
371 {
372 $answer = $httpClient->getResult();
373 }
374
375 if (is_numeric($answer) && $answer < 0)
376 {
377 $result->addError(new Error($this->getErrorMessage($answer)));
378 }
379 $result->setHttpResponse(new MessageService\DTO\Response([
380 'statusCode' => $httpClient->getStatus(),
381 'headers' => $httpClient->getHeaders()->toArray(),
382 'body' => $httpClient->getResult(),
383 'error' => Sender\Util::getHttpClientErrorString($httpClient)
384 ]));
385
386 $result->setData(['response' => $answer]);
387
388 return $result;
389 }
390
391 private function callJsonApi($command, array $params = []): Sender\Result\HttpRequestResult
392 {
393 $httpClient = new HttpClient(array(
394 "socketTimeout" => $this->socketTimeout,
395 "streamTimeout" => $this->streamTimeout,
396 "waitResponse" => true,
397 ));
398 $httpClient->setHeader('User-Agent', 'Bitrix24');
399 $httpClient->setCharset('UTF-8');
400 $httpClient->setHeader('Content-Type', 'application/json');
401
402 if (!isset($params['login']) && $this->isRegistered())
403 {
404 $params['login'] = $this->getOption('user');
405 }
406
407 if (!isset($params['password']) && $this->isRegistered())
408 {
409 $params['password'] = $this->getOption('password');
410 }
411
412 $params['command'] = $command;
413
414 $params = Json::encode($params);
415
416 $result = new Sender\Result\HttpRequestResult();
417 $result->setHttpRequest(new MessageService\DTO\Request([
418 'method' => HttpClient::HTTP_POST,
419 'uri' => self::JSON_API_URL,
420 'headers' => method_exists($httpClient, 'getRequestHeaders') ? $httpClient->getRequestHeaders()->toArray() : [],
421 'body' => $params,
422 ]));
423 $answer = [];
424
425 if ($httpClient->query(HttpClient::HTTP_POST, self::JSON_API_URL, $params) && $httpClient->getStatus() == '200')
426 {
427 try
428 {
429 $answer = Json::decode($httpClient->getResult());
430 }
431 catch (\Bitrix\Main\ArgumentException $e)
432 {
433 $answer = ['error' => -1000];
434 }
435 }
436
437 if (isset($answer['error']))
438 {
439 $result->addError(new Error($this->getErrorMessage($answer['error'], $answer)));
440 }
441
442 if (isset($answer['status']) && $answer['status'] === -1)
443 {
444 $msg = !empty($answer['message']) ? $answer['message'] : $this->getErrorMessage($answer['error'], 1000);
445 $result->addError(new Error($msg));
446 }
447
448 $result->setHttpResponse(new MessageService\DTO\Response([
449 'statusCode' => $httpClient->getStatus(),
450 'headers' => $httpClient->getHeaders()->toArray(),
451 'body' => $httpClient->getResult(),
452 'error' => Sender\Util::getHttpClientErrorString($httpClient)
453 ]));
454 $result->setData($answer);
455
456 return $result;
457 }
458
459 private function getErrorMessage($errorCode)
460 {
461 $errorCode = abs($errorCode);
462 $message = Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSASTBY_ERROR_'.$errorCode);
463 return $message ?: Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSASTBY_ERROR_OTHER');
464 }
465
466 private function loadFromList()
467 {
468 $result = $this->callJsonApi('get_senders');
469
470 if ($result->isSuccess())
471 {
472 $from = array();
473 $resultData = $result->getData();
474 foreach ($resultData['senders'] as $sender)
475 {
476 if (!empty($sender))
477 {
478 $from[] = array(
479 'id' => $sender,
480 'name' => $sender
481 );
482 }
483 }
484
485 $this->setOption('from_list', $from);
486 }
487 }
488}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static isModuleInstalled($moduleName)
getOption($optionName, $defaultValue=null)
prepareMessageBodyForSend(string $text)
Definition base.php:176
Providers Sender $sender
Definition base.php:13
static getHttpClientErrorString(HttpClient $httpClient)
Definition util.php:24