forked from messagebird/go-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
423 lines (337 loc) · 10.7 KB
/
client.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//
// Copyright (c) 2014 MessageBird B.V.
// All rights reserved.
//
// Author: Maurice Nonnekes <[email protected]>
// Package messagebird is an official library for interacting with MessageBird.com API.
// The MessageBird API connects your website or application to operators around the world. With our API you can integrate SMS, Chat & Voice.
// More documentation you can find on the MessageBird developers portal: https://developers.messagebird.com/
package messagebird
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"net/url"
"runtime"
"strings"
)
const (
// ClientVersion is used in User-Agent request header to provide server with API level.
ClientVersion = "4.2.0"
// Endpoint points you to MessageBird REST API.
Endpoint = "https://rest.messagebird.com"
)
const (
// HLRPath represents the path to the HLR resource.
HLRPath = "hlr"
// MessagePath represents the path to the Message resource.
MessagePath = "messages"
// MMSPath represents the path to the MMS resource.
MMSPath = "mms"
// VoiceMessagePath represents the path to the VoiceMessage resource.
VoiceMessagePath = "voicemessages"
// VerifyPath represents the path to the Verify resource.
VerifyPath = "verify"
// LookupPath represents the path to the Lookup resource.
LookupPath = "lookup"
)
var (
// ErrResponse is returned when we were able to contact API but request was not successful and contains error details.
ErrResponse = errors.New("The MessageBird API returned an error")
// ErrUnexpectedResponse is used when there was an internal server error and nothing can be done at this point.
ErrUnexpectedResponse = errors.New("The MessageBird API is currently unavailable")
)
// Client is used to access API with a given key.
// Uses standard lib HTTP client internally, so should be reused instead of created as needed and it is safe for concurrent use.
type Client struct {
AccessKey string // The API access key
HTTPClient *http.Client // The HTTP client to send requests on
DebugLog *log.Logger // Optional logger for debugging purposes
}
// New creates a new MessageBird client object.
func New(AccessKey string) *Client {
return &Client{AccessKey: AccessKey, HTTPClient: &http.Client{}}
}
func (c *Client) request(v interface{}, method, path string, data interface{}) error {
uri, err := url.Parse(Endpoint + "/" + path)
if err != nil {
return err
}
var jsonEncoded []byte
if data != nil {
jsonEncoded, err = json.Marshal(data)
if err != nil {
return err
}
}
request, err := http.NewRequest(method, uri.String(), bytes.NewBuffer(jsonEncoded))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
request.Header.Set("Authorization", "AccessKey "+c.AccessKey)
request.Header.Set("User-Agent", "MessageBird/ApiClient/"+ClientVersion+" Go/"+runtime.Version())
if c.DebugLog != nil {
if data != nil {
log.Printf("HTTP REQUEST: %s %s %s", method, uri.String(), jsonEncoded)
} else {
log.Printf("HTTP REQUEST: %s %s", method, uri.String())
}
}
response, err := c.HTTPClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if c.DebugLog != nil {
log.Printf("HTTP RESPONSE: %s", string(responseBody))
}
// Status code 500 is a server error and means nothing can be done at this
// point.
if response.StatusCode == 500 {
return ErrUnexpectedResponse
}
if err = json.Unmarshal(responseBody, &v); err != nil {
return err
}
// Status codes 200 and 201 are indicative of being able to convert the
// response body to the struct that was specified.
if response.StatusCode == 200 || response.StatusCode == 201 {
return nil
}
// Anything else than a 200/201/500 should be a JSON error.
return ErrResponse
}
// Balance returns the balance information for the account that is associated
// with the access key.
func (c *Client) Balance() (*Balance, error) {
balance := &Balance{}
if err := c.request(balance, "GET", "balance", nil); err != nil {
if err == ErrResponse {
return balance, err
}
return nil, err
}
return balance, nil
}
// HLR looks up an existing HLR object for the specified id that was previously
// created by the NewHLR function.
func (c *Client) HLR(id string) (*HLR, error) {
hlr := &HLR{}
if err := c.request(hlr, "GET", HLRPath+"/"+id, nil); err != nil {
if err == ErrResponse {
return hlr, err
}
return nil, err
}
return hlr, nil
}
// HLRs lists all HLR objects that were previously created by the NewHLR
// function.
func (c *Client) HLRs() (*HLRList, error) {
hlrList := &HLRList{}
if err := c.request(hlrList, "GET", HLRPath, nil); err != nil {
if err == ErrResponse {
return hlrList, err
}
return nil, err
}
return hlrList, nil
}
// NewHLR retrieves the information of an existing HLR.
func (c *Client) NewHLR(msisdn string, reference string) (*HLR, error) {
requestData, err := requestDataForHLR(msisdn, reference)
if err != nil {
return nil, err
}
hlr := &HLR{}
if err := c.request(hlr, "POST", HLRPath, requestData); err != nil {
if err == ErrResponse {
return hlr, err
}
return nil, err
}
return hlr, nil
}
// Message retrieves the information of an existing Message.
func (c *Client) Message(id string) (*Message, error) {
message := &Message{}
if err := c.request(message, "GET", MessagePath+"/"+id, nil); err != nil {
if err == ErrResponse {
return message, err
}
return nil, err
}
return message, nil
}
// Messages retrieves all messages of the user represented as a MessageList object.
func (c *Client) Messages(msgListParams *MessageListParams) (*MessageList, error) {
messageList := &MessageList{}
params, err := paramsForMessageList(msgListParams)
if err != nil {
return messageList, err
}
if err := c.request(messageList, "GET", MessagePath+"?"+params.Encode(), nil); err != nil {
if err == ErrResponse {
return messageList, err
}
return nil, err
}
return messageList, nil
}
// NewMessage creates a new message for one or more recipients.
func (c *Client) NewMessage(originator string, recipients []string, body string, msgParams *MessageParams) (*Message, error) {
requestData, err := requestDataForMessage(originator, recipients, body, msgParams)
if err != nil {
return nil, err
}
message := &Message{}
if err := c.request(message, "POST", MessagePath, requestData); err != nil {
if err == ErrResponse {
return message, err
}
return nil, err
}
return message, nil
}
// MMSMessage retrieves the information of an existing MmsMessage.
func (c *Client) MMSMessage(id string) (*MMSMessage, error) {
mmsMessage := &MMSMessage{}
if err := c.request(mmsMessage, "GET", MMSPath+"/"+id, nil); err != nil {
if err == ErrResponse {
return mmsMessage, err
}
return nil, err
}
return mmsMessage, nil
}
// NewMMSMessage creates a new MMS message for one or more recipients.
func (c *Client) NewMMSMessage(originator string, recipients []string, msgParams *MMSMessageParams) (*MMSMessage, error) {
params, err := paramsForMMSMessage(msgParams)
if err != nil {
return nil, err
}
params.Set("originator", originator)
params.Set("recipients", strings.Join(recipients, ","))
mmsMessage := &MMSMessage{}
if err := c.request(mmsMessage, "POST", MMSPath, params); err != nil {
if err == ErrResponse {
return mmsMessage, err
}
return nil, err
}
return mmsMessage, nil
}
// VoiceMessage retrieves the information of an existing VoiceMessage.
func (c *Client) VoiceMessage(id string) (*VoiceMessage, error) {
message := &VoiceMessage{}
if err := c.request(message, "GET", VoiceMessagePath+"/"+id, nil); err != nil {
if err == ErrResponse {
return message, err
}
return nil, err
}
return message, nil
}
// VoiceMessages retrieves all VoiceMessages of the user.
func (c *Client) VoiceMessages() (*VoiceMessageList, error) {
messageList := &VoiceMessageList{}
if err := c.request(messageList, "GET", VoiceMessagePath, nil); err != nil {
if err == ErrResponse {
return messageList, err
}
return nil, err
}
return messageList, nil
}
// NewVoiceMessage creates a new voice message for one or more recipients.
func (c *Client) NewVoiceMessage(recipients []string, body string, params *VoiceMessageParams) (*VoiceMessage, error) {
requestData, err := requestDataForVoiceMessage(recipients, body, params)
if err != nil {
return nil, err
}
message := &VoiceMessage{}
if err := c.request(message, "POST", VoiceMessagePath, requestData); err != nil {
if err == ErrResponse {
return message, err
}
return nil, err
}
return message, nil
}
// NewVerify generates a new One-Time-Password for one recipient.
func (c *Client) NewVerify(recipient string, params *VerifyParams) (*Verify, error) {
requestData, err := requestDataForVerify(recipient, params)
if err != nil {
return nil, err
}
verify := &Verify{}
if err := c.request(verify, "POST", VerifyPath, requestData); err != nil {
if err == ErrResponse {
return verify, err
}
return nil, err
}
return verify, nil
}
// VerifyToken performs token value check against MessageBird API.
func (c *Client) VerifyToken(id, token string) (*Verify, error) {
params := &url.Values{}
params.Set("token", token)
path := VerifyPath + "/" + id + "?" + params.Encode()
verify := &Verify{}
if err := c.request(verify, "GET", path, nil); err != nil {
if err == ErrResponse {
return verify, err
}
return nil, err
}
return verify, nil
}
// Lookup performs a new lookup for the specified number.
func (c *Client) Lookup(phoneNumber string, params *LookupParams) (*Lookup, error) {
urlParams := paramsForLookup(params)
path := LookupPath + "/" + phoneNumber + "?" + urlParams.Encode()
lookup := &Lookup{}
if err := c.request(lookup, "POST", path, nil); err != nil {
if err == ErrResponse {
return lookup, err
}
return nil, err
}
return lookup, nil
}
// NewLookupHLR creates a new HLR lookup for the specified number.
func (c *Client) NewLookupHLR(phoneNumber string, params *LookupParams) (*HLR, error) {
requestData := requestDataForLookup(params)
path := LookupPath + "/" + phoneNumber + "/" + HLRPath
hlr := &HLR{}
if err := c.request(hlr, "POST", path, requestData); err != nil {
if err == ErrResponse {
return hlr, err
}
return nil, err
}
return hlr, nil
}
// LookupHLR performs a HLR lookup for the specified number.
func (c *Client) LookupHLR(phoneNumber string, params *LookupParams) (*HLR, error) {
urlParams := paramsForLookup(params)
path := LookupPath + "/" + phoneNumber + "/" + HLRPath + "?" + urlParams.Encode()
hlr := &HLR{}
if err := c.request(hlr, "GET", path, nil); err != nil {
if err == ErrResponse {
return hlr, err
}
return nil, err
}
return hlr, nil
}