-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg.go
123 lines (91 loc) · 2.43 KB
/
pg.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
package pg
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/spf13/cast"
)
const (
BASE_URL = "https://pg-next.codeblock.co.tz"
)
type Credentials struct {
ClientID string `json:"clientID"`
ClientSecret string `json:"clientSecret"`
GrantType string `json:"grantType"`
}
type PG struct {
Credentials
}
type UssdPushRequest struct {
Channel string `json:"channel"`
Amount float32 `json:"amount"`
Reference string `json:"reference"`
Currency string `json:"currency"`
CallbackURL string `json:"callbackUrl"`
Description string `json:"description"`
Msisdn string `json:"msisdn"`
CountryCode string `json:"countryCode"`
}
func (pg PG) RequestUssdPush(input UssdPushRequest) (map[string]interface{}, bool) {
client := &http.Client{}
result, success := requestAccessToken(&pg.Credentials)
if !success {
return result, success
}
token := cast.ToStringMapString(result["data"])["token"]
body, err := json.Marshal(input)
if err != nil {
fmt.Println(err.Error())
}
req, httpErr := http.NewRequest("POST", fmt.Sprintf("%s/channel/ussd/push", BASE_URL), bytes.NewBuffer(body))
if httpErr != nil {
fmt.Println(httpErr.Error())
return nil, false
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
res, err := client.Do(req)
if err != nil {
fmt.Println(err.Error())
return nil, false
}
defer res.Body.Close()
var pushResult map[string]interface{}
decodeErr := json.NewDecoder(res.Body).Decode(&pushResult)
if decodeErr != nil {
fmt.Println(decodeErr.Error())
}
if res.StatusCode != 201 {
return pushResult, false
}
return pushResult, true
}
func requestAccessToken(c *Credentials) (map[string]interface{}, bool) {
client := &http.Client{}
body, err := json.Marshal(c)
if err != nil {
fmt.Println(err.Error())
}
req, httpErr := http.NewRequest("POST", fmt.Sprintf("%s/auth/oauth2/token", BASE_URL), bytes.NewBuffer(body))
if httpErr != nil {
fmt.Println(httpErr.Error())
return nil, false
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err.Error())
return nil, false
}
defer res.Body.Close()
var result map[string]interface{}
decodeErr := json.NewDecoder(res.Body).Decode(&result)
if decodeErr != nil {
fmt.Println(decodeErr.Error())
}
if res.StatusCode != 201 {
return result, false
}
return result, true
}