26 public const ID =
'twilio';
48 return ($this->
getOption(
'account_sid') !==
null);
64 return is_array($from) ? $from : array();
67 public function register(array $fields)
69 $sid = (string)$fields[
'account_sid'];
70 $token = (string)$fields[
'account_token'];
72 $result = $this->callExternalMethod(
74 'Accounts/'.$sid, array(), $sid, $token
76 if ($result->isSuccess())
78 $data = $result->getData();
80 if ($data[
'status'] !==
'active')
82 $result->addError(
new Error(
Loc::getMessage(
'MESSAGESERVICE_SENDER_SMS_TWILIO_ERROR_ACCOUNT_INACTIVE')));
87 $this->
setOption(
'account_token', $token);
88 $this->
setOption(
'account_friendly_name', $data[
'friendly_name']);
99 'friendly_name' => $this->
getOption(
'account_friendly_name')
105 return 'https://www.twilio.com/console';
115 $result->addError(
new Error(
Loc::getMessage(
'MESSAGESERVICE_SENDER_SMS_TWILIO_CAN_USE_ERROR')));
119 $eventResults = self::fireEventBeforeMessageSend($messageFields);
120 foreach ($eventResults as $eventResult)
122 $eventParams = $eventResult->getParameters();
124 if ($eventResult->getType() === \
Bitrix\Main\EventResult::ERROR)
127 if ($eventParams && is_string($eventParams))
129 $result->addError(
new Error($eventParams));
133 $result->addError(
new Error(
Loc::getMessage(
"MESSAGESERVICE_SENDER_SMS_TWILIO_MESSAGE_HAS_NOT_BEEN_SENT")));
138 if (is_array($eventParams))
140 $messageFields = array_merge($messageFields, $eventParams);
144 if (isset($messageFields[
'MESSAGE_FROM_ALPHANUMERIC']))
146 $apiResult = $this->sendMessageByAlphanumericNumber($sid, $messageFields);
148 !$apiResult->isSuccess()
149 && $this->checkSupportErrorAlphanumericNumber($apiResult->getErrorCollection())
152 $apiResult = $this->sendMessageByNumber($sid, $messageFields);
157 $apiResult = $this->sendMessageByNumber($sid, $messageFields);
161 $result->setServiceRequest($apiResult->getHttpRequest());
162 $result->setServiceResponse($apiResult->getHttpResponse());
164 if (!$apiResult->isSuccess())
166 $result->addErrors($apiResult->getErrors());
170 $resultData = $apiResult->getData();
171 if (isset($resultData[
'sid']))
173 $result->setExternalId($resultData[
'sid']);
175 $result->setAccepted();
184 $result->setId($messageFields[
'ID']);
185 $result->setExternalId($messageFields[
'EXTERNAL_ID']);
190 $result->addError(
new Error(
Loc::getMessage(
'MESSAGESERVICE_SENDER_SMS_TWILIO_CAN_USE_ERROR')));
194 $apiResult = $this->callExternalMethod(
196 'Accounts/'.$sid.
'/Messages/'.$result->getExternalId()
198 if (!$apiResult->isSuccess())
200 $result->addErrors($apiResult->getErrors());
204 $resultData = $apiResult->getData();
205 $result->setStatusCode($resultData[
'status']);
206 $result->setStatusText($resultData[
'status']);
207 if (in_array($resultData[
'status'],
208 array(
'accepted',
'queued',
'sending',
'sent',
'delivered',
'undelivered',
'failed')))
210 $result->setStatusText(
211 Loc::getMessage(
'MESSAGESERVICE_SENDER_SMS_TWILIO_MESSAGE_STATUS_'.mb_strtoupper($resultData[
'status']))
221 $status = parent::resolveStatus($serviceStatus);
223 switch ((
string)$serviceStatus)
226 return MessageService\MessageStatus::ACCEPTED;
229 return MessageService\MessageStatus::QUEUED;
232 return MessageService\MessageStatus::SENDING;
235 return MessageService\MessageStatus::SENT;
238 return MessageService\MessageStatus::DELIVERED;
241 return MessageService\MessageStatus::UNDELIVERED;
244 return MessageService\MessageStatus::FAILED;
255 $this->loadFromList();
260 private function callExternalMethod($httpMethod, $apiMethod, array $params = array(), $sid =
null, $token =
null):
Sender\
Result\
HttpRequestResult
262 $url = $this->getRequestUrl($apiMethod);
265 "socketTimeout" => $this->socketTimeout,
266 "streamTimeout" => $this->streamTimeout,
267 "waitResponse" =>
true,
269 $httpClient->setHeader(
'User-Agent',
'Bitrix24');
270 $httpClient->setCharset(
'UTF-8');
272 if (!$sid || !$token)
274 $sid = $this->getOption(
'account_sid');
275 $token = $this->getOption(
'account_token');
278 $httpClient->setAuthorization($sid, $token);
284 $params = \Bitrix\Main\Text\Encoding::convertEncoding($params, SITE_CHARSET,
'UTF-8');
290 $result->setHttpRequest(
new MessageService\DTO\
Request([
293 'headers' => method_exists($httpClient,
'getRequestHeaders') ? $httpClient->getRequestHeaders()->toArray() : [],
296 if ($httpClient->query($httpMethod, $url, $params))
300 $answer = Json::decode($httpClient->getResult());
302 catch (ArgumentException $e)
304 $result->addError(
new Error(
'Service error'));
307 $httpStatus = $httpClient->getStatus();
308 if ($httpStatus >= 400)
310 $errorInformant =
new ErrorInformant($answer[
'message'], $answer[
'code'], $answer[
'more_info'], $httpStatus);
311 $result->addError($errorInformant->getError());
322 $result->setHttpResponse(
new MessageService\DTO\Response([
323 'statusCode' => $httpClient->getStatus(),
324 'headers' => $httpClient->getHeaders()->toArray(),
325 'body' => $httpClient->getResult(),
326 'error' => Sender\Util::getHttpClientErrorString($httpClient)
329 if ($result->isSuccess())
331 $result->setData($answer);
337 private function loadFromList()
340 $result = $this->callExternalMethod(
342 'Accounts/'.$sid.
'/IncomingPhoneNumbers'
345 if ($result->isSuccess())
348 $resultData = $result->getData();
349 if (isset($resultData[
'incoming_phone_numbers']) && is_array($resultData[
'incoming_phone_numbers']))
351 foreach ($resultData[
'incoming_phone_numbers'] as $phoneNumber)
353 if ($phoneNumber[
'capabilities'][
'sms'] ===
true)
356 'id' => $phoneNumber[
'phone_number'],
357 'name' => $phoneNumber[
'friendly_name']
367 private function checkSupportErrorAlphanumericNumber(ErrorCollection $collection): bool
369 if ($collection->getErrorByCode(self::NOT_SUPPORT_ALPHANUMERIC_NUMBER_STATUS_CODE))
382 private function sendMessageByAlphanumericNumber(
string $sid, array $messageFields): Sender\Result\HttpRequestResult
385 'To' => $messageFields[
'MESSAGE_TO'],
387 'From' => $messageFields[
'MESSAGE_FROM_ALPHANUMERIC'],
391 return $this->callExternalMethod(
393 'Accounts/'.$sid.
'/Messages/',
403 private function sendMessageByNumber(
string $sid, array $messageFields): Sender\Result\HttpRequestResult
406 'To' => $messageFields[
'MESSAGE_TO'],
408 'From' => $messageFields[
'MESSAGE_FROM'],
412 if (!$params[
'From'])
416 if (is_string($params[
'From']) && mb_strlen($params[
'From']) === 34)
418 $params[
'MessagingServiceSid'] = $params[
'From'];
419 unset($params[
'From']);
422 return $this->callExternalMethod(
424 'Accounts/'.$sid.
'/Messages/',
435 $event =
new Event(
'messageservice', self::ON_BEFORE_TWILIO_MESSAGE_SEND, $messageFields);
438 return $event->getResults();
441 private function getRequestUrl(
string $apiMethod): string
445 'twilio_api_uri_tpl',
446 'https://api.twilio.com/2010-04-01/%apiMethod%.json'
449 return str_replace(
'%apiMethod%', $apiMethod, $url);
static loadMessages($file)
static getMessage($code, $replace=null, $language=null)