短信验证码

This commit is contained in:
2023-08-24 08:13:50 +08:00
parent 6fe75cf9c8
commit 34e748f337
3 changed files with 68 additions and 8 deletions

View File

@@ -4,7 +4,10 @@ import (
"fmt"
"main/configs"
"math/rand"
"net/smtp"
"time"
// 引入阿里云短信
"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)
type Code struct {
@@ -22,17 +25,47 @@ func CodeCreate(email, mobile string) (err error) {
code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
// 如果是邮箱,发送邮件
if email != "" {
go func() {
// 发送邮件
// ...
}()
message := `
To: xxx@qq.com
From: 发送邮件的人名称
Subject: 使用Golang发送邮件
Content-Type: text/html; charset=UTF-8
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="iso-8859-15">
<title>MMOGA POWER</title>
</head>
<body>
您的验证码: 123456
</body>
</html>
`
// 发送邮件到邮箱
auth := smtp.PlainAuth("", "admin@mochu.art", "password", "smtpdm.aliyun.com")
if err := smtp.SendMail("smtpdm.aliyun.com:80", auth, "admin@mochu.art", []string{"xxx@qq.com"}, []byte(message)); err != nil {
//发送邮件失败
fmt.Println(err)
return err
}
}
// 如果是手机,发送短信
if mobile != "" {
go func() {
// 发送短信
// ...
}()
// 发送短信
client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", "your-access-key-id", "your-access-key-secret")
request := dysmsapi.CreateSendSmsRequest()
request.Scheme = "https"
request.PhoneNumbers = mobile
request.SignName = "Mochu"
request.TemplateCode = "SMS_123456"
request.TemplateParam = "{\"code\":\"" + code + "\"}"
response, err := client.SendSms(request)
if err != nil {
fmt.Println(err)
return err
}
fmt.Println(response)
}
// 保存验证码
configs.ORMDB().Create(&Code{