-
Notifications
You must be signed in to change notification settings - Fork 1
/
twilio.go
88 lines (71 loc) · 1.91 KB
/
twilio.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package sendo
import (
"bytes"
"context"
"text/template"
"github.com/kamva/tracer"
"github.com/twilio/twilio-go"
openapi "github.com/twilio/twilio-go/rest/api/v2010"
)
type TwilioService struct {
client *twilio.RestClient
tpl *template.Template
defaultSender string
}
type TwilioOptions struct {
AccountSID string
AuthToken string
Templates map[string]string
DefaultSender string
}
func NewTwilioService(o TwilioOptions) (SMSService, error) {
t, err := parseTextTemplates("twilio_root", o.Templates)
return &TwilioService{
tpl: t,
client: twilio.NewRestClientWithParams(twilio.RestClientParams{
Username: o.AccountSID,
Password: o.AuthToken,
}),
defaultSender: o.DefaultSender,
}, tracer.Trace(err)
}
func (s *TwilioService) renderTemplate(tplName string, data interface{}) (string, error) {
var buf bytes.Buffer
if err := s.tpl.ExecuteTemplate(&buf, tplName, data); err != nil {
return "", tracer.Trace(err)
}
return buf.String(), nil
}
func (s *TwilioService) Send(_ context.Context, o SMSOptions) error {
msg, err := s.renderTemplate(o.TemplateName, o.Data)
if err != nil {
return tracer.Trace(err)
}
if o.Sender == "" {
o.Sender = s.defaultSender
}
params := &openapi.CreateMessageParams{}
params.SetTo(o.PhoneNumber)
params.SetFrom(o.Sender)
params.SetBody(msg)
_, err = s.client.ApiV2010.CreateMessage(params)
return tracer.Trace(err)
}
func (s *TwilioService) SendVerificationCode(_ context.Context, o VerificationOptions) error {
msg, err := s.renderTemplate(o.TemplateName, map[string]interface{}{
"code": o.Code,
})
if err != nil {
return tracer.Trace(err)
}
if o.Sender == "" {
o.Sender = s.defaultSender
}
params := &openapi.CreateMessageParams{}
params.SetTo(o.PhoneNumber)
params.SetFrom(o.Sender)
params.SetBody(msg)
_, err = s.client.ApiV2010.CreateMessage(params)
return tracer.Trace(err)
}
var _ SMSService = &TwilioService{}