golang中使用阿里云sdk发送短信验证码

  1. 下载依赖
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
  1. 封装代码
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 {
	// 1. 生成一个验证码
	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	// 获取配置文件
	config := global.ServerConfig.SMSInfo
	// 2. 调用阿里云sdk,完成发送
	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)),
	}
	// 复制代码运行请自行打印 API 的返回值
	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{
		// 您的AccessKey ID
		AccessKeyId: accessKeyId,
		// 您的AccessKey Secret
		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)
}

posted @ 2022-03-05 11:32  专职  阅读(662)  评论(0编辑  收藏  举报