Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
smslineby.php
1<?php
3
10
14
16
17Loc::loadMessages(__FILE__);
18
20{
21 public const ID = 'smslineby';
22
23 const JSON_API_URL = 'https://api.smsline.by/v3/';
24
25 public static function isSupported()
26 {
27 return ModuleManager::isModuleInstalled('b24network');
28 }
29
30 public function getId()
31 {
32 return static::ID;
33 }
34
35 public function getName()
36 {
37 return 'SMS-line';
38 }
39
40 public function getShortName()
41 {
42 return 'smsline.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('login') !== null
55 &&
56 $this->getOption('api_key') !== null
57 );
58 }
59
60 public function register(array $fields)
61 {
62 $login = (string) $fields['login'];
63 $key = (string) $fields['api_key'];
64
65 $result = $this->sendGetRequest('balance/packets', $this->makeSignature('balancepackets', $key), $login);
66 if ($result->isSuccess())
67 {
68 $this->setOption('login', $login);
69 $this->setOption('api_key', $key);
70 }
71
72 return $result;
73 }
74
80 public function getOwnerInfo()
81 {
82 return array(
83 'login' => $this->getOption('login'),
84 );
85 }
86
87 public function getExternalManageUrl()
88 {
89 return 'https://mobilemarketing.by/login/';
90 }
91
92 public function sendMessage(array $messageFields)
93 {
94 if (!$this->canUse())
95 {
96 $result = new SendMessage();
97 $result->addError(new Error('Service is unavailable'));
98 return $result;
99 }
100
101 $message = [
102 'target' => $messageFields['MESSAGE_FROM'],
103 'msisdn' => str_replace('+', '', $messageFields['MESSAGE_TO']),
104 'text' => $this->prepareMessageBodyForSend($messageFields['MESSAGE_BODY']),
105 'callback_url' => $this->getCallbackUrl()
106 ];
107
108 $result = new SendMessage();
109 $apiResult = $this->sendPostRequest('messages/single/sms', $message);
110 $result->setServiceRequest($apiResult->getHttpRequest());
111 $result->setServiceResponse($apiResult->getHttpResponse());
112
113 if (!$apiResult->isSuccess())
114 {
115 $result->addErrors($apiResult->getErrors());
116 }
117 else
118 {
119 $resultData = $apiResult->getData();
120 $smsData = $resultData['message'];
121 $smsId = $smsData['id_message'];
122
123 if (!$smsId)
124 {
125 $result->addError(new Error($this->getErrorMessage(-1000)));
126 }
127 else
128 {
129 $result->setExternalId($smsId);
130 $result->setAccepted();
131 }
132 }
133
134 return $result;
135 }
136
137 public function getMessageStatus(array $messageFields)
138 {
139 $result = new MessageStatus();
140 $result->setId($messageFields['ID']);
141 $result->setExternalId($messageFields['EXTERNAL_ID']);
142
143 if (!$this->canUse())
144 {
145 $result->addError(new Error('Service is unavailable'));
146 return $result;
147 }
148
149 $apiResult = $this->sendGetRequest('messages/'.$result->getExternalId());
150 if (!$apiResult->isSuccess())
151 {
152 $result->addErrors($apiResult->getErrors());
153 }
154 else
155 {
156 $resultData = $apiResult->getData();
157 $smsData = $resultData['message'];
158
159 if (!$smsData)
160 {
161 $result->addError(new Error($this->getErrorMessage(-1000)));
162 }
163
164 $result->setStatusText($smsData['state']['name']);
165 $result->setStatusCode(self::resolveStatus($smsData['state']['state']));
166 }
167
168 return $result;
169 }
170
171 public static function resolveStatus($serviceStatus)
172 {
173 $status = parent::resolveStatus($serviceStatus);
174
175 switch ($serviceStatus)
176 {
177 case 'seen':
178 return MessageService\MessageStatus::READ;
179 break;
180 case 'delivered':
181 return MessageService\MessageStatus::DELIVERED;
182 break;
183 case 'accepted':
184 return MessageService\MessageStatus::ACCEPTED;
185 break;
186 case 'enrouted':
187 return MessageService\MessageStatus::SENT;
188 break;
189 case 'undeliverable':
190 case 'expired':
191 case 'deleted':
192 return MessageService\MessageStatus::UNDELIVERED;
193 break;
194 case 'reject':
195 case 'notsent':
196 case 'textblacklist':
197 case 'noviber':
198 case 'blocked':
199 case 'unknown':
200 case 'nostatus':
201 return MessageService\MessageStatus::FAILED;
202 break;
203 }
204
205 return $status;
206 }
207
208 public function sync()
209 {
210 if ($this->isRegistered())
211 {
212 $this->loadFromList();
213 }
214 return $this;
215 }
216
217 private function loadFromList()
218 {
219 $result = $this->sendGetRequest('balance/packets');
220
221 if ($result->isSuccess())
222 {
223 $from = [];
224 $resultData = $result->getData();
225 foreach ($resultData['packets'] as $packet)
226 {
227 if (isset($packet['targets']) && is_array($packet['targets']))
228 {
229 foreach ($packet['targets'] as $target)
230 {
231 $from[] = array(
232 'id' => $target,
233 'name' => $target
234 );
235 }
236 }
237 }
238
239 $this->setOption('from_list', $from);
240 }
241 }
242
243 private function makeSignature($text, $key = null)
244 {
245 if (!$key)
246 {
247 $key = $this->getOption('api_key');
248 }
249
250 return hash_hmac("sha256", $text, $key);
251 }
252
253 private function sendGetRequest($path, $signature = null, $login = null)
254 {
255 if (!$signature)
256 {
257 $signature = $this->makeSignature(str_replace('/', '', $path));
258 }
259
260 if (!$login)
261 {
262 $login = $this->getOption('login');
263 }
264
265 return $this->sendHttpRequest(HttpClient::HTTP_GET, $login, $signature, $path);
266 }
267
268 private function sendPostRequest($path, array $params)
269 {
270 $login = $this->getOption('login');
271 $requestBody = Json::encode($params);
272 $signature = $this->makeSignature(str_replace('/', '', $path).$requestBody);
273
274 return $this->sendHttpRequest(HttpClient::HTTP_POST, $login, $signature, $path, $requestBody);
275 }
276
277
278 private function sendHttpRequest($method, $login, $signature, $path, $body = null): Sender\Result\HttpRequestResult
279 {
280 $httpClient = new HttpClient(array(
281 "socketTimeout" => $this->socketTimeout,
282 "streamTimeout" => $this->streamTimeout,
283 "waitResponse" => true,
284 ));
285 $httpClient->setCharset('UTF-8');
286 $httpClient->setHeader('User-Agent', 'Bitrix24');
287 $httpClient->setHeader('Content-Type', 'application/json');
288 $httpClient->setHeader('Authorization-User', $login);
289 $httpClient->setHeader('Authorization', "Bearer $signature");
290
291 $result = new Sender\Result\HttpRequestResult();
292 $answer = ['error' => -1000];
293
294 $url = self::JSON_API_URL.$path;
295
296 $result->setHttpRequest(new MessageService\DTO\Request([
297 'method' => $method,
298 'uri' => $url,
299 'headers' => method_exists($httpClient, 'getRequestHeaders') ? $httpClient->getRequestHeaders()->toArray() : [],
300 'body' => $body,
301 ]));
302 if ($httpClient->query($method, $url, $body))
303 {
304 try
305 {
306 $answer = Json::decode($httpClient->getResult());
307 }
308 catch (\Bitrix\Main\ArgumentException $e)
309 {
310 }
311 }
312
313 if (isset($answer['error']))
314 {
315 $result->addError(new Error($this->getErrorMessage($answer['error']['code'], $answer['error']['message'])));
316 }
317
318 $result->setHttpResponse(new MessageService\DTO\Response([
319 'statusCode' => $httpClient->getStatus(),
320 'headers' => $httpClient->getHeaders()->toArray(),
321 'body' => $httpClient->getResult(),
322 'error' => Sender\Util::getHttpClientErrorString($httpClient)
323 ]));
324
325 $result->setData($answer);
326
327 return $result;
328 }
329
330 private function getErrorMessage($errorCode, $text = null)
331 {
332 $message = Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSLINE_ERROR_'.$errorCode, null, 'ru');
333 return $message ?: ($text ?: Loc::getMessage('MESSAGESERVICE_SENDER_SMS_SMSLINE_ERROR_OTHER',null, 'ru'));
334 }
335}
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
static getHttpClientErrorString(HttpClient $httpClient)
Definition util.php:24