1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
smsru.php
См. документацию.
1<?php
2namespace Bitrix\MessageService\Sender\Sms;
3
4use Bitrix\Main\Error;
5use Bitrix\Main\Localization\Loc;
6use Bitrix\Main\Result;
7use Bitrix\Main\Web\HttpClient;
8use Bitrix\Main\Web\Json;
9
10use Bitrix\MessageService\Sender;
11use Bitrix\MessageService\Sender\Result\MessageStatus;
12use Bitrix\MessageService\Sender\Result\SendMessage;
13
14use Bitrix\MessageService;
15
16Loc::loadMessages(__FILE__);
17
19{
20 use Sender\Traits\RussianProvider;
21
22 public const ID = 'smsru';
23
24 public function getId()
25 {
26 return static::ID;
27 }
28
29 public function getName()
30 {
31 return Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSRU_NAME');
32 }
33
34 public function getShortName()
35 {
36 return 'sms.ru';
37 }
38
39 public function isDemo()
40 {
41 return false;
42 }
43
44 public function getDemoBalance()
45 {
46 $params = array(
47 'embed_id' => $this->getOption('embed_id')
48 );
49 $apiResult = $this->callExternalMethod('my/free', $params);
50
51 $balance = array(
52 'total_free' => 0,
53 'used_today' => 0,
54 'available_today' => 0
55 );
56
57 if ($apiResult->isSuccess())
58 {
59 $balanceData = $apiResult->getData();
60 $balance['total_free'] = (int)$balanceData['total_free'];
61 $balance['used_today'] = (int)$balanceData['used_today'];
62 $balance['available_today'] = max(0, $balance['total_free'] - $balance['used_today']);
63 }
64
65 return $balance;
66 }
67
68 public function getFromList()
69 {
70 $from = $this->getOption('from_list');
71 return is_array($from) ? $from : array();
72 }
73
74 public function isConfirmed()
75 {
76 return ($this->getOption('is_confirmed') === true);
77 }
78
79 public function isRegistered()
80 {
81 return ($this->getOption('embed_id') !== null);
82 }
83
84 public function register(array $fields)
85 {
86 $userPhone = \NormalizePhone($fields['user_phone']);
87 $params = array(
88 'user_phone' => $userPhone,
89 'user_firstname' => $fields['user_firstname'],
90 'user_lastname' => $fields['user_lastname'],
91 'user_email' => $fields['user_email'],
92 'embed_partner' => $this->getEmbedPartner(),
93 'embed_hash' => $this->getEmbedHash($userPhone)
94 );
95
96 $result = $this->callExternalMethod('embed/register', $params);
97 if ($result->isSuccess())
98 {
99 $data = $result->getData();
100
101 $this->setOption('embed_id', $data['embed_id']);
102 $this->setOption('user_phone', $userPhone);
103 if (!empty($params['user_firstname']))
104 {
105 $this->setOption('user_firstname', $params['user_firstname']);
106 }
107 if (!empty($params['user_lastname']))
108 {
109 $this->setOption('user_lastname', $params['user_lastname']);
110 }
111 if (!empty($params['user_email']))
112 {
113 $this->setOption('user_email', $params['user_email']);
114 }
115
116 if (!empty($data['confirmed']))
117 {
118 $this->setOption('is_confirmed', true);
119 }
120 }
121
122 return $result;
123 }
124
133 public function getOwnerInfo()
134 {
135 return array(
136 'phone' => $this->getOption('user_phone'),
137 'firstName' => $this->getOption('user_firstname'),
138 'lastName' => $this->getOption('user_lastname'),
139 'email' => $this->getOption('user_email')
140 );
141 }
142
148 {
149 $embedId = $this->getOption('embed_id');
150 $params = array(
151 'embed_id' => $embedId,
152 'confirm' => $fields['confirm']
153 );
154 $result = $this->callExternalMethod('embed/confirm', $params);
155
156 if ($result->isSuccess())
157 {
158 $this->setOption('is_confirmed', true);
159 $callBackResult = $this->callExternalMethod('callback/add', array(
160 'embed_id' => $embedId,
161 'url' => $this->getCallbackUrl()
162 ));
163 if ($callBackResult->isSuccess())
164 {
165 $this->setOption('callback_set', true);
166 }
167 }
168
169 return $result;
170 }
171
172 public function sendConfirmationCode()
173 {
174 if ($this->isRegistered())
175 {
176 $ownerInfo = $this->getOwnerInfo();
177 $result = $this->register(array(
178 'user_phone' => $ownerInfo['phone'],
179 'user_firstname' => $ownerInfo['firstName'],
180 'user_lastname' => $ownerInfo['lastName'],
181 'user_email' => $ownerInfo['email'],
182 ));
183 }
184 else
185 {
186 $result = new Result();
187 $result->addError(new Error('Provider is not registered.'));
188 }
189
190 return $result;
191 }
192
193 public function getExternalManageUrl()
194 {
195 if ($this->isRegistered())
196 {
197 return 'https://sms.ru/?panel=login&action=login&embed_id='.$this->getOption('embed_id');
198 }
199 return 'https://sms.ru/?panel=login';
200 }
201
203 {
204 if (!$this->canUse())
205 {
206 $result = new SendMessage();
207 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSRU_CAN_USE_ERROR')));
208 return $result;
209 }
210
211 $params = array(
212 'to' => $messageFields['MESSAGE_TO'],
213 'text' => $this->prepareMessageBodyForSend($messageFields['MESSAGE_BODY']),
214 'embed_id' => $this->getOption('embed_id')
215 );
216
217 if ($this->isDemo())
218 {
219 $params['to'] = $this->getOption('user_phone');
220 }
221
222 if ($messageFields['MESSAGE_FROM'])
223 {
224 $params['from'] = $messageFields['MESSAGE_FROM'];
225 }
226
227 $result = new SendMessage();
228 $apiResult = $this->callExternalMethod('sms/send', $params);
229 $result->setServiceRequest($apiResult->getHttpRequest());
230 $result->setServiceResponse($apiResult->getHttpResponse());
231
232 $resultData = $apiResult->getData();
233
234 if (!$apiResult->isSuccess())
235 {
236 if ((int)$resultData['status_code'] == 206)
237 {
239 $result->addError(new Error($this->getErrorMessage($resultData['status_code'])));
240 }
241 else
242 {
243 $result->addErrors($apiResult->getErrors());
244 }
245 }
246 else
247 {
248 $smsData = current($resultData['sms']);
249
250 if (isset($smsData['sms_id']))
251 {
252 $result->setExternalId($smsData['sms_id']);
253 }
254
255 if ((int)$smsData['status_code'] !== 100)
256 {
257 $result->addError(new Error($this->getErrorMessage($smsData['status_code'])));
258 }
259 elseif ((int)$smsData['status_code'] == 206)
260 {
262 $result->addError(new Error($this->getErrorMessage($smsData['status_code'])));
263 }
264 else
265 {
266 $result->setAccepted();
267 }
268 }
269
270 return $result;
271 }
272
274 {
275 $result = new MessageStatus();
276 $result->setId($messageFields['ID']);
277 $result->setExternalId($messageFields['EXTERNAL_ID']);
278
279 if (!$this->canUse())
280 {
281 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSRU_CAN_USE_ERROR')));
282 return $result;
283 }
284
285 $params = array(
286 'sms_id' => $result->getExternalId(),
287 'embed_id' => $this->getOption('embed_id')
288 );
289
290 $apiResult = $this->callExternalMethod('sms/status', $params);
291 if (!$apiResult->isSuccess())
292 {
293 $result->addErrors($apiResult->getErrors());
294 }
295 else
296 {
297 $resultData = $apiResult->getData();
298 $smsData = current($resultData['sms']);
299
300 $result->setStatusCode($smsData['status_code']);
301 $result->setStatusText($smsData['status_text']);
302
303 if ((int)$resultData['status_code'] !== 100)
304 {
305 $result->addError(new Error($this->getErrorMessage($smsData['status_code'])));
306 }
307 }
308
309 return $result;
310 }
311
312 public static function resolveStatus($serviceStatus)
313 {
314 $status = parent::resolveStatus($serviceStatus);
315
316 switch ((int)$serviceStatus)
317 {
318 case 100:
320 break;
321 case 101:
323 break;
324 case 102:
326 break;
327 case 103:
329 break;
330 case 104: //timeout
331 case 105: //removed by moderator
332 case 106: //error on receiver`s side
333 case 107: //unknown reason
334 case 108: //rejected
336 break;
337 case 110:
339 break;
340 }
341
342 return $status;
343 }
344
345 public function sync()
346 {
347 if ($this->isRegistered())
348 {
349 $this->loadFromList();
350 }
351 return $this;
352 }
353
354 private function callExternalMethod($method, $params): Sender\Result\HttpRequestResult
355 {
356 $url = 'https://sms.ru/'.$method;
357
358 $httpClient = new HttpClient(array(
359 "socketTimeout" => $this->socketTimeout,
360 "streamTimeout" => $this->streamTimeout,
361 "waitResponse" => true,
362 ));
363 $httpClient->setHeader('User-Agent', 'Bitrix24');
364 $httpClient->setCharset('UTF-8');
365
366 $params['json'] = 1;
367
369 $answer = array();
370
371 $result->setHttpRequest(new MessageService\DTO\Request([
372 'method' => HttpClient::HTTP_POST,
373 'uri' => $url,
374 'headers' => method_exists($httpClient, 'getRequestHeaders') ? $httpClient->getRequestHeaders()->toArray() : [],
375 'body' => $params,
376 ]));
377 if ($httpClient->query(HttpClient::HTTP_POST, $url, $params) && $httpClient->getStatus() == '200')
378 {
379 $answer = $this->parseExternalAnswer($httpClient->getResult());
380 }
381
382 $answerCode = isset($answer['status_code']) ? (int)$answer['status_code'] : 0;
383
384 if ($answerCode !== 100)
385 {
386 $result->addError(new Error($this->getErrorMessage($answerCode, $answer)));
387 }
388 $result->setData($answer);
389 $result->setHttpResponse(new MessageService\DTO\Response([
390 'statusCode' => $httpClient->getStatus(),
391 'headers' => $httpClient->getHeaders()->toArray(),
392 'body' => $httpClient->getResult(),
393 'error' => Sender\Util::getHttpClientErrorString($httpClient)
394 ]));
395
396 return $result;
397 }
398
399 private function parseExternalAnswer($httpResult)
400 {
401 try
402 {
403 $answer = Json::decode($httpResult);
404 }
405 catch (\Bitrix\Main\ArgumentException $e)
406 {
407 $data = explode(PHP_EOL, $httpResult);
408 $code = (int)array_shift($data);
409 $answer = $data;
410 $answer['status_code'] = $code;
411 $answer['status'] = $code === 100 ? 'OK' : 'ERROR';
412 }
413
414 if (!is_array($answer) && is_numeric($answer))
415 {
416 $answer = array(
417 'status' => $answer === 100 ? 'OK' : 'ERROR',
418 'status_code' => $answer
419 );
420 }
421
422 return $answer;
423 }
424
425 private function getEmbedPartner()
426 {
427 return 'bitrix24';//Option::get('messageservice', 'smsru_partner');
428 }
429
430 private function getSecretKey()
431 {
432 return 'P46y811M84W3b4H18SmDpy9KG3pKG3Ok';//Option::get('messageservice', 'smsru_secret_key');
433 }
434
435 private function getEmbedHash($phoneNumber)
436 {
437 return md5($phoneNumber.$this->getSecretKey());
438 }
439
440 private function getErrorMessage($errorCode, $answer = null)
441 {
442 $message = Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSRU_ERROR_'.$errorCode);
443 if (!$message && $answer && !empty($answer['errors']))
444 {
445 $errorCode = $answer['errors'][0]['status_code'];
446 $message = Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSRU_ERROR_'.$errorCode);
447 if (!$message)
448 {
449 $message = $answer['errors'][0]['status_text'];
450 }
451 }
452
453 return $message ?: Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSRU_ERROR_OTHER');
454 }
455
456 private function loadFromList()
457 {
458 $params = array(
459 'embed_id' => $this->getOption('embed_id')
460 );
461 $result = $this->callExternalMethod('my/senders', $params);
462
463 if ($result->isSuccess())
464 {
465 $from = array();
466 $resultData = $result->getData();
467 foreach ($resultData['senders'] as $sender)
468 {
469 if (!empty($sender))
470 {
471 $from[] = array(
472 'id' => $sender,
473 'name' => $sender
474 );
475 }
476 }
477
478 $this->setOption('from_list', $from);
479 }
480 }
481}
$messageFields
Определения callback_ednaru.php:22
Определения error.php:15
Определения request.php:10
Определения response.php:5
setOption($optionName, $optionValue)
Определения baseconfigurable.php:224
getOption($optionName, $defaultValue=null)
Определения baseconfigurable.php:237
prepareMessageBodyForSend(string $text)
Определения base.php:177
Providers Sender $sender
Определения base.php:14
confirmRegistration(array $fields)
Определения smsru.php:147
sendMessage(array $messageFields)
Определения smsru.php:202
static resolveStatus($serviceStatus)
Определения smsru.php:312
getMessageStatus(array $messageFields)
Определения smsru.php:273
static getHttpClientErrorString(HttpClient $httpClient)
Определения util.php:24
$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
if(!is_null($config))($config as $configItem)(! $configItem->isVisible()) $code
Определения options.php:195
$status
Определения session.php:10
NormalizePhone($number, $minLength=10)
Определения tools.php:4959
$message
Определения payment.php:8
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$method
Определения index.php:27
$url
Определения iframe.php:7
$fields
Определения yandex_run.php:501