Skip to content

Instantly share code, notes, and snippets.

@EscApp2
Created Dec 16, 2020
Embed
What would you like to do?
sms
<?php
//https://gricuk.ru/lp/blog/item/kastomnaya-sluzhba-otpravki-sms-v-bitrix/#block75
use Bitrix\Main\Application;
use Bitrix\Main\Error;
use Bitrix\Main\Result;
use Bitrix\Main\Web\HttpClient;
use Bitrix\Main\Web\Json;
use Bitrix\Main\Loader;
use Bitrix\MessageService\Sender\Result\MessageStatus;
use Bitrix\MessageService\Sender\Result\SendMessage;
use Bitrix\MessageService;
\CModule::IncludeModule('messageservice');
class SmsConsultKz extends \Bitrix\MessageService\Sender\Base
//class SmsConsultKz extends \Bitrix\MessageService\Sender\BaseConfigurable
{
const LOGIN = "LOGIN";
const PASS = "PASSWORD";
/*
public function getExternalManageUrl()
{
return 'http://cabinet.sms-consult.kz/';
}
public function isRegistered()
{
return (
$this->getOption('login') !== null
&&
$this->getOption('password') !== null
);
}
public function getDefaultFrom()
{
$fromList = $this->getFromList();
$from = isset($fromList[0]) ? $fromList[0]['id'] : null;
//Try to find alphanumeric from
foreach ($fromList as $item)
{
if (!preg_match('#^[0-9]+$#', $item['id']))
{
$from = $item['id'];
break;
}
}
return $from;
}
public function setDefaultFrom($from)
{
//$from = (string)$from;
//$this->setOption('default_from', $from);
return $this;
}
public function register(array $fields)
{
$result = new Result();
//$result->addError(new Error($this->getErrorMessage($answerCode, $answer)));
//$result->setData($answer);
//pre($fields);
if (!empty($fields['login']))
{
$this->setOption('login', $fields['login']);
}
if (!empty($fields['password']))
{
$this->setOption('password', $fields['password']);
}
return $result;
}
public function getOwnerInfo()
{
return array(
'login' => $this->getOption('login'),
'password' => $this->getOption('password'),
);
}
*/
//################################
public static function isSupported()
{
return true;
}
public function getId()
{
return 'sms_consult_kz';
}
public function getName()
{
return "Компания sms-consult.kz";
}
public function getShortName()
{
return 'sms-consult.kz';
}
public function isDemo()
{
return false;
}
public function canUse()
{
return true;
}
public function sendMessage(array $messageFields)
{
if (!$this->canUse()) {
$result = new SendMessage();
$result->addError(new Error(self::getMessage('MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_CAN_USE_ERROR')));
return $result;
}
//logto(date('d.m.Y H:i:s'),10,true);
//logto($messageFields,10,true);
$EXTERNAL_ID = time();
$params = array(
"login"=>"",
"password"=>"",
"id"=>$EXTERNAL_ID,
"type"=>"",
'recipient' => $messageFields['MESSAGE_TO'],
'sender' => $messageFields['MESSAGE_FROM'],
'text' => $messageFields['MESSAGE_BODY']
);
//logto(date('d.m.Y H:i:s'),11,true);
//logto($params,11,true);
$result = new SendMessage();
$apiResult = $this->callExternalMethod('message', $params);
$resultData = $apiResult->getData();
//logto($apiResult,11,true);
if (!$apiResult->isSuccess()) {
$result->addErrors($apiResult->getErrors());
} else {
$result->setExternalId($EXTERNAL_ID);
if($resultData['status_code']){
$status_const = self::resolveStatus($resultData['status_code']);
$result->setStatus($status_const);
/*
$arOKStatus = $this->getOkStatus();
if (!in_array($resultData['status_code'],$arOKStatus)) {
$result->setAccepted();
}
*/
}else{
$result->addError(new Error($this->getErrorMessage(999)));
}
}
return $result;
}
public function getMessageStatus(array $messageFields)
{
//logto(date('d.m.Y H:i:s'),12,true);
//logto($messageFields,12,true);
$result = new MessageStatus();
$result->setId($messageFields['ID']);
$result->setExternalId($messageFields['EXTERNAL_ID']);
if (!$this->canUse()) {
$result->addError(new Error(self::getMessage('MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_CAN_USE_ERROR')));
return $result;
}
$params = array(
"login"=>"",
"password"=>"",
"type"=>"",
"id"=>$result->getExternalId(),
);
$apiResult = $this->callExternalMethod('status', $params);
if (!$apiResult->isSuccess()) {
$result->addErrors($apiResult->getErrors());
} else {
$resultData = $apiResult->getData();
$result->setStatusCode($resultData['status_code']);
//$result->setStatusText($smsData['status_text']);
$arOKStatus = $this->getOkStatus();
if (!in_array($resultData['status_code'],$arOKStatus)) {
$result->addError(new Error($this->getErrorMessage($smsData['status_code'])));
}
}
return $result;
}
public static function resolveStatus($serviceStatus)
{
switch ((int)$serviceStatus) {
case 100:
return MessageService\MessageStatus::QUEUED;
break;
case 101:
return MessageService\MessageStatus::SENDING;
break;
case 102:
return MessageService\MessageStatus::DELIVERED;
break;
case 103: //expired
case 104: //deleted
case 105: //undeliverable
case 107: //unknown reason
case 108: //rejected
case 109: //rejected by sms-consult
return MessageService\MessageStatus::UNDELIVERED;
break;
case 106:
return MessageService\MessageStatus::READ;
break;
}
return $status;
}
public function getOkStatus(){
return array(
100,101,102,106
);
}
private function callExternalMethod($method, $params = [])
{
$url = 'http://service.sms-consult.kz/get.ashx';
$params["login"] = self::LOGIN;
$params["password"] = self::PASS;
$params["type"] = $method;
$httpClient = new HttpClient(array(
"socketTimeout" => 10,
"streamTimeout" => 30,
"waitResponse" => true,
));
$httpClient->setHeader('User-Agent', 'Bitrix24');
$httpClient->setCharset('UTF-8');
$isUtf = Application::getInstance()->isUtfMode();
if (!$isUtf) {
$params = \Bitrix\Main\Text\Encoding::convertEncoding($params, SITE_CHARSET, 'UTF-8');
}
$entityBody = http_build_query($params, "", "&");
$result = new Result();
$answer = array();
//$raw_answer = "status=201";
//$answer = $this->parseExternalAnswer($raw_answer);
if ($httpClient->query(HttpClient::HTTP_GET, $url."?".$entityBody) && $httpClient->getStatus() == '200') {
$answer = $this->parseExternalAnswer($httpClient->getResult());
}else{
$result->addError(new Error($this->getErrorMessage(999)));
return $result;
}
$answerCode = isset($answer['status_code']) ? (int)$answer['status_code'] : 0;
$arOKStatus = $this->getOkStatus();
if (!in_array($answerCode,$arOKStatus)) {
$result->addError(new Error($this->getErrorMessage($answerCode, $answer)));
}
$result->setData($answer);
return $result;
}
private function parseExternalAnswer($httpResult)
{
$output = array();
parse_str($httpResult, $output);
/*
try {
$answer = Json::decode($httpResult);
} catch (\Bitrix\Main\ArgumentException $e) {
$data = explode(PHP_EOL, $httpResult);
$code = (int)array_shift($data);
$answer = $data;
$answer['status_code'] = $code;
$answer['status'] = $code === 100 ? 'OK' : 'ERROR';
}
*/
//$answer = array();
// $answer['status'] = 'ERROR';
//$answer['status_code'] = 0;
$arOKStatus = $this->getOkStatus();
$answer = array(
'status' => in_array($output['status'],$arOKStatus) ? 'OK' : 'ERROR',
'status_code' => $output['status'],
);
return $answer;
}
private function getErrorMessage($errorCode, $answer = null)
{
$message = self::getMessage('MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_' . $errorCode);
if (!$message && $answer && !empty($answer['errors'])) {
$errorCode = $answer['errors'][0]['status_code'];
$message = self::getMessage('MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_' . $errorCode);
if (!$message) {
$message = $answer['errors'][0]['status_text'];
}
}
return $message ?: self::getMessage('MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_OTHER');
}
public static function getMessage($code)
{
$MESS = [];
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_NAME"] = "Компания SMS-Consult.kz";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_CAN_USE_ERROR"] = "Провайдер компании SMS-Consult.kz не настроен";
//NOT ERROR
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_100"] = "Сообщение поставлено в очередь на отправку.Доставка сообщения ещѐ не начата.";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_101"] = "Сообщение успешно отправлено на оборудование оператора.";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_102"] = "Сообщение успешно доставленоабоненту";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_106"] = "Сообщение прочитано абонентом";
//NOT ERROR end
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_103"] = "Истѐк срок жизни сообщения в процессе доставки на абонентское оборудование";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_104"] = "Сообщение удалено из очереди на доставку на стороне SMSC оператора";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_105"] = "Сообщение невозможно доставить";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_107"] = "Сообщение находится в неопределѐнном статусе";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_108"] = "Сообщение отвергнуто системой оператора";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_109"] = "Сообщение отвергнуто системой SMS-Consult";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_200"] = "Общая ошибка, покрывающая все неспецифичные причины синтаксической некорректности исходного запроса";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_201"] = "Некорректный формат идентификатора сообщения";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_202"] = "Некорректный формат имени отправителя";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_203"] = "Некорректный формат получателя";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_204"] = "Некорректная длина тела запроса";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_205"] = "Пользователь заблокирован в системе SMS-Consult";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_206"] = "Пользователь заблокирован в системе SMS-Consultпо причине задолженности";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_207"] = "Пользователь заблокирован в системе SMS-Consultпо причине превышения лимит";
$MESS["MESSAGESERVICE_SENDER_SMS_SMS_CONSULT_KZ_ERROR_OTHER"] = "Системная ошибка. Необходимо повторить запрос еще раз";
return $MESS[$code];
}
public static function onGetSmsSenders()
{
$class = __CLASS__;
return [new $class()];
}
public function getFromList()
{
/*
$result = $this->callExternalMethod('my/senders');
if ($result->isSuccess()) {
$from = array();
$resultData = $result->getData();
foreach ($resultData['senders'] as $sender) {
if (!empty($sender)) {
$from[] = array(
'id' => $sender,
'name' => $sender
);
}
}
return $from;
}
*/
$ret = array(
array(
"id"=>"SMS_NAME",
"name"=>"SMS_NAME",
),
);
return $ret;
//return [];
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment