添加阿里云短信服务支持

This commit is contained in:
2025-04-18 17:47:54 +08:00
parent a7e59fb1d7
commit 999d0b0a1d
8 changed files with 234 additions and 27 deletions

View File

@@ -2,14 +2,19 @@ package services
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"math/rand"
"platform/pkg/env"
"platform/pkg/rds"
"platform/pkg/u"
g "platform/web/globals"
"strconv"
"time"
"github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
"github.com/redis/go-redis/v9"
)
@@ -44,9 +49,6 @@ func (s *verifierService) SendSms(ctx context.Context, phone string, purpose Ver
key := smsKey(phone, purpose)
keyLock := key + ":lock"
// 生成验证码
code := rand.Intn(900000) + 100000 // 6-digit code between 100000-999999
// 检查发送频率1 分钟内只能发送一次
err := rds.Client.Watch(ctx, func(tx *redis.Tx) error {
result, err := tx.TTL(ctx, keyLock).Result()
@@ -61,7 +63,6 @@ func (s *verifierService) SendSms(ctx context.Context, phone string, purpose Ver
}
pipe := rds.Client.Pipeline()
pipe.Set(ctx, key, code, 10*time.Minute)
pipe.Set(ctx, keyLock, "", 1*time.Minute)
_, err = pipe.Exec(ctx)
if err != nil {
@@ -73,9 +74,39 @@ func (s *verifierService) SendSms(ctx context.Context, phone string, purpose Ver
return err
}
// TODO: 发送短信验证码
slog.Debug("发送验证码", slog.String("phone", phone), slog.String("code", strconv.Itoa(code)))
// 生成验证码
code := rand.Intn(900000) + 100000 // 6-digit code between 100000-999999
// 发送短信验证码
params, err := json.Marshal(map[string]string{
"code": strconv.Itoa(code),
})
if err != nil {
return err
}
response, err := g.Aliyun.Sms.SendSms(&client.SendSmsRequest{
PhoneNumbers: &phone,
SignName: &env.AliyunSmsSignature,
TemplateCode: &env.AliyunSmsTemplateLogin,
TemplateParam: u.P(string(params)),
})
if err != nil {
_ = rds.Client.Del(ctx, key, keyLock).Err()
return err
}
if response.Body.Code == nil || *response.Body.Code != "OK" {
_ = rds.Client.Del(ctx, key, keyLock).Err()
return VerifierServiceError("验证码发送失败")
}
// 设置验证码
err = rds.Client.Set(ctx, key, code, 5*time.Minute).Err()
if err != nil {
_ = rds.Client.Del(ctx, key, keyLock).Err()
return err
}
slog.Debug("发送验证码", slog.String("phone", phone), slog.String("code", strconv.Itoa(code)))
return nil
}