实现个人客户微信认证和短信验证功能

- 添加个人客户微信登录和手机验证码登录接口
- 实现个人客户设备、ICCID、手机号关联管理
- 添加短信发送服务(HTTP 客户端)
- 添加微信认证服务(含 mock 实现)
- 添加 JWT Token 生成和验证工具
- 创建数据库迁移脚本(personal_customer 关联表)
- 修复测试文件中的路由注册参数错误
- 重构 scripts 目录结构(分离独立脚本到子目录)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-10 11:42:38 +08:00
parent 1b9080e3ab
commit 9c6d4a3bd4
53 changed files with 4258 additions and 97 deletions

72
pkg/auth/jwt.go Normal file
View File

@@ -0,0 +1,72 @@
package auth
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
// PersonalCustomerClaims 个人客户 JWT Claims
type PersonalCustomerClaims struct {
CustomerID uint `json:"customer_id"` // 个人客户 ID
Phone string `json:"phone"` // 手机号
jwt.RegisteredClaims
}
// JWTManager JWT 管理器
type JWTManager struct {
secretKey string
tokenDuration time.Duration
}
// NewJWTManager 创建 JWT 管理器
func NewJWTManager(secretKey string, tokenDuration time.Duration) *JWTManager {
return &JWTManager{
secretKey: secretKey,
tokenDuration: tokenDuration,
}
}
// GeneratePersonalCustomerToken 生成个人客户 Token
func (m *JWTManager) GeneratePersonalCustomerToken(customerID uint, phone string) (string, error) {
claims := &PersonalCustomerClaims{
CustomerID: customerID,
Phone: phone,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(m.tokenDuration)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(m.secretKey))
if err != nil {
return "", fmt.Errorf("生成 Token 失败: %w", err)
}
return tokenString, nil
}
// VerifyPersonalCustomerToken 验证个人客户 Token
func (m *JWTManager) VerifyPersonalCustomerToken(tokenString string) (*PersonalCustomerClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &PersonalCustomerClaims{}, func(token *jwt.Token) (interface{}, error) {
// 验证签名算法
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(m.secretKey), nil
})
if err != nil {
return nil, fmt.Errorf("Token 解析失败: %w", err)
}
claims, ok := token.Claims.(*PersonalCustomerClaims)
if !ok || !token.Valid {
return nil, fmt.Errorf("Token 无效")
}
return claims, nil
}

View File

@@ -18,6 +18,8 @@ type Config struct {
Queue QueueConfig `mapstructure:"queue"`
Logging LoggingConfig `mapstructure:"logging"`
Middleware MiddlewareConfig `mapstructure:"middleware"`
SMS SMSConfig `mapstructure:"sms"`
JWT JWTConfig `mapstructure:"jwt"`
}
// ServerConfig HTTP 服务器配置
@@ -94,6 +96,21 @@ type RateLimiterConfig struct {
Storage string `mapstructure:"storage"` // "memory" 或 "redis"
}
// SMSConfig 短信服务配置
type SMSConfig struct {
GatewayURL string `mapstructure:"gateway_url"` // 短信网关地址
Username string `mapstructure:"username"` // 账号用户名
Password string `mapstructure:"password"` // 账号密码
Signature string `mapstructure:"signature"` // 短信签名(例如:【签名】)
Timeout time.Duration `mapstructure:"timeout"` // 请求超时时间
}
// JWTConfig JWT 认证配置
type JWTConfig struct {
SecretKey string `mapstructure:"secret_key"` // JWT 签名密钥
TokenDuration time.Duration `mapstructure:"token_duration"` // Token 有效期
}
// Validate 验证配置值
func (c *Config) Validate() error {
// 服务器验证
@@ -158,6 +175,34 @@ func (c *Config) Validate() error {
return fmt.Errorf("invalid configuration: middleware.rate_limiter.storage: invalid storage type (current value: %s, expected: memory or redis)", c.Middleware.RateLimiter.Storage)
}
// 短信服务验证
if c.SMS.GatewayURL == "" {
return fmt.Errorf("invalid configuration: sms.gateway_url: must be non-empty (current value: empty)")
}
if c.SMS.Username == "" {
return fmt.Errorf("invalid configuration: sms.username: must be non-empty (current value: empty)")
}
if c.SMS.Password == "" {
return fmt.Errorf("invalid configuration: sms.password: must be non-empty (current value: empty)")
}
if c.SMS.Signature == "" {
return fmt.Errorf("invalid configuration: sms.signature: must be non-empty (current value: empty)")
}
if c.SMS.Timeout < 5*time.Second || c.SMS.Timeout > 60*time.Second {
return fmt.Errorf("invalid configuration: sms.timeout: duration out of range (current value: %s, expected: 5s-60s)", c.SMS.Timeout)
}
// JWT 验证
if c.JWT.SecretKey == "" {
return fmt.Errorf("invalid configuration: jwt.secret_key: must be non-empty (current value: empty)")
}
if len(c.JWT.SecretKey) < 32 {
return fmt.Errorf("invalid configuration: jwt.secret_key: secret key too short (current length: %d, expected: >= 32)", len(c.JWT.SecretKey))
}
if c.JWT.TokenDuration < 1*time.Hour || c.JWT.TokenDuration > 720*time.Hour {
return fmt.Errorf("invalid configuration: jwt.token_duration: duration out of range (current value: %s, expected: 1h-720h)", c.JWT.TokenDuration)
}
return nil
}

