-
Notifications
You must be signed in to change notification settings - Fork 8
/
token.go
79 lines (70 loc) · 1.91 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package WeChatCustomerServiceSDK
import (
"encoding/json"
"fmt"
"github.com/NICEXAI/WeChatCustomerServiceSDK/util"
)
const (
//获取调用凭证AccessToken
getTokenAddr = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"
)
// AccessTokenSchema 获取调用凭证响应数据
type AccessTokenSchema struct {
BaseModel
AccessToken string `json:"access_token"` // 获取到的凭证,最长为512字节
ExpiresIn int `json:"expires_in"` // 凭证的有效时间(秒)
}
// GetAccessToken 获取调用凭证access_token
func (r *Client) GetAccessToken() (info AccessTokenSchema, err error) {
data, err := util.HttpGet(fmt.Sprintf(getTokenAddr, r.corpID, r.secret))
if err != nil {
return info, err
}
fmt.Println(string(data))
_ = json.Unmarshal(data, &info)
if info.ErrCode != 0 {
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
}
return info, nil
}
// RefreshAccessToken 刷新调用凭证access_token
func (r *Client) RefreshAccessToken() error {
//初始化AccessToken
tokenInfo, err := r.GetAccessToken()
if err != nil {
return err
}
if err = r.setAccessToken(tokenInfo.AccessToken); err != nil {
return err
}
r.accessToken = tokenInfo.AccessToken
return nil
}
func (r *Client) initAccessToken() error {
//如果关闭自动缓存则直接刷新AccessToken
if r.isCloseCache {
if err := r.RefreshAccessToken(); err != nil {
return err
}
return nil
}
//判断是否已初始化完成,如果己初始化则直接返回当前实例
token, err := r.getAccessToken()
if err != nil {
return NewSDKErr(50002)
}
if token == "" {
if err = r.RefreshAccessToken(); err != nil {
return err
}
} else {
r.accessToken = token
}
return nil
}
func (r *Client) getAccessToken() (string, error) {
return r.cache.Get("wechat:kf:" + r.corpID)
}
func (r *Client) setAccessToken(token string) error {
return r.cache.Set("wechat:kf:"+r.corpID, token, r.expireTime)
}