fix(代理分销注册): 验证码改为落库成功后消费并细化失败原因
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 12m54s

公开扫码注册原先在审批准备前就消费短信验证码,落库前的任何失败都会烧掉验证码,
客户重试只能得到统一的“分销码不可用”,掩盖了真实失败原因。

- 验证码校验与消费拆分为 CheckCode 与 ConsumeCode,注册记录与审批实例落库成功后才原子消费;
  校验不消费、消费一次性,落库前失败时同一验证码可直接重试
- 分销码无效、所属店铺已停用、上级店铺缺少启用的主账号、验证码错误分别返回各自错误码与提示
- 注册必填字段缺失与请求参数校验失败提示定位到具体字段
- 同步公开接口描述与 agent-distribution-withdrawal 主 Spec 行为契约
This commit is contained in:
2026-09-17 18:01:47 +08:00
parent 398a5e4282
commit e8ab1f471e
7 changed files with 112 additions and 33 deletions

View File

@@ -118,12 +118,20 @@ func (s *Service) SendCode(ctx context.Context, phone string) error {
return nil
}
// VerifyCode 验证验证码
func (s *Service) VerifyCode(ctx context.Context, phone string, code string) error {
codeKey := constants.RedisVerificationCodeKey(phone)
// verificationCodeConsumeScript 原子消费验证码:仅当键值仍等于已校验通过的验证码时删除。
// 并发的两次提交只有一次能消费成功,验证码不会被重复使用。
var verificationCodeConsumeScript = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`)
// CheckCode 校验验证码但不消费。
// 供消费必须晚于业务事实落库的链路复用;不消费时验证码仍受原有 5 分钟有效期约束。
func (s *Service) CheckCode(ctx context.Context, phone string, code string) error {
// 从 Redis 获取验证码
storedCode, err := s.redisClient.Get(ctx, codeKey).Result()
storedCode, err := s.redisClient.Get(ctx, constants.RedisVerificationCodeKey(phone)).Result()
if err == redis.Nil {
s.logger.Warn("验证码不存在或已过期",
zap.String("phone", phone),
@@ -146,15 +154,39 @@ func (s *Service) VerifyCode(ctx context.Context, phone string, code string) err
return errors.New(errors.CodeInvalidParam, "验证码错误")
}
// 验证成功,删除验证码(防止重复使用)
err = s.redisClient.Del(ctx, codeKey).Err()
return nil
}
// ConsumeCode 消费已校验通过的验证码;验证码已失效或已被其它请求消费时返回错误并记录日志。
func (s *Service) ConsumeCode(ctx context.Context, phone string, code string) error {
consumed, err := verificationCodeConsumeScript.Run(
ctx, s.redisClient, []string{constants.RedisVerificationCodeKey(phone)}, code,
).Int64()
if err != nil {
s.logger.Error("删除验证码失败",
s.logger.Error("消费验证码失败",
zap.String("phone", phone),
zap.Error(err),
)
// 这个错误不影响主流程,只记录日志
return errors.Wrap(errors.CodeInternalError, err, "消费验证码失败")
}
if consumed == 0 {
s.logger.Warn("验证码已失效或已被消费",
zap.String("phone", phone),
)
return errors.New(errors.CodeInvalidParam, "验证码已失效或已被消费")
}
return nil
}
// VerifyCode 验证并消费验证码,校验成功即消费。
// 仅适用于失败后必须重新获取验证码的链路;失败可能晚于消费的链路改用 CheckCode 与 ConsumeCode。
func (s *Service) VerifyCode(ctx context.Context, phone string, code string) error {
if err := s.CheckCode(ctx, phone, code); err != nil {
return err
}
// 消费失败不影响主流程ConsumeCode 内部已记录日志,与既有链路保持一致。
_ = s.ConsumeCode(ctx, phone, code)
s.logger.Info("验证码验证成功",
zap.String("phone", phone),