View File

@@ -106,3 +106,10 @@ const (
const (
MaxShopLevel = 7 // 店铺最大层级
)
// 验证码配置常量
const (
VerificationCodeLength = 6 // 验证码长度6位数字
VerificationCodeExpiration = 5 * time.Minute // 验证码过期时间5分钟
VerificationCodeRateLimit = 60 * time.Second // 验证码发送频率限制60秒
)

View File

@@ -39,3 +39,17 @@ func RedisAccountSubordinatesKey(accountID uint) string {
func RedisShopSubordinatesKey(shopID uint) string {
return fmt.Sprintf("shop:subordinates:%d", shopID)
}
// RedisVerificationCodeKey 生成验证码的 Redis 键
// 用途:存储手机验证码
// 过期时间5 分钟
func RedisVerificationCodeKey(phone string) string {
return fmt.Sprintf("verification:code:%s", phone)
}
// RedisVerificationCodeLimitKey 生成验证码发送频率限制的 Redis 键
// 用途:限制验证码发送频率
// 过期时间60 秒
func RedisVerificationCodeLimitKey(phone string) string {
return fmt.Sprintf("verification:limit:%s", phone)
}

160
pkg/sms/client.go Normal file
View File

@@ -0,0 +1,160 @@
package sms
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"time"
"github.com/bytedance/sonic"
"go.uber.org/zap"
)
// Client 短信客户端
type Client struct {
gatewayURL string // 短信网关地址
username string // 账号用户名
password string // 账号密码
signature string // 短信签名
timeout time.Duration // 请求超时时间
logger *zap.Logger // 日志记录器
httpClient HTTPClient // HTTP 客户端接口
}
// HTTPClient HTTP 客户端接口(便于测试)
type HTTPClient interface {
Post(ctx context.Context, url string, body []byte) ([]byte, error)
}
// NewClient 创建短信客户端
func NewClient(gatewayURL, username, password, signature string, timeout time.Duration, logger *zap.Logger, httpClient HTTPClient) *Client {
return &Client{
gatewayURL: gatewayURL,
username: username,
password: password,
signature: signature,
timeout: timeout,
logger: logger,
httpClient: httpClient,
}
}
// SendMessage 发送短信
// content: 短信内容(不包含签名,签名会自动添加)
// phones: 接收手机号列表
func (c *Client) SendMessage(ctx context.Context, content string, phones []string) (*SendResponse, error) {
// 生成时间戳(毫秒)
timestamp := time.Now().UnixMilli()
// 计算签名
sign := c.calculateSign(timestamp)
// 构造完整的短信内容(添加签名)
fullContent := c.signature + content
// 构造请求
req := &SendRequest{
UserName: c.username,
Content: fullContent,
PhoneList: phones,
Timestamp: timestamp,
Sign: sign,
}
// 序列化请求
reqBody, err := sonic.Marshal(req)
if err != nil {
c.logger.Error("序列化短信请求失败",
zap.Error(err),
zap.Strings("phones", phones),
)
return nil, fmt.Errorf("序列化短信请求失败: %w", err)
}
// 记录请求日志(脱敏处理)
c.logger.Info("发送短信请求",
zap.Strings("phones", phones),
zap.String("content_preview", c.truncateContent(content)),
zap.Int64("timestamp", timestamp),
)
// 发送请求
url := c.gatewayURL + "/api/sendMessageMass"
// 创建带超时的上下文
reqCtx, cancel := context.WithTimeout(ctx, c.timeout)
defer cancel()
respBody, err := c.httpClient.Post(reqCtx, url, reqBody)
if err != nil {
c.logger.Error("发送短信请求失败",
zap.Error(err),
zap.String("url", url),
zap.Strings("phones", phones),
)
return nil, fmt.Errorf("发送短信请求失败: %w", err)
}
// 解析响应
var resp SendResponse
if err := sonic.Unmarshal(respBody, &resp); err != nil {
c.logger.Error("解析短信响应失败",
zap.Error(err),
zap.ByteString("response_body", respBody),
)
return nil, fmt.Errorf("解析短信响应失败: %w", err)
}
// 记录响应日志
if resp.Code == CodeSuccess {
c.logger.Info("短信发送成功",
zap.Int64("msg_id", resp.MsgID),
zap.Int("sms_count", resp.SMSCount),
zap.Strings("phones", phones),
)
} else {
c.logger.Warn("短信发送失败",
zap.Int("code", resp.Code),
zap.String("message", resp.Message),
zap.Strings("phones", phones),
)
}
// 检查响应状态
if resp.Code != CodeSuccess {
return &resp, NewSMSError(resp.Code, resp.Message)
}
return &resp, nil
}
// calculateSign 计算签名
// 规则: MD5(userName + timestamp + MD5(password))
func (c *Client) calculateSign(timestamp int64) string {
// 第一步:计算 MD5(password)
passwordMD5 := c.md5Hash(c.password)
// 第二步:组合字符串
combined := fmt.Sprintf("%s%d%s", c.username, timestamp, passwordMD5)
// 第三步:计算最终签名
return c.md5Hash(combined)
}
// md5Hash 计算 MD5 哈希值(小写)
func (c *Client) md5Hash(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
// truncateContent 截断内容用于日志记录
func (c *Client) truncateContent(content string) string {
const maxLen = 50
runes := []rune(content)
if len(runes) > maxLen {
return string(runes[:maxLen]) + "..."
}
return content
}

37
pkg/sms/error.go Normal file
View File

@@ -0,0 +1,37 @@
package sms
import "fmt"
// SMSError 短信服务错误
type SMSError struct {
Code int // 错误码
Message string // 错误消息
}
// Error 实现 error 接口
func (e *SMSError) Error() string {
return fmt.Sprintf("SMS error (code=%d): %s", e.Code, e.Message)
}
// NewSMSError 创建短信服务错误
func NewSMSError(code int, message string) *SMSError {
return &SMSError{
Code: code,
Message: message,
}
}
// IsInsufficientBalance 判断是否为余额不足错误
func (e *SMSError) IsInsufficientBalance() bool {
return e.Code == CodeInsufficientBalance
}
// IsAuthError 判断是否为认证错误
func (e *SMSError) IsAuthError() bool {
return e.Code == CodeAuthFailed || e.Code == CodeAccountLocked || e.Code == CodeBusinessNotOpened
}
// IsTimestampError 判断是否为时间戳错误
func (e *SMSError) IsTimestampError() bool {
return e.Code == CodeTimestampError
}

51
pkg/sms/http_client.go Normal file
View File

@@ -0,0 +1,51 @@
package sms
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
)
// StandardHTTPClient 标准 HTTP 客户端实现
type StandardHTTPClient struct {
client *http.Client
}
// NewStandardHTTPClient 创建标准 HTTP 客户端
func NewStandardHTTPClient(timeout int) *StandardHTTPClient {
return &StandardHTTPClient{
client: &http.Client{
Timeout: 0, // 使用 context 控制超时
},
}
}
// Post 发送 POST 请求
func (s *StandardHTTPClient) Post(ctx context.Context, url string, body []byte) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
}
req.Header.Set("Content-Type", "application/json;charset=utf-8")
req.Header.Set("Accept", "application/json")
resp, err := s.client.Do(req)
if err != nil {
return nil, fmt.Errorf("发送 HTTP 请求失败: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取响应失败: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP 状态码异常: %d, 响应: %s", resp.StatusCode, string(respBody))
}
return respBody, nil
}

