您好,关于您的问题,我可以为您提供以下代码示例:
package tencentcloud
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
)
const (
SMSAction = "SendSms" // 发送短信动作
SMSSign = "" // 短信签名
)
type TencentCloud struct {
AppID string // 腾讯云应用 ID
SecretID string // 腾讯云 SecretId
SecretKey string // 腾讯云 SecretKey
}
// NewTencentCloud 新建腾讯云实例
func NewTencentCloud(appid, secretid, secretkey string) *TencentCloud {
return &TencentCloud{
AppID: appid,
SecretID: secretid,
SecretKey: secretkey,
}
}
// SendSMS 发送短信
func (tc *TencentCloud) SendSMS(mobiles []string, templateID int, params []string) error {
u := url.Values{}
u.Set("Action", SMSAction)
u.Set("Version", "2019-07-11")
u.Set("Region", "ap-guangzhou")
u.Set("Timestamp", fmt.Sprintf("%d", time.Now().Unix()))
u.Set("Nonce", fmt.Sprintf("%d", time.Now().UnixNano()))
u.Set("PhoneNumberSet.0", strings.Join(mobiles, ","))
u.Set("TemplateParamSet.0", strings.Join(params, ","))
u.Set("TemplateID", fmt.Sprintf("%d", templateID))
u.Set("Sign", SMSSign)
keys := make([]string, 0, len(u))
for k := range u {
keys = append(keys, k)
}
sort.Strings(keys)
var query string
for _, key := range keys {
query += "&" + key + "=" + u.Get(key)
}
stringToSign := "GETsms.tencentcloudapi.com/?" + query[1:]
hmacDigest := hmac.New(sha1.New, []byte(tc.SecretKey))
hmacDigest.Write([]byte(stringToSign))
signatureBytes := hmacDigest.Sum(nil)
signatureBase64 := base64.StdEncoding.EncodeToString(signatureBytes)
finalURL := fmt.Sprintf("https://sms.tencentcloudapi.com/?%s&Signature=%s",
query[1:], url.QueryEscape(signatureBase64))
req, err := http.NewRequest(http.MethodGet, finalURL, nil)
if err != nil {
return err
}
req.Header.Add("Host", "sms.tencentcloudapi.com")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("TC3-HMAC-SHA256 Credential=%s/%s/tc3_request,SignedHeaders=content-type;host;x-tc-timestamp;x-tc-version,Signature=%s",
tc.SecretID,
time.Now().UTC().Format("2006-01-02"),
url.QueryEscape(signatureBase64)))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
bodyBytes, _ := ioutil.ReadAll(resp.Body)
var bodyJSON map[string]interface{}
err = jsoniter.Unmarshal(bodyBytes, &bodyJSON)
if err != nil {
return err
}
return nil
}
该代码中,我们通过 TencentCloud
结构体来封装了腾讯云的相关信息,包括应用ID、SecretId 和 SecretKey。其中 SendSMS
函数实现了发送短信的功能,可以方便地使用。
另外需要注意的是,在实际使用中,您需要将 AppID
、SecretID
和 SecretKey
替换成您自己腾讯云账号下相应的信息。此外,还需要设置正确的 TemplateID
和 SMSSign
。
希望这个回答对您有所帮助!