feat: aliyun sms
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
package sms
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"lone-services/pkg/sms/aliyun"
|
||||
)
|
||||
|
||||
type TemplateKind string
|
||||
|
||||
const (
|
||||
TemplateCode TemplateKind = "code"
|
||||
TemplatePassword TemplateKind = "password"
|
||||
)
|
||||
|
||||
type SMS interface {
|
||||
Send(phone string, templateCode string, params map[string]string) error
|
||||
SendByKind(phone string, kind TemplateKind, params map[string]string) error
|
||||
Template(kind TemplateKind) string
|
||||
Timeout() int
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
AccessKeyId string
|
||||
AccessKeySecret string
|
||||
SignName string
|
||||
Endpoint string
|
||||
TemplateCode string
|
||||
TemplatePwd string
|
||||
Timeout int
|
||||
}
|
||||
|
||||
type client struct {
|
||||
sender *aliyun.Client
|
||||
templates map[TemplateKind]string
|
||||
timeout int
|
||||
}
|
||||
|
||||
func New(cfg Config) (SMS, error) {
|
||||
if cfg.AccessKeyId == "" || cfg.AccessKeySecret == "" || cfg.SignName == "" {
|
||||
return nil, fmt.Errorf("config missing")
|
||||
}
|
||||
|
||||
sender, err := aliyun.New(cfg.AccessKeyId, cfg.AccessKeySecret, cfg.SignName, cfg.Endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = 600
|
||||
}
|
||||
return &client{
|
||||
sender: sender,
|
||||
templates: map[TemplateKind]string{
|
||||
TemplateCode: cfg.TemplateCode,
|
||||
TemplatePassword: cfg.TemplatePwd,
|
||||
},
|
||||
timeout: cfg.Timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *client) Send(phone, templateCode string, params map[string]string) error {
|
||||
return c.sender.Send(phone, templateCode, params)
|
||||
}
|
||||
|
||||
func (c *client) SendByKind(phone string, kind TemplateKind, params map[string]string) error {
|
||||
code := c.Template(kind)
|
||||
if code == "" {
|
||||
return fmt.Errorf("sms template not configured for kind %s", kind)
|
||||
}
|
||||
return c.Send(phone, code, params)
|
||||
}
|
||||
|
||||
func (c *client) Template(kind TemplateKind) string { return c.templates[kind] }
|
||||
func (c *client) Timeout() int { return c.timeout }
|
||||
Reference in New Issue
Block a user