public async Task SendAsync(ISmsNotification message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } var errors = new Dictionary <string, dynamic>(); foreach (var recipientNumber in message.RecipientPhoneNumbers) { try { await _smsSender.SendAsync(new SmsDto() { Text = message.Text, RecipientPhoneNumber = recipientNumber }); } catch (SmsSenderException exception) { errors.Add(exception.Message, exception.InnerException); } } if (errors.Any()) { throw new SmsSenderException(NotAllSmsWereSentExceptionMessage, errors); } }
public async Task <CaptchaResult> GenerateCaptchaAsync() { string captchaCode = await _captchaCodeGenerator.GenerateCaptchaCodeAsync(); await _captchaCodeStorage.SaveAsync(captchaCode); CaptchaResult result = new CaptchaResult { CaptchaCode = captchaCode, Timestamp = DateTime.UtcNow }; string phoneNumber = await _smsReceiverSelector.SelectAsync(); string content = await _smsContentGenerator.GenerateAsync(result); if (string.IsNullOrEmpty(phoneNumber) || string.IsNullOrEmpty(content)) { result.Failed = true; return(result); } await _smsSender.SendAsync(phoneNumber, content); return(result); }
public virtual async Task ExecuteAsync(SmsNotificationSendingJobArgs args) { var notification = await _notificationRepository.GetAsync(args.NotificationId); var userPhoneNumber = await _userPhoneNumberProvider.GetAsync(notification.UserId); if (userPhoneNumber.IsNullOrWhiteSpace()) { await SaveNotificationResultAsync(notification, false, NotificationConsts.FailureReasons.ReceiverInfoNotFound); return; } var notificationInfo = await _notificationInfoRepository.GetAsync(notification.NotificationInfoId); var properties = _jsonSerializer.Deserialize <IDictionary <string, object> >(notificationInfo .GetDataValue(NotificationProviderSmsConsts.NotificationInfoPropertiesPropertyName).ToString()); var smsMessage = new SmsMessage(userPhoneNumber, notificationInfo.GetDataValue(NotificationProviderSmsConsts.NotificationInfoTextPropertyName) .ToString()); foreach (var property in properties) { smsMessage.Properties.AddIfNotContains(property); } await _smsSender.SendAsync(smsMessage); await SaveNotificationResultAsync(notification, true); }
/// <summary> /// 发送短信 /// </summary> /// <returns></returns> public async Task SmsSend() { await _smsSender.SendAsync( "15958456864", // target phone number "This is test sms..." // message text ); }
public async Task SendAsync(OtpSendRequest request) { //validate user existence var userExists = await UserExists(request.User); if (!userExists) { throw new UnauthorizedAccessException(ErrorStrings.UserNotFound); } //Generate otp var otpGeneratedTime = DateTime.UtcNow; var otp = _otpGenerator.Generate(otpGeneratedTime); //store otp generation await CreateOtpDocument(request.User, otpGeneratedTime); //send sms var sent = await _smsSender.SendAsync($"{otp} is your OTP for Covid19Radar. Valid for next 30 seconds.", request.Phone); if (!sent) { throw new ApplicationException(ErrorStrings.OtpSmsSendFailure); } }
public async Task SendNotification(List <NotificationType> notificationTypesToCall, string sendTo, string subject, string message) { if (notificationTypesToCall == null) { return; } foreach (var enm in notificationTypesToCall) { switch (enm) { case NotificationType.Email: await _emailSender.SendAsync(sendTo, subject, message); break; case NotificationType.Sms: await _smsSender.SendAsync(sendTo, subject, message); break; default: break; } } }
public Task SendAsync(SmsJob job, bool isLastAttempt, CancellationToken ct) { return(log.ProfileAsync("SendSms", async() => { try { await UpdateAsync(job, ProcessStatus.Attempt); var result = await smsSender.SendAsync(job.PhoneNumber, job.Text, job.Id.ToString(), ct); if (result == SmsResult.Delivered) { await UpdateAsync(job, ProcessStatus.Handled); } } catch (Exception ex) { if (isLastAttempt) { await UpdateAsync(job, ProcessStatus.Failed); } if (ex is DomainException domainException) { await logStore.LogAsync(job.AppId, domainException.Message); } else { throw; } } }));
/// <summary> /// 发送(通知/内容)短信 (暂未实现) /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <SendResult> BatchSend(BatchSendSMSInput input) { //await _captchaValidator.ValidateAsync(input.CaptchaResponse); var result = await _smsSender.SendAsync(input.TargetNumbers, input.Content); return(result); }
public async Task SendTwoFactorAuthCode([FromBody] SendTwoFactorAuthCodeModel model) { var cacheKey = new UserIdentifier(AbpSession.TenantId, model.UserId).ToString(); var cacheItem = await _cacheManager .GetTwoFactorCodeCache() .GetOrDefaultAsync(cacheKey); if (cacheItem == null) { //There should be a cache item added in Authenticate method! This check is needed to prevent sending unwanted two factor code to users. throw new UserFriendlyException(L("SendSecurityCodeErrorMessage")); } var user = await _userManager.FindByIdAsync(model.UserId.ToString()); if (model.Provider != GoogleAuthenticatorProvider.Name) { cacheItem.Code = await _userManager.GenerateTwoFactorTokenAsync(user, model.Provider); var message = L("EmailSecurityCodeBody", cacheItem.Code); if (model.Provider == "Email") { await _emailSender.SendAsync(await _userManager.GetEmailAsync(user), L("EmailSecurityCodeSubject"), message); } else if (model.Provider == "Phone") { await _smsSender.SendAsync(await _userManager.GetPhoneNumberAsync(user), SettingManager.GetSettingValue(AppSettings.SMSManagement.UserIdentityValidateTemplateCode), "{\"code\":\"" + cacheItem.Code + "\"}"); } } _cacheManager.GetTwoFactorCodeCache().Set( cacheKey, cacheItem ); _cacheManager.GetCache("ProviderCache").Set( "Provider", model.Provider ); }
/// <summary> /// 扩展短信接口 /// </summary> /// <param name="smsSender"></param> /// <param name="templateCode">短信模板号</param> /// <param name="phoneNumber">发送手机号</param> /// <param name="templateParams">短信模板参数</param> /// <returns></returns> public static async Task SendAsync(this ISmsSender smsSender, string templateCode, string phoneNumber, IDictionary <string, object> templateParams = null) { var smsMessage = new SmsMessage(phoneNumber, nameof(AliyunSmsSender)); smsMessage.Properties.Add("TemplateCode", templateCode); if (templateParams != null) { smsMessage.Properties.AddIfNotContains(templateParams); } await smsSender.SendAsync(smsMessage); }
public async Task SendVerificationSms(SendVerificationSmsInputDto input) { var code = RandomHelper.GetRandom(100000, 999999).ToString(); var cacheKey = AbpSession.ToUserIdentifier().ToString(); var cacheItem = new SmsVerificationCodeCacheItem { Code = code }; _cacheManager.GetSmsVerificationCodeCache().Set( cacheKey, cacheItem ); await _smsSender.SendAsync(input.PhoneNumber, L("SmsVerificationMessage", code)); }
public async Task SendSmsNotification(string message, string distroListId, EntityHeader org, EntityHeader user) { var distroList = await _distroListRepo.GetDistroListAsync(distroListId); await AuthorizeAsync(distroList, AuthorizeResult.AuthorizeActions.Perform, user, org, "sendEmail"); foreach (var appUser in distroList.AppUsers) { var appUserDetail = await _appuserRepo.FindByIdAsync(appUser.Id); await _smsSender.SendAsync(appUserDetail.PhoneNumber, message); } }
protected override async Task ExecuteAsync(CancellationToken cancellation) { _logger.LogInformation(GetType().Name + " Started."); while (!cancellation.IsCancellationRequested) { try // To make sure the background service keeps running { // When the queue is empty, this goes to sleep until an item is enqueued var(sms, scheduledAt) = await _queue.DequeueAsync(cancellation); // This SMS spent too long in the queue it is considered stale, SmsPollingJob will // (and might have already) pick it up and send it again, so ignore it if (IsStale(scheduledAt)) { _logger.LogWarning($"Stale SMS remained in the {nameof(SmsQueue)} for {(DateTimeOffset.Now - scheduledAt).TotalSeconds} seconds. TenantId = {sms.TenantId}, MessageId = {sms.MessageId}."); continue; } // Begin serializable transaction using var trx = TransactionFactory.Serializable(TransactionScopeOption.RequiresNew); // Update the state first (since this action can be rolled back) var repo = _repoFactory.GetRepository(tenantId: sms.TenantId); await repo.Notifications_Messages__UpdateState(sms.MessageId, MessageState.Dispatched, DateTimeOffset.Now, cancellation : default); // actions that modify state should not use cancellationToken try { // Send the SMS after you update the state in the DB, since sending SMS // is non-transactional and therefore cannot be rolled back await _smsSender.SendAsync(sms, cancellation : default); } catch (Exception ex) { _logger.LogWarning(ex, $"Failed to Dispatch SMS. TenantId = {sms.TenantId}, MessageId = {sms.MessageId}."); // If sending the SMS fails, update the state to DispatchFailed together with the error message await repo.Notifications_Messages__UpdateState(sms.MessageId, MessageState.DispatchFailed, DateTimeOffset.Now, ex.Message, cancellation : default); } trx.Complete(); } catch (TaskCanceledException) { } catch (OperationCanceledException) { } catch (Exception ex) { _logger.LogError(ex, $"Error in {GetType().Name}."); } } }
public async Task <ApiResult> Send(SendSmsInput input) { var returnResult = new ApiResult(); var sendResult = await _smsSender.SendAsync(input.PhoneNumber, input.Text); if (!sendResult) { returnResult.Code = 400; returnResult.Message = ModelState.FirstErrorMessage(); return(returnResult); } returnResult.Code = 200; returnResult.Message = "发送成功"; return(returnResult); }
public async Task SendSms_Test() { var config = _configuration.GetSection("AbpAliyunSms"); // Please fill in the real parameters in the appsettings.json file. if (config["AccessKeyId"] == "<Enter your AccessKeyId from Aliyun>") { return; } var msg = new SmsMessage(config["TargetPhoneNumber"], config["TemplateParam"]); msg.Properties.Add("SignName", config["SignName"]); msg.Properties.Add("TemplateCode", config["TemplateCode"]); await _smsSender.SendAsync(msg); }
public async Task SendVerificationSms() { var user = await GetCurrentUserAsync(); var code = RandomHelper.GetRandom(100000, 999999).ToString(); var cacheKey = AbpSession.ToUserIdentifier().ToString(); var cacheItem = new SmsVerificationCodeCacheItem { Code = code }; //Logger.Debug($"验证码:{code}"); _cacheManager.GetSmsVerificationCodeCache().Set( cacheKey, cacheItem ); await _smsSender.SendAsync(user.PhoneNumber, L("SmsVerificationMessage", code)); }
public async Task SendVerificationSms() { var user = await GetCurrentUserAsync(); var code = RandomHelper.GetRandom(100000, 999999).ToString(); var cacheKey = AbpSession.ToUserIdentifier().ToString(); var cacheItem = new SmsVerificationCodeCacheItem { Code = code }; _cacheManager.GetSmsVerificationCodeCache().Set( cacheKey, cacheItem ); await _smsSender.SendAsync(user.PhoneNumber, SettingManager.GetSettingValue(AppSettings.SMSManagement.UserIdentityValidateTemplateCode), "{\"code\":\"" + code + "\"}"); }
public async Task <ActionResult> SendSecurityCode(SendSecurityCodeViewModel model) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return(RedirectToAction("Login")); } CheckCurrentTenant(await _signInManager.GetVerifiedTenantIdAsync()); if (model.SelectedProvider != GoogleAuthenticatorProvider.Name) { var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); var message = L("EmailSecurityCodeBody", code); if (model.SelectedProvider == "Email") { await _emailSender.SendAsync(await _userManager.GetEmailAsync(user), L("EmailSecurityCodeSubject"), message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendAsync(await _userManager.GetPhoneNumberAsync(user), message); } } return(RedirectToAction( "VerifySecurityCode", new { provider = model.SelectedProvider, returnUrl = model.ReturnUrl, rememberMe = model.RememberMe } )); }
public async Task <InvokeResult> SendSMSCodeAsync(VerfiyPhoneNumber sendSMSCode, EntityHeader orgHeader, EntityHeader userHeader) { if (String.IsNullOrEmpty(sendSMSCode.PhoneNumber)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserVerficationManager_SendSMSCodeAsync", UserAdminErrorCodes.RegMissingEmail.Message); return(InvokeResult.FromErrors(UserAdminErrorCodes.RegMissingPhoneNumber.ToErrorMessage())); } var user = await _userManager.FindByIdAsync(userHeader.Id); if (user == null) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserVerficationManager_SendSMSCodeAsync", "Could not get current user."); return(InvokeResult.FromErrors(UserAdminErrorCodes.AuthCouldNotFindUserAccount.ToErrorMessage())); } try { var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, sendSMSCode.PhoneNumber); var result = await _smsSender.SendAsync(sendSMSCode.PhoneNumber, UserAdminResources.SMS_Verification_Body.Replace("[CODE]", code).Replace("[APP_NAME]", _appConfig.AppName)); _adminLogger.LogInvokeResult("UserVerficationManager_SendSMSCodeAsync", result, new KeyValuePair <string, string>("phone", sendSMSCode.PhoneNumber), new KeyValuePair <string, string>("code", code)); return(result); } catch (Exception ex) { _adminLogger.AddException("UserVerficationManager_SendSMSCodeAsync", ex); return(InvokeResult.FromErrors(UserAdminErrorCodes.RegErrorSendingSMS.ToErrorMessage(), new ErrorMessage() { Message = ex.Message })); } }
public async Task SendTestSms() { await _sms.SendAsync(new TencentCloudSmsMessage("+8618588688087", "广州安华磨具") { Sign = "广州安华磨具", TemplateID = "656176", TemplateParamSet = "德邦物流;20234234" }); }
public async Task <bool> GetMobileValidationCodeAsync(GetMobileValidationCodeInput getMobileValidationCodeInput, ModelStateDictionary modelState) { if (getMobileValidationCodeInput.Type == MobileValidationCodeType.Register) { if (await _manager.IsExistsMobileAsync(getMobileValidationCodeInput.Mobile)) { modelState.AddModelError("Mobile", "手机号码已经被使用"); return(false); } } else if (getMobileValidationCodeInput.Type == MobileValidationCodeType.Login || getMobileValidationCodeInput.Type == MobileValidationCodeType.ChangeMobile) { if (!await _manager.IsExistsMobileAsync(getMobileValidationCodeInput.Mobile)) { modelState.AddModelError("Mobile", "手机号码尚未注册"); return(false); } } string validationCode = null; var cacheKey = MobileValidationCodeCacheKeyFormat.FormatWith(getMobileValidationCodeInput.Mobile); var mobileValidationCode = await _cache.GetJsonAsync <MobileValidationCode>(cacheKey); var now = DateTime.Now; if (mobileValidationCode != null) { if (now - mobileValidationCode.CreationTime < TimeSpan.FromSeconds(_mobileValidationCodeSettings.RequestInterval)) { modelState.AddModelError("Mobile", "请求过于频繁,请稍后再试"); return(false); } if (!mobileValidationCode.ValidationCode.IsNullOrWhiteSpace() && mobileValidationCode.Type == getMobileValidationCodeInput.Type /* 验证码用途未发生更改 */ && mobileValidationCode.ExpirationDate <= now /* 验证码没到期 */ && mobileValidationCode.VerifyTimes < mobileValidationCode.MaxVerifyTimes /* 验证码在合理使用次数内 */) { // 继续沿用之前的验证码 validationCode = mobileValidationCode.ValidationCode; } } if (validationCode == null) { validationCode = GenerateMobileValidationCode(_mobileValidationCodeSettings.CodeLength); mobileValidationCode = new MobileValidationCode { Mobile = getMobileValidationCodeInput.Mobile, Type = getMobileValidationCodeInput.Type, ValidationCode = validationCode, ExpirationDate = now.AddSeconds(_mobileValidationCodeSettings.Expiration), MaxVerifyTimes = _mobileValidationCodeSettings.MaxVerifyTimes, VerifyTimes = 0, FinishVerifyDate = null, CreationTime = now, }; await _cache.SetJsonAsync(cacheKey, mobileValidationCode, new DistributedCacheEntryOptions { SlidingExpiration = TimeSpan.FromSeconds(_mobileValidationCodeSettings.Expiration) }); } var sms = "{\"code\":\"" + validationCode + "\",\"time\":\"" + (_mobileValidationCodeSettings.Expiration / 60) + "\"}"; return(await _smsSender.SendAsync(getMobileValidationCodeInput.Mobile, sms)); }
public async Task SendAsync(IdentityMessage message) { await _smsSender.SendAsync(new SmsMessage(message.Destination, message.Body)); }
private async Task <InvokeResult> SendToUserAsync(UserMessage message) { if (!String.IsNullOrEmpty(message.UserId)) { var getUserResult = await GetUserAsync(message.UserId); if (!getUserResult.Successful) { throw new InvalidDataException("RuntimeController_SendUserMessageAsync", getUserResult.Errors.Select(er => er.Message).ToArray()); } if (String.IsNullOrEmpty(message.Phone)) { message.Phone = getUserResult.Result.Phone; } if (String.IsNullOrEmpty(message.Email)) { message.Email = getUserResult.Result.Email; } } if (String.IsNullOrEmpty(message.Phone) && (message.MessageType == MessageTypes.SMS || message.MessageType == MessageTypes.SMSAndEmail)) { if (String.IsNullOrEmpty(message.UserId)) { throw new InvalidDataException(errors: new string[] { "Did not supply User Id to load user, and phone number was not provided." }); } else { throw new InvalidDataException(errors: new string[] { $"User with id: {message.UserId} does not have a phone number." }); } } if (String.IsNullOrEmpty(message.Email) && (message.MessageType == MessageTypes.Email || message.MessageType == MessageTypes.SMSAndEmail)) { if (String.IsNullOrEmpty(message.UserId)) { throw new InvalidDataException(errors: new string[] { "Did not supply User Id to load user, and email was not provided." }); } else { throw new InvalidDataException(errors: new string[] { $"User with id: {message.UserId} does not have a valid email address." }); } } switch (message.MessageType) { case MessageTypes.Email: if (String.IsNullOrEmpty(message.Body) || String.IsNullOrEmpty(message.Subject)) { throw new InvalidDataException(errors: new string[] { "Body and Subject are required to send an email." }); } await _emailSender.SendAsync(message.Email, message.Subject, message.Body); break; case MessageTypes.SMS: if (String.IsNullOrEmpty(message.Body)) { throw new InvalidDataException(errors: new string[] { "Body is required to send an SMS Message." }); } await _smsSender.SendAsync(message.Phone, message.Body); break; case MessageTypes.SMSAndEmail: if (String.IsNullOrEmpty(message.Body) || String.IsNullOrEmpty(message.Subject)) { throw new InvalidDataException(errors: new string[] { "Body and Subject are required." }); } await _smsSender.SendAsync(message.Phone, message.Body); await _emailSender.SendAsync(message.Email, message.Subject, message.Body); break; } return(InvokeResult.Success); }
public async Task SendAsync(SmsMessage sms, CancellationToken cancellation = default) { await _smsSender.SendAsync(sms, cancellation); }
public async Task <InvokeResult> ClearDeviceExceptionAsync(DeviceException exception, EntityHeader org, EntityHeader user) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } if (org == null) { throw new ArgumentNullException(nameof(org)); } if (user == null) { throw new ArgumentNullException(nameof(user)); } var repo = await _repoManager.GetDeviceRepositoryWithSecretsAsync(exception.DeviceRepositoryId, org, user); var device = await _deviceManager.GetDeviceByIdAsync(repo, exception.DeviceUniqueId, org, user); var deviceConfig = await _deviceConfigManager.GetDeviceConfigurationAsync(device.DeviceConfiguration.Id, org, user); var deviceErrorCode = deviceConfig.ErrorCodes.FirstOrDefault(err => err.Key == exception.ErrorCode); if (deviceErrorCode == null) { return(InvokeResult.FromError($"Could not find error code [{exception.ErrorCode}] on device configuration [{deviceConfig.Name}] for device [{device.Name}]")); } Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("Clear Device Exception."); if (!EntityHeader.IsNullOrEmpty(deviceErrorCode.ServiceTicketTemplate)) { var tickets = await _repo.GetOpenTicketOnDeviceAsync(device.Id, deviceErrorCode.ServiceTicketTemplate.Id, org.Id); foreach (var ticket in tickets) { ticket.IsClosed = true; ticket.ClosedBy = user; await _repo.UpdateServiceTicketAsync(ticket); } } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("No service ticket, skipping."); } if (!EntityHeader.IsNullOrEmpty(deviceErrorCode.DistroList)) { var distroList = await _distroManager.GetListAsync(deviceErrorCode.DistroList.Id, org, user); var subject = "[CLEARED] -" + (String.IsNullOrEmpty(deviceErrorCode.EmailSubject) ? deviceErrorCode.Name : deviceErrorCode.EmailSubject.Replace("[DEVICEID]", device.DeviceId).Replace("[DEVICENAME]", device.Name)); foreach (var notificationUser in distroList.AppUsers) { var appUser = await _userManager.FindByIdAsync(notificationUser.Id); if (deviceErrorCode.SendEmail) { var body = $"The error code [{deviceErrorCode.Key}] was cleared on the device {device.Name}<br>{deviceErrorCode.Description}<br>{exception.Details}"; await _emailSender.SendAsync(appUser.Email, subject, body); } if (deviceErrorCode.SendSMS) { var body = $"Device {device.Name} cleared error code [${deviceErrorCode.Key}] {deviceErrorCode.Description} {exception.Details}"; await _smsSender.SendAsync(appUser.PhoneNumber, body); } } } else { Console.WriteLine("No distro, skipping."); } Console.ResetColor(); return(InvokeResult.Success); }
public async Task SendTestSms(SendTestSmsInput input) { await _smsSender.SendAsync(new SmsMessage(input.Phone, L("TestSms_Body"))); }
/// <summary> /// SendAsync /// </summary> /// <param name="smsSender"></param> /// <param name="phoneNumber"></param> /// <param name="text"></param> /// <returns></returns> public static Task <bool> SendAsync([NotNull] this ISmsSender smsSender, [NotNull] string phoneNumber, [NotNull] string text) { Check.NotNull(smsSender, nameof(smsSender)); return(smsSender.SendAsync(new SmsMessage(phoneNumber, text))); }
private Task SendCodeAsync(string phone, string code) { var message = $"Confirmation code: {code}"; return(_smsSender.SendAsync(phone, message)); }