package smsservice import ( "bytes" "fmt" statuscode "go-admin/common/status_code" "go-admin/config" "io/ioutil" "net/http" "time" "github.com/bytedance/sonic" "github.com/go-admin-team/go-admin-core/logger" ) type GotoneService struct { } func (s *GotoneService) SendSMS(area, phonenumber string, content string) int { type SmsRequest struct { Recipient string `json:"recipient"` // 收件人电话号码 Message string `json:"message"` // 短信内容 SenderId string `json:"sender_id"` // 发送者名称 Type string `json:"type"` } // 创建请求数据 smsRequest := SmsRequest{ Recipient: "+" + area + phonenumber, SenderId: config.ExtConfig.GoToneSmsConfig.SenderId, Message: fmt.Sprintf("欢迎使用 GoTone SMS,高速稳定地发送短信至中国大陆及全球用户,体验验证码:%s。如非本人操作请忽略此信息", content), Type: "plain", } // 将请求数据编码为 JSON requestBody, err := sonic.Marshal(smsRequest) if err != nil { logger.Error("GoToneSms requestBody Error:", err) return statuscode.ServerError } // 创建 HTTP 请求 req, err := http.NewRequest("POST", config.ExtConfig.GoToneSmsConfig.APIEndpoint, bytes.NewBuffer(requestBody)) if err != nil { logger.Error("GoToneSms http.NewRequest Error:", err) return statuscode.ServerError } // 设置请求头 req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+config.ExtConfig.GoToneSmsConfig.Authorization) // 使用 API 密钥进行身份验证 // 创建 HTTP 客户端并发送请求 client := &http.Client{ Timeout: 10 * time.Second, // 设置请求超时时间 } resp, err := client.Do(req) fmt.Println("resp:", resp) if err != nil { logger.Error("GoToneSms do NewRequest Error:", err) return statuscode.CaptchaFailInSend } defer resp.Body.Close() // 检查响应状态 if resp.StatusCode != http.StatusOK { logger.Error("GoToneSms do NewRequest Error:", err) return statuscode.CaptchaFailInSend } // 读取响应体 body, err := ioutil.ReadAll(resp.Body) if err != nil { logger.Error("读取响应体失败:", err) fmt.Printf("响应体: %s", string(body)) return statuscode.CaptchaFailInSend //return fmt.Errorf("读取响应体失败: %v", err) } return statuscode.OK }