-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
236 lines (223 loc) · 4.94 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
package coleteonline
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
)
// https://docs.api.colete-online.ro
type Client struct {
sync.Mutex
authURL string
apiURL string
authBasic string
authBearer string
authBearerExp time.Time
http *http.Client
timeNow func() time.Time
}
type Config struct {
ClientId string
ClientSecret string
UseProduction bool
Timeout time.Duration
}
func NewClient(config Config) *Client {
client := &Client{
authURL: "https://auth.colete-online.ro/token",
authBasic: "Basic " + base64.StdEncoding.EncodeToString(
[]byte(config.ClientId+":"+config.ClientSecret),
),
http: &http.Client{
Timeout: config.Timeout,
},
timeNow: func() time.Time {
return time.Now()
},
}
if config.UseProduction {
client.apiURL = "https://api.colete-online.ro/v1"
} else {
client.apiURL = "https://api.colete-online.ro/v1/staging"
}
return client
}
func (c *Client) GetAuthBearer() (*string, error) {
c.Lock()
defer c.Unlock()
if c.timeNow().After(c.authBearerExp) {
req, err := http.NewRequest(
"POST",
c.authURL,
strings.NewReader("grant_type=client_credentials"),
)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", c.authBasic)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1MB
if err != nil {
return nil, err
}
if r.StatusCode != 200 {
var rErr AuthResponseError
err = json.Unmarshal(b, &rErr)
if err != nil {
return nil, err
}
return nil, &rErr
}
var res AuthToken
err = json.Unmarshal(b, &res)
if err != nil {
return nil, err
}
c.authBearerExp, err = c.getExpiresAtFromJWT(res.AccessToken)
if err != nil {
return nil, err
}
c.authBearer = "Bearer " + res.AccessToken
}
return &c.authBearer, nil
}
func (c *Client) CreateOrder(order *Order) (*OrderResponse, error) {
var res OrderResponse
err := c.request("POST", "/order", order, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) OrderPrice(order *Order) (*OrderPriceResponse, error) {
var res OrderPriceResponse
err := c.request("POST", "/order/price", order, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) OrderStatus(uniqueIdOrAWB *string) (*OrderStatusResponse, error) {
var res OrderStatusResponse
err := c.request("GET", "/order/status/"+*uniqueIdOrAWB, nil, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) AddressList(page int64) (*AddressListResponse, error) {
var res AddressListResponse
err := c.request("GET", fmt.Sprintf("/address?page=%d", page), nil, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) ServiceList() ([]ServiceResponse, error) {
var res []ServiceResponse
err := c.request("GET", "/service", nil, &res)
if err != nil {
return nil, err
}
return res, nil
}
func (c *Client) UserBalance() (*UserBalance, error) {
var res UserBalance
err := c.request("GET", "/user/balance", nil, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) request(
method string,
path string,
body interface{},
res interface{},
) error {
token, err := c.GetAuthBearer()
if err != nil {
return err
}
var b []byte
if body != nil {
b, err = json.Marshal(body)
if err != nil {
return err
}
}
req, err := http.NewRequest(
method,
c.apiURL+path,
bytes.NewReader(b),
)
if err != nil {
return err
}
req.Header.Set("Authorization", *token)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
r, err := c.http.Do(req)
if err != nil {
return err
}
defer r.Body.Close()
if r.StatusCode == 200 || r.StatusCode == 400 {
b, err = io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1MB
if err != nil {
return err
}
if r.StatusCode == 400 {
var rErr ResponseError
err = json.Unmarshal(b, &rErr)
if err != nil {
return err
}
return &rErr
}
err = json.Unmarshal(b, res)
if err != nil {
return err
}
return nil
}
// Unauthorized: retry request in case the token expired
if r.StatusCode == 401 {
return c.request(method, path, body, res)
}
return &ResponseError{
Message: "unexpected response status",
Code: r.StatusCode,
}
}
// This does not guarantee that the token/payload is valid.
func (c *Client) getExpiresAtFromJWT(token string) (time.Time, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return time.Time{}, errors.New("invalid JWT token")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return time.Time{}, err
}
var claims struct {
Exp int64 `json:"exp"`
}
err = json.Unmarshal(payload, &claims)
if err != nil {
return time.Time{}, fmt.Errorf("invalid JWT payload: %s", err)
}
return time.Unix(claims.Exp, 0), nil
}