准备条件
阿里云等平台已开通短信服务功能
上代码
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
dysmsapi "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)
func main() {
client, err := dysmsapi.NewClientWithAccessKey("cn-qingdao", "<your-access-key-id>", "<your-access-key-secret>")
/* use STS Token
client, err := dysmsapi.NewClientWithStsToken("cn-qingdao", "<your-access-key-id>", "<your-access-key-secret>", "<your-sts-token>")
*/
request := dysmsapi.CreateSendSmsRequest()
request.Scheme = "https"
request.PhoneNumbers = "1368846****" //接收短信的手机号码
request.SignName = "阿里云" //短信签名名称
request.TemplateCode = "SMS_20933****" //短信模板ID
//code := "1234"
var num int
number := InitData(&num) //随机生成6位验证码
code := strconv.FormatInt(int64(number), 10)
println(code)
request.TemplateParam = "{\"code\":\"" + code + "\"}"
response, err := client.SendSms(request) //这个可以把code存入redis中,方便后面和用户的code比对
if err != nil {
fmt.Print(err.Error())
}
fmt.Printf("response is %#v\n", response)
}
func InitData(p *int) int {
rand.Seed(time.Now().UnixNano())
num := rand.Intn(1000000)
return num
}
run一下