82
pkg/sms/types.go Normal file
View File

@@ -0,0 +1,82 @@
package sms
// SendRequest 短信发送请求
type SendRequest struct {
UserName string `json:"userName"` // 账号用户名
Content string `json:"content"` // 短信内容(直接发送内容,不使用模板)
PhoneList []string `json:"phoneList"` // 发送手机号码列表
Timestamp int64 `json:"timestamp"` // 当前时间戳(毫秒)
Sign string `json:"sign"` // 签名MD5(userName + timestamp + MD5(password))
}
// SendResponse 短信发送响应
type SendResponse struct {
Code int `json:"code"` // 处理结果0为成功其他失败
Message string `json:"message"` // 处理结果描述
MsgID int64 `json:"msgId"` // 消息ID当code=0时返回
SMSCount int `json:"smsCount"` // 消耗计费总数当code=0时返回
}
// 错误码常量
const (
CodeSuccess = 0 // 处理成功
CodeEmptyUserName = 1 // 帐号名为空
CodeAuthFailed = 2 // 帐号名或密码鉴权错误
CodeAccountLocked = 3 // 帐号已被锁定
CodeBusinessNotOpened = 4 // 此帐号业务未开通
CodeInsufficientBalance = 5 // 帐号余额不足
CodeMissingPhoneNumbers = 6 // 缺少发送号码
CodeTooManyPhoneNumbers = 7 // 超过最大发送号码数
CodeEmptyContent = 8 // 发送消息内容为空
CodeInvalidIP = 10 // 非法的IP地址
CodeTimeLimitRestriction = 11 // 24小时发送时间段限制
CodeInvalidScheduledTime = 12 // 定时发送时间错误或超过15天
CodeTooFrequent = 13 // 请求过于频繁
CodeInvalidExtCode = 14 // 错误的用户扩展码
CodeTimestampError = 16 // 时间戳差异过大
CodeNotRealNameAuthenticated = 18 // 帐号未进行实名认证
CodeReceiptNotEnabled = 19 // 帐号未开放回执状态
CodeMissingParameters = 22 // 缺少必填参数
CodeDuplicateUserName = 23 // 用户帐号名重复
CodeNoSignatureRestriction = 24 // 用户无签名限制
CodeSignatureMissingBrackets = 25 // 签名需要包含【】符
CodeInvalidContentType = 98 // HTTP Content-Type错误
CodeInvalidJSON = 99 // 错误的请求JSON字符串
CodeSystemError = 500 // 系统异常
)
// 错误码到中文消息的映射
var errorMessages = map[int]string{
CodeSuccess: "处理成功",
CodeEmptyUserName: "帐号名为空",
CodeAuthFailed: "帐号名或密码鉴权错误",
CodeAccountLocked: "帐号已被锁定",
CodeBusinessNotOpened: "此帐号业务未开通",
CodeInsufficientBalance: "帐号余额不足",
CodeMissingPhoneNumbers: "缺少发送号码",
CodeTooManyPhoneNumbers: "超过最大发送号码数",
CodeEmptyContent: "发送消息内容为空",
CodeInvalidIP: "非法的IP地址",
CodeTimeLimitRestriction: "24小时发送时间段限制",
CodeInvalidScheduledTime: "定时发送时间错误或超过15天",
CodeTooFrequent: "请求过于频繁",
CodeInvalidExtCode: "错误的用户扩展码",
CodeTimestampError: "时间戳差异过大与系统时间误差不得超过5分钟",
CodeNotRealNameAuthenticated: "帐号未进行实名认证",
CodeReceiptNotEnabled: "帐号未开放回执状态",
CodeMissingParameters: "缺少必填参数",
CodeDuplicateUserName: "用户帐号名重复",
CodeNoSignatureRestriction: "用户无签名限制",
CodeSignatureMissingBrackets: "签名需要包含【】符",
CodeInvalidContentType: "HTTP Content-Type错误",
CodeInvalidJSON: "错误的请求JSON字符串",
CodeSystemError: "系统异常",
}
// GetErrorMessage 获取错误码对应的错误消息
func GetErrorMessage(code int) string {
if msg, ok := errorMessages[code]; ok {
return msg
}
return "未知错误"
}

