-
Notifications
You must be signed in to change notification settings - Fork 26
/
ussd.go
107 lines (85 loc) · 2.25 KB
/
ussd.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
package nexmo
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
// USSD represents the USSD API functions for sending
// USSD push and prompt messages.
type USSD struct {
client *Client
}
// USSDMessage represents a single USSD message.
type USSDMessage struct {
From string
To string
Text string
StatusReportRequired bool // Optional.
ClientReference string // Optional.
NetworkCode string // Optional.
// Optional: If true, message will be a USSD prompt type,
// otherwise it will be a push.
Prompt bool
}
// Send the message using the specified USSD client.
func (c *USSD) Send(msg *USSDMessage) (*MessageResponse, error) {
if len(msg.From) <= 0 {
return nil, errors.New("Invalid From field specified")
}
if len(msg.To) <= 0 {
return nil, errors.New("Invalid To field specified")
}
if len(msg.ClientReference) > 40 {
return nil, errors.New("Client reference too long")
}
var messageResponse *MessageResponse
values := make(url.Values)
if len(msg.Text) <= 0 {
return nil, errors.New("Invalid message text")
}
// TODO(inhies): UTF8 and URL encode before setting
values.Set("text", msg.Text)
if !c.client.useOauth {
values.Set("api_key", c.client.apiKey)
values.Set("api_secret", c.client.apiSecret)
}
if msg.StatusReportRequired {
values.Set("status_report_req", "1")
}
if msg.ClientReference != "" {
values.Set("client_ref", msg.ClientReference)
}
if msg.NetworkCode != "" {
values.Set("network-code", msg.NetworkCode)
}
var endpoint string
if msg.Prompt {
endpoint = "/ussd-prompt/json"
} else {
endpoint = "/ussd/json"
}
values.Set("to", msg.To)
values.Set("from", msg.From)
valuesReader := bytes.NewReader([]byte(values.Encode()))
var r *http.Request
r, _ = http.NewRequest("POST", apiRoot+endpoint, valuesReader)
r.Header.Add("Accept", "application/json")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := c.client.HTTPClient.Do(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &messageResponse)
if err != nil {
return nil, err
}
return messageResponse, nil
}