61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package aliyun
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
openapi "github.com/alibabacloud-go/darabonba-openapi/client"
|
|
dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
|
|
"github.com/alibabacloud-go/tea/tea"
|
|
)
|
|
|
|
type Client struct {
|
|
cli *dysmsapi.Client
|
|
signName string
|
|
}
|
|
|
|
func New(accessKeyId, accessKeySecret, signName, endpoint string) (*Client, error) {
|
|
config := &openapi.Config{
|
|
AccessKeyId: tea.String(accessKeyId),
|
|
AccessKeySecret: tea.String(accessKeySecret),
|
|
Endpoint: tea.String(endpoint),
|
|
}
|
|
cli, err := dysmsapi.NewClient(config)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Client{cli: cli, signName: signName}, nil
|
|
}
|
|
|
|
func (c *Client) Send(phone, templateCode string, params map[string]string) error {
|
|
if phone == "" || templateCode == "" {
|
|
return fmt.Errorf("phone and templateCode are required")
|
|
}
|
|
|
|
var templateParam *string
|
|
if len(params) > 0 {
|
|
raw, err := json.Marshal(params)
|
|
if err != nil {
|
|
return fmt.Errorf("marshal template params: %w", err)
|
|
}
|
|
templateParam = tea.String(string(raw))
|
|
}
|
|
|
|
resp, err := c.cli.SendSms(&dysmsapi.SendSmsRequest{
|
|
PhoneNumbers: tea.String(phone),
|
|
SignName: tea.String(c.signName),
|
|
TemplateCode: tea.String(templateCode),
|
|
TemplateParam: templateParam,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp == nil || resp.Body == nil {
|
|
return fmt.Errorf("aliyun sms: empty response")
|
|
}
|
|
if code := tea.StringValue(resp.Body.Code); code != "OK" {
|
|
return fmt.Errorf("aliyun sms: %s %s", code, tea.StringValue(resp.Body.Message))
|
|
}
|
|
return nil
|
|
}
|