实现个人客户微信认证和短信验证功能
- 添加个人客户微信登录和手机验证码登录接口 - 实现个人客户设备、ICCID、手机号关联管理 - 添加短信发送服务(HTTP 客户端) - 添加微信认证服务(含 mock 实现) - 添加 JWT Token 生成和验证工具 - 创建数据库迁移脚本(personal_customer 关联表) - 修复测试文件中的路由注册参数错误 - 重构 scripts 目录结构(分离独立脚本到子目录) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
160
pkg/sms/client.go
Normal file
160
pkg/sms/client.go
Normal 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
37
pkg/sms/error.go
Normal 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
51
pkg/sms/http_client.go
Normal 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
82
pkg/sms/types.go
Normal 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 "未知错误"
|
||||
}
|
||||
Reference in New Issue
Block a user