25
pkg/wechat/mock.go Normal file
View File

@@ -0,0 +1,25 @@
package wechat
import (
"context"
"fmt"
)
// MockService Mock 微信服务实现(用于开发和测试)
type MockService struct{}
// NewMockService 创建 Mock 微信服务
func NewMockService() *MockService {
return &MockService{}
}
// GetUserInfo Mock 实现:通过授权码获取用户信息
// 注意:这是一个 Mock 实现,实际生产环境需要对接微信 OAuth API
func (s *MockService) GetUserInfo(ctx context.Context, code string) (string, string, error) {
// TODO: 实际实现需要调用微信 OAuth2.0 接口
// 1. 使用 code 换取 access_token
// 2. 使用 access_token 获取用户信息
// 参考文档: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
return "", "", fmt.Errorf("微信服务暂未实现,待对接微信 SDK")
}

21
pkg/wechat/wechat.go Normal file
View File

@@ -0,0 +1,21 @@
package wechat
import "context"
// Service 微信服务接口
type Service interface {
// GetUserInfo 通过授权码获取用户信息
GetUserInfo(ctx context.Context, code string) (openID, unionID string, err error)
}
// UserInfo 微信用户信息
type UserInfo struct {
OpenID string `json:"open_id"` // 微信 OpenID
UnionID string `json:"union_id"` // 微信 UnionID开放平台统一ID
Nickname string `json:"nickname"` // 昵称
Avatar string `json:"avatar"` // 头像URL
Sex int `json:"sex"` // 性别 0-未知 1-男 2-女
Province string `json:"province"` // 省份
City string `json:"city"` // 城市
Country string `json:"country"` // 国家
}