-
Notifications
You must be signed in to change notification settings - Fork 4
/
token.go
60 lines (49 loc) · 1.24 KB
/
token.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
package youdu
import (
"context"
"strconv"
"time"
)
type token struct {
Token string
Expired time.Time
}
func (c *Client) GetToken(ctx context.Context) (string, error) {
if c.token != nil && c.token.Expired.After(time.Now()) {
return c.token.Token, nil
}
ciphertext, err := c.encryptor.Encrypt([]byte(strconv.Itoa(int(time.Now().Unix()))))
if err != nil {
return "", err
}
resp, err := c.getToken(ctx, tokenRequest{
Buin: c.config.Buin,
AppID: c.config.AppID,
Encrypt: ciphertext,
})
if err != nil {
return "", err
}
c.token = &token{
Token: resp.AccessToken,
Expired: time.Now().Add(time.Duration(resp.ExpireIn)*time.Second - 10*time.Minute), // 提前10分钟过期
}
return resp.AccessToken, nil
}
type tokenRequest struct {
Buin int `json:"buin"`
AppID string `json:"appId"`
Encrypt string `json:"encrypt"`
}
type tokenResponse struct {
AccessToken string `json:"accessToken"`
ExpireIn int `json:"expireIn"`
}
func (c *Client) getToken(ctx context.Context, request tokenRequest) (response tokenResponse, err error) {
req, err := c.newRequest(ctx, "POST", "/cgi/gettoken", withRequestBody(request))
if err != nil {
return
}
err = c.sendRequest(req, &response, withResponseDecrypt())
return
}