78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package sms
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"errors"
|
|
"fmt"
|
|
"math/big"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// 短信验证码封装
|
|
// 参数未配置时返回 ErrNotConfigured,开发阶段可在日志中输出验证码
|
|
|
|
var ErrNotConfigured = errors.New("短信服务未配置,请联系管理员")
|
|
|
|
type Config struct {
|
|
Provider string
|
|
AccessKey string
|
|
SecretKey string
|
|
SignName string
|
|
TemplateCode string
|
|
}
|
|
|
|
type codeItem struct {
|
|
code string
|
|
expireAt time.Time
|
|
}
|
|
|
|
var (
|
|
store = sync.Map{} // phone -> codeItem
|
|
)
|
|
|
|
// SendCode 发送短信验证码
|
|
// 开发阶段(未配置短信服务商):验证码输出到日志,方便测试
|
|
func SendCode(cfg Config, phone string) (string, error) {
|
|
code := generateCode()
|
|
|
|
if cfg.AccessKey == "" || cfg.SecretKey == "" || cfg.SignName == "" || cfg.TemplateCode == "" {
|
|
// 未配置短信服务商,开发模式:日志输出验证码
|
|
fmt.Printf("[SMS-DEV] 手机号 %s 的验证码: %s (5分钟有效)\n", phone, code)
|
|
store.Store(phone, codeItem{code: code, expireAt: time.Now().Add(5 * time.Minute)})
|
|
return code, nil
|
|
}
|
|
|
|
// TODO: 接入阿里云/腾讯云短信 SDK
|
|
// 阿里云:dysmsapi.Client + SendSmsRequest
|
|
// 腾讯云:sms.Client + SendSms
|
|
store.Store(phone, codeItem{code: code, expireAt: time.Now().Add(5 * time.Minute)})
|
|
return code, nil
|
|
}
|
|
|
|
// VerifyCode 校验短信验证码(一次性)
|
|
func VerifyCode(phone, code string) bool {
|
|
if phone == "" || code == "" {
|
|
return false
|
|
}
|
|
v, ok := store.Load(phone)
|
|
if !ok {
|
|
return false
|
|
}
|
|
item := v.(codeItem)
|
|
store.Delete(phone)
|
|
if time.Now().After(item.expireAt) {
|
|
return false
|
|
}
|
|
return item.code == code
|
|
}
|
|
|
|
func generateCode() string {
|
|
b := make([]byte, 6)
|
|
for i := range b {
|
|
n, _ := rand.Int(rand.Reader, big.NewInt(10))
|
|
b[i] = byte('0' + n.Int64())
|
|
}
|
|
return string(b)
|
|
}
|