package aliyun import ( "context" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/aliyun/credentials-go/credentials" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/glog" "server/internal/model" isms "server/utility/sms" ) type aliyunClient struct { accessKeyId string accessKeySecret string endpoint string templateId string signName string } // 初始化并注册 func init() { ctx := context.Background() client := &aliyunClient{ accessKeyId: g.Config().MustGet(ctx, "sms.aliyun.accessKeyId").String(), accessKeySecret: g.Config().MustGet(ctx, "sms.aliyun.accessKeySecret").String(), endpoint: g.Config().MustGet(ctx, "sms.aliyun.endpoint").String(), templateId: g.Config().MustGet(ctx, "sms.aliyun.templateId").String(), signName: g.Config().MustGet(ctx, "sms.aliyun.signName").String(), } isms.Register("aliyunsms", client) glog.Infof(ctx, "注册阿里云短信服务成功") } func (a *aliyunClient) client(ctx context.Context) (_result *dysmsapi20170525.Client, _err error) { config := new(credentials.Config). SetType("access_key"). SetAccessKeyId(a.accessKeyId). SetAccessKeySecret(a.accessKeySecret) akCredential, err := credentials.NewCredential(config) if err != nil { return } config1 := &openapi.Config{ Credential: akCredential, } // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi config1.Endpoint = tea.String(a.endpoint) _result = &dysmsapi20170525.Client{} _result, _err = dysmsapi20170525.NewClient(config1) return _result, _err } func (a *aliyunClient) SendCode(ctx context.Context, in *model.SMSCodeIn) (out *model.SMSCodeOut, err error) { client, _err := a.client(ctx) if _err != nil { return nil, _err } // 创建请求对象并设置入参 sendSmsRequest := &dysmsapi20170525.SendSmsRequest{ // 需替换成为您的短信模板code TemplateCode: tea.String(a.templateId), // 需替换成为您的短信模板变量对应的实际值,示例值:{\"code\":\"1234\"} TemplateParam: tea.String(fmt.Sprintf("{\"code\":\"%s\"}", in.Code)), // 需替换成为您的接收手机号码 PhoneNumbers: tea.String(in.Phone), // 需替换成为您的短信签名 SignName: tea.String(a.signName), } glog.Infof(ctx, "aliyun sms request: phone: %s, code: %s", in.Phone, in.Code) runtime := &util.RuntimeOptions{} result, _err := client.SendSmsWithOptions(sendSmsRequest, runtime) if _err != nil { return nil, _err } if *result.Body.Code != `OK` && *result.Body.Code != `isv.BUSINESS_LIMIT_CONTROL` { glog.Errorf(ctx, "阿里云短信发送失败") return nil, fmt.Errorf("发送短信失败") } glog.Infof(ctx, "阿里云短信发送成功") return &model.SMSCodeOut{Success: true}, err }