This commit is contained in:
zpc 2025-04-24 01:45:31 +08:00
parent af397d25c8
commit 21e571e237
2 changed files with 54 additions and 13 deletions

View File

@ -53,8 +53,6 @@ public class SMSBLL : ChouBoxCodeBase
var dailyCountKey = $"VerificationCodeDailyCount:{phone}:{DateTime.Now:yyyyMMdd}";
var dailyCount = RedisCache.StringGet<int?>(dailyCountKey) ?? 0;
// 获取重试次数
var retryCountKey = $"VerificationCode:{phone}{RETRY_COUNT_SUFFIX}";
var retryCount = RedisCache.StringGet<int?>(retryCountKey) ?? 0;
@ -103,18 +101,26 @@ public class SMSBLL : ChouBoxCodeBase
try
{
TencentSMSSendVerificationCode tencentSMSSendVerificationCode = new TencentSMSSendVerificationCode(smsConfig, phone);
bool smsSucceeded = true;
string errorMessage = "验证码发送失败";
try
{
var result = await tencentSMSSendVerificationCode.SendVerificationCode(verificationCode.ToString(), 5);
if (!result)
{
smsSucceeded = false;
}
}
catch (Exception smsEx)
{
smsSucceeded = false;
errorMessage = smsEx.Message;
// 记录发送失败日志
Logger.LogError($"验证码发送失败,手机号:{phone}IP{ipAddress}");
throw new CustomException("验证码发送失败");
Logger.LogError($"验证码发送异常,手机号:{phone}IP{ipAddress},错误:{smsEx.Message}");
}
// 发送成功存入Redis5分钟有效期
await RedisCache.StringSetAsync(redisKey, verificationCode.ToString(), TimeSpan.FromMinutes(5));
// 更新重试次数和锁定时间
// 无论成功失败都更新重试次数和锁定时间
retryCount++;
var nextWaitSeconds = GetWaitSeconds(retryCount);
@ -130,6 +136,15 @@ public class SMSBLL : ChouBoxCodeBase
var expireTime = endOfDay - DateTime.Now;
await RedisCache.StringSetAsync(dailyCountKey, dailyCount.ToString(), expireTime);
// 如果短信发送失败,抛出异常
if (!smsSucceeded)
{
throw new CustomException(errorMessage);
}
// 发送成功存入Redis5分钟有效期
await RedisCache.StringSetAsync(redisKey, verificationCode.ToString(), TimeSpan.FromMinutes(5));
// 保存到数据库
var verificationRecord = new UserVerificationCodes
{

View File

@ -124,12 +124,39 @@ public class TencentSMSSendVerificationCode(TencentSMSConfig tencentSMSConfig, s
Console.WriteLine(AbstractModel.ToJsonString(resp));
// 检查短信发送状态
if (resp.SendStatusSet != null && resp.SendStatusSet.Length > 0)
{
foreach (var status in resp.SendStatusSet)
{
if (status.Code != "Ok")
{
// 检查特定错误码并提供更友好的错误信息
if (status.Code == "LimitExceeded.PhoneNumberSameContentDailyLimit" || status.Code == "LimitExceeded.PhoneNumberDailyLimit")
{
throw new Exception($"您的手机号今日接收该内容的短信次数已达上限,请明天再试");
}
else if (status.Code == "LimitExceeded.PhoneNumberThirtySecondLimit")
{
throw new Exception($"您的手机号短信请求过于频繁请30秒后再试");
}
else
{
throw new Exception($"短信发送失败:手机号 {status.PhoneNumber},错误代码 {status.Code},错误信息 {status.Message}");
}
}
}
}
else
{
throw new Exception("短信发送失败:未收到发送状态");
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
throw; // 重新抛出异常而不是返回false
}
//Console.Read();
return true;
@ -137,4 +164,3 @@ public class TencentSMSSendVerificationCode(TencentSMSConfig tencentSMSConfig, s
}
}