-
Notifications
You must be signed in to change notification settings - Fork 14
/
sinch_provider.go
101 lines (85 loc) · 2.25 KB
/
sinch_provider.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
89
90
91
92
93
94
95
96
97
98
99
100
101
package sms
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"time"
"github.com/coretrix/hitrix/pkg/helper"
"github.com/coretrix/hitrix/service/component/clock"
"github.com/coretrix/hitrix/service/component/config"
)
const (
javascriptISOString = `2006-01-02T15:04:05.999Z07:00`
Sinch = "sinch"
)
type SinchProvider struct {
Clock clock.IClock
AppID string
AppSecret string
MsgURL string
FromNumber string
}
func NewSinchProvider(configService config.IConfig, clockService clock.IClock) (IProvider, error) {
appID, ok := configService.String("sms.sinch.app_id")
if !ok {
return nil, errors.New("missing sms.sinch.app_id")
}
appSecret, ok := configService.String("sms.sinch.app_secret")
if !ok {
return nil, errors.New("missing sms.sinch.app_secret")
}
msgURL, ok := configService.String("sms.sinch.msg_url")
if !ok {
return nil, errors.New("missing sms.sinch.msg_url")
}
fromNumberSinch, ok := configService.String("sms.sinch.from_number")
if !ok {
return nil, errors.New("missing sms.sinch.from_number")
}
return &SinchProvider{
Clock: clockService,
AppID: appID,
AppSecret: appSecret,
MsgURL: msgURL,
FromNumber: fromNumberSinch,
}, nil
}
func (g *SinchProvider) GetName() string {
return Sinch
}
func (g *SinchProvider) SendSMSMessage(message *Message) (string, error) {
body := struct {
From string `json:"from"`
Message string `json:"message"`
Caller string `json:"caller"`
}{
From: g.FromNumber,
Message: message.Text,
Caller: message.Number,
}
headers := g.getSinchHeaders()
responseBody, _, code, err := helper.Call(
context.Background(),
"POST",
g.MsgURL+"/"+message.Number,
headers,
time.Duration(timeoutInSeconds)*time.Second,
body,
nil)
if err != nil {
return failure, err
}
if code != http.StatusOK {
return failure, fmt.Errorf("expected status code OK, but got %v Response: %s", code, string(responseBody))
}
return success, nil
}
func (g *SinchProvider) getSinchHeaders() map[string]string {
return map[string]string{
"Content-Type": "application/json",
"Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(g.AppID+":"+g.AppSecret)),
"X-Timestamp": g.Clock.Now().Format(javascriptISOString),
}
}