-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
295 lines (221 loc) · 6.45 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
package azampay
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
// NewClient returns new Client struct
func NewClient(appName, clientID, clientSecret, tokenKey string) (*Client, error) {
if appName == "" || clientID == "" || clientSecret == "" || tokenKey == "" {
return nil, errors.New("appName , clientID, clientSecret, tokenKey are required to create a Client")
}
return &Client{
Client: &http.Client{},
AppName: appName,
ClientID: clientID,
ClientSecret: clientSecret,
TokenKey: tokenKey,
APIBase: APIBase,
}, nil
}
func (c *Client) GetAccessToken(ctx context.Context) (*TokenResponse, error) {
payload := &TokenRequest{
AppName: c.AppName,
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
}
req, err := c.NewRequest(ctx, "POST", AuthenicateUrl, payload)
if err != nil {
return &TokenResponse{}, err
}
response := &TokenResponse{}
errResponse := &ErrTokenResponse{}
err = c.Send(req, response, errResponse)
// Set Token for current Client
if response.Data.AccessToken != nil && err == nil {
c.Token = response
return response, err
}
return &TokenResponse{}, fmt.Errorf("status code %d, %s", errResponse.StatusCode, errResponse.Message)
}
// SetHTTPClient sets *http.Client to current client
func (c *Client) SetHTTPClient(client *http.Client) {
c.Client = client
}
func (c *Client) NewRequest(ctx context.Context, method, url string, payload interface{}) (*http.Request, error) {
var buf io.Reader
if payload != nil {
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequestWithContext(ctx, method, url, buf)
}
// SendWithAuth makes a request to the API using clientID:secret basic auth
func (c *Client) SendWithAuth(req *http.Request, v interface{}, e interface{}) error {
c.mu.Lock()
if c.Token.Data.AccessToken != nil {
if time.Until(c.Token.Data.Expire) < RequestNewTokenBeforeExpiresIn {
// c.Token will be updated in GetAccessToken call
if _, err := c.GetAccessToken(req.Context()); err != nil {
// c.Unlock()
c.mu.Unlock()
return err
}
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *c.Token.Data.AccessToken))
req.Header.Set("X-API-Key", c.TokenKey)
}
c.mu.Unlock()
return c.Send(req, v, e)
}
func (c *Client) Send(req *http.Request, v interface{}, e interface{}) error {
var (
err error
resp *http.Response
data []byte
)
// Set default headers
req.Header.Set("Accept", "application/json")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err = c.Client.Do(req)
if err != nil {
return err
}
defer func(Body io.ReadCloser) error {
return Body.Close()
}(resp.Body)
if resp.StatusCode == 500 {
return errors.New("internal Server Error")
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
data, err = io.ReadAll(resp.Body)
if e == nil {
return fmt.Errorf("unknown error (%s), status code: %d", string(data), resp.StatusCode)
}
if err == nil && len(data) > 0 {
err := json.Unmarshal(data, e)
if err != nil {
return err
}
}
return fmt.Errorf("unknown error, status code: %d", resp.StatusCode)
}
if v == nil {
return nil
}
if w, ok := v.(io.Writer); ok {
_, err := io.Copy(w, resp.Body)
return err
}
return json.NewDecoder(resp.Body).Decode(v)
}
// SendWithAuth makes a request to the API using clientID:secret basic auth
func (c *Client) SendWithAuthStringReturns(req *http.Request) (string, error) {
c.mu.Lock()
if c.Token.Data.AccessToken != nil {
if time.Until(c.Token.Data.Expire) < RequestNewTokenBeforeExpiresIn {
// c.Token will be updated in GetAccessToken call
if _, err := c.GetAccessToken(req.Context()); err != nil {
// c.Unlock()
c.mu.Unlock()
return "", err
}
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *c.Token.Data.AccessToken))
req.Header.Set("X-API-Key", c.TokenKey)
}
c.mu.Unlock()
return c.SendWithStringReturns(req)
}
func (c *Client) SendWithStringReturns(req *http.Request) (string, error) {
var (
err error
resp *http.Response
)
// Set default headers
req.Header.Set("Accept", "application/json")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err = c.Client.Do(req)
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) error {
return Body.Close()
}(resp.Body)
if resp.StatusCode == 500 {
return "", errors.New("internal Server Error")
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return "", fmt.Errorf("unknown error, status code: %d", resp.StatusCode)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), nil
}
func (c *Client) SendWithAuthQueriesParams(req *http.Request, queries TransactionStatusQueries, v interface{}) error {
c.mu.Lock()
if c.Token.Data.AccessToken != nil {
if time.Until(c.Token.Data.Expire) < RequestNewTokenBeforeExpiresIn {
// c.Token will be updated in GetAccessToken call
if _, err := c.GetAccessToken(req.Context()); err != nil {
// c.Unlock()
c.mu.Unlock()
return err
}
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *c.Token.Data.AccessToken))
req.Header.Set("X-API-Key", c.TokenKey)
}
c.mu.Unlock()
return c.SendWithQueriesParams(req, queries, v)
}
func (c *Client) SendWithQueriesParams(req *http.Request, queries TransactionStatusQueries, v interface{}) error {
var (
err error
resp *http.Response
data []byte
)
// Set default headers
req.Header.Set("Accept", "application/json")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
qv := req.URL.Query()
qv.Add("bankName", queries.BankName)
qv.Add("pgReferenceId", queries.PgReferenceID)
resp, err = c.Client.Do(req)
if err != nil {
return err
}
defer func(Body io.ReadCloser) error {
return Body.Close()
}(resp.Body)
if resp.StatusCode == 500 {
return errors.New("internal Server Error")
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
data, err = io.ReadAll(resp.Body)
if err == nil && len(data) > 0 {
return fmt.Errorf("error , status code: %d, %s", resp.StatusCode, string(data))
}
return fmt.Errorf("error reading body error , status code: %d", resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(v)
}