74 lines
2.1 KiB
Go
74 lines
2.1 KiB
Go
package sms
|
|
|
|
// SMS短信服务
|
|
import (
|
|
"encoding/json"
|
|
"git.echol.cn/loser/lckt/global"
|
|
"github.com/alibabacloud-go/tea/tea"
|
|
"go.uber.org/zap"
|
|
|
|
util "github.com/alibabacloud-go/tea-utils/v2/service"
|
|
|
|
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
|
dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
|
|
)
|
|
|
|
type message struct {
|
|
Code string `json:"code"`
|
|
}
|
|
|
|
func SendSMS(phone string, code string) bool {
|
|
// 从配置中获取阿里云短信配置
|
|
aliyunConfig := global.GVA_CONFIG.SMS
|
|
|
|
clientConfig := &openapi.Config{
|
|
AccessKeyId: tea.String(aliyunConfig.AccessKeyID),
|
|
AccessKeySecret: tea.String(aliyunConfig.AccessKeySecret),
|
|
Endpoint: tea.String("dysmsapi.aliyuncs.com"),
|
|
RegionId: tea.String("cn-hangzhou"), // 添加区域配置
|
|
}
|
|
|
|
smsClient, err := dysmsapi.NewClient(clientConfig)
|
|
if err != nil {
|
|
global.GVA_LOG.Error("创建短信客户端失败", zap.Error(err))
|
|
return false
|
|
}
|
|
mes := message{Code: code}
|
|
templateParam, err := json.Marshal(mes)
|
|
if err != nil {
|
|
global.GVA_LOG.Error("模板参数序列化失败", zap.Error(err))
|
|
return false
|
|
}
|
|
|
|
sendSmsRequest := &dysmsapi.SendSmsRequest{
|
|
PhoneNumbers: tea.String(phone),
|
|
SignName: tea.String(aliyunConfig.SignName),
|
|
TemplateCode: tea.String(aliyunConfig.TemplateCode),
|
|
TemplateParam: tea.String(string(templateParam)),
|
|
}
|
|
|
|
// 添加更多的运行时选项
|
|
runtime := &util.RuntimeOptions{
|
|
ReadTimeout: tea.Int(5000),
|
|
ConnectTimeout: tea.Int(5000),
|
|
}
|
|
|
|
response, err := smsClient.SendSmsWithOptions(sendSmsRequest, runtime)
|
|
if err != nil {
|
|
global.GVA_LOG.Error("发送短信失败", zap.Error(err))
|
|
return false
|
|
}
|
|
|
|
if response.Body == nil || *response.Body.Code != "OK" {
|
|
if response.Body != nil {
|
|
global.GVA_LOG.Error("服务商返回错误", zap.Any("resp", *response.Body.Message))
|
|
} else {
|
|
global.GVA_LOG.Error("服务商返回错误", zap.String("resp", "response body is nil"))
|
|
}
|
|
return false
|
|
}
|
|
|
|
global.GVA_LOG.Info("短信[阿里云]", zap.String("发送成功", "手机号: "+phone))
|
|
return true
|
|
}
|