/// <summary> /// 验证短信验证码 /// </summary> /// <param name="msgCaptchaDto">短信验证码信息</param> /// <returns></returns> public (bool, string) ValidateMsgCaptcha(MsgCaptchaDto msgCaptchaDto) { var key = $"MsgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}"; var cachedMsgCaptcha = _cache.Get <MsgCaptchaDto>(key); if (cachedMsgCaptcha == null) { return(false, "短信验证码无效,请重新获取"); } if (cachedMsgCaptcha.ValidateCount >= 3) { _cache.Remove(key); return(false, "短信验证码已失效,请重新获取"); } cachedMsgCaptcha.ValidateCount++; if (!string.Equals(cachedMsgCaptcha.MsgCaptcha, msgCaptchaDto.MsgCaptcha, StringComparison.OrdinalIgnoreCase)) { return(false, "短信验证码错误"); } else { return(true, "验证通过"); } }
public IActionResult ValidateMsgCaptcha(MsgCaptchaDto msgCaptchaDto) { var validateResult = _captchaService.ValidateMsgCaptcha(msgCaptchaDto); if (validateResult.Item1) { return(Ok(validateResult.Item2)); } else { return(StatusCode(StatusCodes.Status403Forbidden, validateResult.Item2)); } }
public IActionResult GetMsgCaptcha([FromQuery] MsgCaptchaDto msgCaptchaDto) { var msgSendResult = _captchaService.GetMsgCaptcha(msgCaptchaDto); if (msgSendResult.Item1) { return(Ok(msgSendResult.Item2)); } else { return(StatusCode(StatusCodes.Status403Forbidden, msgSendResult.Item2)); } }
/// <summary> /// 获取短信验证码 /// </summary> /// <param name="msgCaptchaDto">短信验证码请求信息</param> /// <returns></returns> public (bool, string) GetMsgCaptcha(MsgCaptchaDto msgCaptchaDto) { if (string.IsNullOrWhiteSpace(msgCaptchaDto.ImgCaptcha)) { throw new BusinessException((int)ErrorCode.BadRequest, "请输入图形验证码"); } var cachedImageCaptcha = _cache.Get <string>($"ImgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}"); if (!string.Equals(msgCaptchaDto.ImgCaptcha, cachedImageCaptcha, StringComparison.OrdinalIgnoreCase)) { return(false, "验证失败,请输入正确手机号及获取到的图形验证码"); } string key = $"MsgCaptcha{msgCaptchaDto.MsgCaptchaType}{msgCaptchaDto.Mobile}"; var cachedMsgCaptcha = _cache.Get <MsgCaptchaDto>(key); if (cachedMsgCaptcha != null) { var offsetSecionds = (DateTime.Now - cachedMsgCaptcha.CreateTime).Seconds; if (offsetSecionds < 60) { return(false, $"短信验证码获取太频繁,请{60 - offsetSecionds}秒之后再获取"); } } var msgCaptcha = MsgCaptchaHelper.CreateRandomNumber(6); msgCaptchaDto.MsgCaptcha = msgCaptcha; msgCaptchaDto.CreateTime = DateTime.Now; msgCaptchaDto.ValidateCount = 0; _cache.Set(key, msgCaptchaDto, TimeSpan.FromMinutes(2)); if (_hostingEnvironment.IsProduction()) { //TODO:调用第三方SDK实际发送短信 return(true, "发送成功"); } else //非生产环境,直接将验证码返给前端,便于调查跟踪 { return(true, $"发送成功,短信验证码为:{msgCaptcha}"); } }