- 下载依赖
go get -u github.com/alibabacloud-go/dysmsapi-20170525/v2
go get -u github.com/alibabacloud-go/darabonba-openapi
go get -u github.com/alibabacloud-go/tea
- 封装代码
package utils
import (
"encoding/json"
"fmt"
"math/rand"
"time"
openapi "github.com/alibabacloud-go/darabonba-openapi/client"
dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
"github.com/alibabacloud-go/tea/tea"
"go.uber.org/zap"
"mxshop-api/user-web/global"
)
type SmsService struct{}
func (m *SmsService) SendCode(phone string) bool {
code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
config := global.ServerConfig.SMSInfo
client, _err := m.CreateClient(tea.String(config.AppKey), tea.String(config.AppSecret))
if _err != nil {
fmt.Println(_err.Error())
return false
}
bCode, _ := json.Marshal(map[string]interface{}{
"code": code,
})
sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
PhoneNumbers: tea.String(phone),
TemplateCode: tea.String(config.TemplateCode),
SignName: tea.String(config.SignName),
TemplateParam: tea.String(string(bCode)),
}
sendSmsResponse, _ := client.SendSms(sendSmsRequest)
if *sendSmsResponse.Body.Code == "OK" {
zap.S().Infof("发送给手机号: %s 的短信验证码成功【%s】", phone, code)
return true
}
return false
}
func (m *SmsService) CreateClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
config := &openapi.Config{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
}
config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
_result = &dysmsapi20170525.Client{}
_result, _err = dysmsapi20170525.NewClient(config)
return _result, _err
}
func SendSmsCode(phone string) bool {
sms := new(SmsService)
return sms.SendCode(phone)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)