Files
bdqr-server/app/main/api/internal/service/tencentCloudService.go

72 lines
2.5 KiB
Go
Raw Normal View History

2026-01-14 16:37:52 +08:00
package service
import (
"bdqr-server/app/main/api/internal/config"
"strings"
"github.com/pkg/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111" //引入sms
)
type TencentCloudService struct {
config config.Config
TencentSmsClient *sms.Client
}
func NewTencentCloudService(config config.Config) *TencentCloudService {
credential := common.NewCredential(
config.TencentCloud.SecretId,
config.TencentCloud.SecretKey,
)
cpf := profile.NewClientProfile()
cpf.HttpProfile.ReqMethod = "POST"
cpf.HttpProfile.ReqTimeout = 10 // 请求超时时间,单位为秒(默认60秒)
/* 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"
/* SDK 默认用 TC3-HMAC-SHA256 进行签名,非必要请不要修改该字段 */
cpf.SignMethod = "HmacSHA1"
cpf.Debug = true
/* 实例化 SMS client 对象
* 第二个参数是地域信息可以直接填写字符串 ap-guangzhou或者引用预设的常量 */
client, err := sms.NewClient(credential, "ap-guangzhou", cpf)
if err != nil {
panic(err)
}
return &TencentCloudService{
config: config,
TencentSmsClient: client,
}
}
// SendVerificationCode 发送验证码短信
func (t *TencentCloudService) SendVerificationCode(mobile, code string) error {
// 判断手机号是否以+86开头如果没有则自动添加
if !strings.HasPrefix(mobile, "+86") {
mobile = "+86" + mobile
}
request := &sms.SendSmsRequest{}
request.SmsSdkAppId = common.StringPtr(t.config.TencentCloud.SmsSdkAppId)
request.SignName = common.StringPtr(t.config.TencentCloud.SignName)
request.TemplateParamSet = common.StringPtrs([]string{code})
request.TemplateId = common.StringPtr(t.config.TencentCloud.TemplateId)
request.PhoneNumberSet = common.StringPtrs([]string{mobile})
response, err := t.TencentSmsClient.SendSms(request)
if err != nil {
return errors.Wrapf(err, "调用腾讯云短信服务失败")
}
if len(response.Response.SendStatusSet) == 0 {
return errors.New("腾讯云短信服务返回空响应")
}
if *response.Response.SendStatusSet[0].Code != "Ok" {
return errors.Errorf("腾讯云短信服务响应失败: %s", *response.Response.SendStatusSet[0].Message)
}
return nil
}