mirror of https://github.com/veypi/OneAuth.git
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
//
|
|
// Copyright (C) 2024 veypi <i@veypi.com>
|
|
// 2025-03-04 16:08:06
|
|
// Distributed under terms of the MIT license.
|
|
//
|
|
|
|
package sms
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
|
dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v5/client"
|
|
util "github.com/alibabacloud-go/tea-utils/v2/service"
|
|
"github.com/alibabacloud-go/tea/tea"
|
|
)
|
|
|
|
// AliyunProvider 阿里云短信
|
|
type AliyunProvider struct {
|
|
client *dysmsapi20170525.Client
|
|
signName string
|
|
templateCode string
|
|
}
|
|
|
|
// NewAliyunProvider 创建阿里云短信提供商
|
|
func NewAliyunProvider(accessKey, accessSecret, signName, templateCode string) (*AliyunProvider, error) {
|
|
config := &openapi.Config{
|
|
AccessKeyId: tea.String(accessKey),
|
|
AccessKeySecret: tea.String(accessSecret),
|
|
}
|
|
config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
|
|
|
|
client, err := dysmsapi20170525.NewClient(config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create aliyun sms client: %w", err)
|
|
}
|
|
|
|
return &AliyunProvider{
|
|
client: client,
|
|
signName: signName,
|
|
templateCode: templateCode,
|
|
}, nil
|
|
}
|
|
|
|
// Send 发送短信
|
|
func (p *AliyunProvider) Send(phone, code string) error {
|
|
param, _ := json.Marshal(map[string]string{"code": code})
|
|
|
|
req := &dysmsapi20170525.SendSmsRequest{
|
|
PhoneNumbers: tea.String(phone),
|
|
SignName: tea.String(p.signName),
|
|
TemplateCode: tea.String(p.templateCode),
|
|
TemplateParam: tea.String(string(param)),
|
|
}
|
|
|
|
resp, err := p.client.SendSmsWithOptions(req, &util.RuntimeOptions{})
|
|
if err != nil {
|
|
return fmt.Errorf("send sms: %w", err)
|
|
}
|
|
|
|
if *resp.Body.Code != "OK" {
|
|
return fmt.Errorf("send sms failed: %s", tea.StringValue(resp.Body.Message))
|
|
}
|
|
|
|
return nil
|
|
}
|