You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

72 lines
2.6 KiB

package sms
import (
"fmt"
"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
)
func newTencent(options Options) (sys *Tencent, err error) {
sys = &Tencent{options: options}
// 必要步骤:
// 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
credential := common.NewCredential(
options.SecretId, // 替换为你的SecretId
options.SecretKey, // 替换为你的SecretKey
)
// 实例化一个客户端配置对象,可以指定超时时间等配置
cpf := profile.NewClientProfile()
cpf.HttpProfile.ReqMethod = "POST"
cpf.HttpProfile.ReqTimeout = 30
cpf.SignMethod = "HmacSHA1"
// 实例化要请求产品的client对象
sys.client, err = sms.NewClient(credential, "ap-guangzhou", cpf)
return
}
type Tencent struct {
options Options
client *sms.Client
}
// 发送短信验证吗
func (this *Tencent) SendCaptcha(mobile string, captcha string) (err error) {
template, err := pickTemplate(this.options, mobile)
if err != nil {
return
}
// 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
request := sms.NewSendSmsRequest()
// 基本类型的设置。
request.SmsSdkAppId = common.StringPtr(this.options.AppId) // 替换为你的SDK AppID
request.SignName = common.StringPtr(this.options.SignName) // 替换为你的签名
request.TemplateId = common.StringPtr(template) // 替换为你的模板ID
request.PhoneNumberSet = common.StringPtrs([]string{mobile}) // 替换为接收短信的手机号
request.TemplateParamSet = common.StringPtrs([]string{captcha}) // 替换为模板中的参数
// 通过client对象调用想要访问的接口,需要传入请求对象
resp, err := this.client.SendSms(request)
if err != nil {
return
}
// 接口调用成功 ≠ 短信发出去了:签名/模板/号码有问题时 err 为 nil,
// 真实结果在 SendStatusSet[i].Code(成功为 "Ok")。不看它会把失败当成功返回给客户端。
if resp == nil || resp.Response == nil || len(resp.Response.SendStatusSet) == 0 {
return fmt.Errorf("腾讯云短信发送失败: 返回为空")
}
for _, st := range resp.Response.SendStatusSet {
if st == nil || st.Code == nil {
continue
}
if *st.Code != "Ok" {
msg := ""
if st.Message != nil {
msg = *st.Message
}
return fmt.Errorf("腾讯云短信发送失败: %s %s", *st.Code, msg)
}
}
return
}