【笔记】Go语言通过腾讯云发送短信

前言

Go语言通过腾讯云发送短信(sms)

下载依赖

1
go get github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common

发送短信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main

import (
"encoding/json"
"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"
"math/rand"
"strings"
"time"
)

// SendPhoneMessage 发送短信
func SendPhoneMessage(phoneNumber string) {

secretID := ""
secretKey := ""
// 应用ID
smsSdkAppID := ""
// 已审核通过的短信签名内容
signName := ""
// 已审核通过的模板ID
templateID := ""

// 创建认证对象
credential := common.NewCredential(
secretID,
secretKey,
)
// 创建请求配置对象
cpf := profile.NewClientProfile()
// 定义请求类型
cpf.HttpProfile.ReqMethod = "POST"
// 定义请求URL
cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"
// 创建客户端对象
client, _ := sms.NewClient(credential, "ap-beijing", cpf)
// 创建发送短信请求对象
request := sms.NewSendSmsRequest()
// 应用ID
request.SmsSdkAppId = common.StringPtr(smsSdkAppID)
// 已审核通过的短信签名内容
request.SignName = common.StringPtr(signName)
// 已审核通过的模板ID
request.TemplateId = common.StringPtr(templateID)
// 定义模板参数
request.TemplateParamSet = common.StringPtrs([]string{generateCode(6)})
// 定义手机号,群发短信不超过200个,包含+86前缀
request.PhoneNumberSet = common.StringPtrs([]string{phoneNumber})

// 发送请求
responseObject, _ := client.SendSms(request)
// 将结果对象转换成JSON格式字符串
responseCharArray, _ := json.Marshal(responseObject.Response)
responseString := string(responseCharArray)
fmt.Println(responseString)
}

// generateCode 生成验证码
func generateCode(length int) string {
num := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
rand.Seed(time.Now().Unix())
var sb strings.Builder
for i := 0; i < length; i++ {
fmt.Fprintf(&sb, "%d", num[rand.Intn(len(num))])
}
return sb.String()
}

完成

参考文献

CSDN——.番茄炒蛋
tencentcloud/tencentcloud-sdk-go