-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
87 lines (70 loc) · 1.55 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
package fedex
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"git.sr.ht/~mendelmaleh/track"
)
type Client struct {
Config Config
OAuth OAuthResponse
}
type Config struct {
ID string
Secret string
URL string
}
func (c *Client) RefreshToken() error {
v := url.Values{}
v.Set("grant_type", "client_credentials")
v.Set("client_id", c.Config.ID)
v.Set("client_secret", c.Config.Secret)
resp, err := http.PostForm(c.Config.URL+"/oauth/token", v)
if err != nil {
return err
}
if err := json.NewDecoder(resp.Body).Decode(&c.OAuth); err != nil {
return err
}
return nil
}
func (c *Client) Track(number string) (tracking track.Tracking, err error) {
if c.OAuth == (OAuthResponse{}) {
if err = c.RefreshToken(); err != nil {
return
}
}
payload := TrackingRequest{
IncludeDetailedScans: true,
TrackingInfo: []TrackingInfoRequest{
{
TrackingNumberInfo: TrackingNumberInfoRequest{
TrackingNumber: number,
},
},
},
}
var buf bytes.Buffer
if err = json.NewEncoder(&buf).Encode(payload); err != nil {
return
}
client := &http.Client{}
req, err := http.NewRequest(http.MethodPost, c.Config.URL+"/track/v1/trackingnumbers", &buf)
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-locale", "en_US")
req.Header.Set("Authorization", "Bearer "+c.OAuth.AccessToken)
resp, err := client.Do(req)
if err != nil {
return
}
var raw TrackResponse
if err = json.NewDecoder(resp.Body).Decode(&raw); err != nil {
return
}
tracking = raw.Tracking()
return
}