public SmsSentResult SendSmsMessage(SmsMessage smsMessage, string userId) { SmsConfiguration smsConfiguration = GetSmsConfiguration(); SmsSentResult smsSentResult = new SmsSentResult() { Success = false }; try { TwilioClient.Init(smsConfiguration.Sid, smsConfiguration.AuthToken); var message = MessageResource.Create( body: smsMessage.Body, from: new Twilio.Types.PhoneNumber(smsConfiguration.Number), to: new Twilio.Types.PhoneNumber(smsMessage.ReceiverPhoneNo) ); smsSentResult.Success = true; smsSentResult.Id = userId; _log.Info("SmsSenderManager - SendSmsMessage - Sms send successfully for user id: " + userId + " number: " + smsMessage.ReceiverPhoneNo); } catch (Exception ex) { smsSentResult.Ex = ex; _log.Error(Log4NetMessageHelper.FormateMessageForException(ex, "SendSmsMessage", smsMessage.ReceiverPhoneNo)); } return(smsSentResult); }
public SmsSentResult SendSmsMessage(SmsMessage smsMessage, string userId) { SmsConfiguration smsConfiguration = GetSmsConfiguration(); SmsSentResult smsSentResult = new SmsSentResult() { Success = false }; try { smsSentResult.Success = true; smsSentResult.Id = userId; log.Info("SmsSenderManager - SendSmsMessage - Sms send successfully for user id: " + userId + " number: " + smsMessage.ReceiverPhoneNo); } catch (Exception ex) { smsSentResult.Ex = ex; log.Error(Log4NetMessageHelper.FormateMessageForException(ex, "SendSmsMessage", smsMessage.ReceiverPhoneNo)); } return(smsSentResult); }
private async Task <Response <SmsSentResult> > SendSmsAsync( string phoneNumber, string message, string smscLogin, string smscPassword, string?senderName, int retriesCount = 0, CancellationToken cancellationToken = default) { var client = new RestClient("https://smsc.ru/sys/send.php"); var request = new RestRequest { Method = Method.POST }; request.AddQueryParameter("login", smscLogin); request.AddQueryParameter("psw", smscPassword); if (!String.IsNullOrWhiteSpace(senderName)) { request.AddQueryParameter("sender", senderName); } request.AddQueryParameter("phones", phoneNumber); request.AddQueryParameter("mes", message); request.AddQueryParameter("cost", "2"); // отправить и вернуть стоимость request.AddQueryParameter("fmt", "3"); // результат в json _logger.LogInformation($"Отправляем sms на номер {phoneNumber}..."); // execute var response = await client.ExecuteAsync <SmscResponseData>(request, cancellationToken); string resultJson; decimal?messageCost = null; if (response.IsSuccessful) { resultJson = JsonConvert.SerializeObject(response.Data, SmsConstants.JsonSerializerSettings); _logger.LogDebug(resultJson); // has sent error if ((response.Data.ErrorCode ?? 0) != 0) { // if we got message denied error (6) and it is our first attempt, let's remove sender name and try again // because SMSC can block SMS to Megafon and Tele2 with specified sender name when there is sender name is not agreed if (response.Data.ErrorCode == 6 && retriesCount == 0) { _logger.LogWarning("Отправка SMS на номер {PhoneNumber} заблокирована. Попробуем повторно отправить без указания имени отправтиеля (текущее имя отправителя = \"{SenderName}\")", phoneNumber, senderName); return(await SendSmsAsync(phoneNumber, message, smscLogin, smscPassword, null, 1, cancellationToken)); } var errorMessage = $"Ошибка при отправке sms на номер {phoneNumber} (error_code = {response.Data.ErrorCode}, error = \"{response.Data.Error}\")"; _logger.LogWarning($"Ошибка при отправке sms на номер {phoneNumber} (error_code = {response.Data.ErrorCode}, error = \"{response.Data.Error}\")"); // check error code switch (response.Data.ErrorCode) { case 1: // Ошибка в параметрах. case 2: // Неверный логин или пароль. return(Response.Failed(new Error((int)SmsError.Auth, errorMessage), new SmsSentResult(null, null, resultJson))); case 3: // Недостаточно средств на счёте Клиента. return(Response.Failed(new Error((int)SmsError.NoMoney, errorMessage), new SmsSentResult(null, null, resultJson))); case 4: // IP-адрес временно заблокирован из-за частых ошибок в запросах. case 9: // Более 15 параллельных запросов под одним логином с разных подключений. return(Response.Failed(new Error((int)SmsError.RateLimit, errorMessage), new SmsSentResult(null, null, resultJson))); default: return(Response.Failed(new Error((int)SmsError.Unknown, errorMessage), new SmsSentResult(null, null, resultJson))); } } } // has HTTP error else { var data = new SmscResponseData { ErrorCode = -1 }; if (response.ErrorException != null) { data.Error = $"{response.ErrorException.GetType().Name}: {response.ErrorException.Message}"; } else { data.Error = !String.IsNullOrEmpty(response.ErrorMessage) ? $"{response.ErrorMessage}" : $"{(int) response.StatusCode}, {response.StatusDescription}"; } resultJson = JsonConvert.SerializeObject(data, SmsConstants.JsonSerializerSettings); _logger.LogWarning( $"Ошибка при отправке sms на номер {phoneNumber} (error = \"{data.Error}\")"); return(Response.Failed(new Error((int)SmsError.Unknown, data.Error), new SmsSentResult(null, null, resultJson))); } // successfully sent if (response.Data.Cost.HasValue) { messageCost = response.Data.Cost; } _logger.LogInformation($"Успешно отправили sms на номер {phoneNumber}"); int?sentSmsCount = null; if (response.IsSuccessful && response.Data != null ! && response.Data.Count > 0) { sentSmsCount = response.Data.Count.Value; } var result = new SmsSentResult(sentSmsCount, messageCost, resultJson); return(Response.Successful(result)); }