-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
default_access_token.go
232 lines (201 loc) · 7.47 KB
/
default_access_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
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
package credential
import (
"context"
"encoding/json"
"fmt"
"github.com/donetkit/contrib/utils/cache"
"github.com/donetkit/wechat/util"
"sync"
"time"
)
const (
// accessTokenURL 获取access_token的接口
accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
// stableAccessTokenURL 获取稳定版access_token的接口
stableAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/stable_token"
// workAccessTokenURL 企业微信获取access_token的接口
workAccessTokenURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"
// CacheKeyOfficialAccountPrefix 微信公众号cache key前缀
CacheKeyOfficialAccountPrefix = "gowechat_officialaccount_"
// CacheKeyMiniProgramPrefix 小程序cache key前缀
CacheKeyMiniProgramPrefix = "gowechat_miniprogram_"
// CacheKeyWorkPrefix 企业微信cache key前缀
CacheKeyWorkPrefix = "gowechat_work_"
)
// DefaultAccessToken 默认AccessToken 获取
type DefaultAccessToken struct {
appID string
appSecret string
cacheKeyPrefix string
cache cache.ICache
accessTokenLock *sync.Mutex
}
// NewDefaultAccessToken new DefaultAccessToken
func NewDefaultAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.ICache) AccessTokenHandle {
if cache == nil {
panic("cache is ineed")
}
return &DefaultAccessToken{
appID: appID,
appSecret: appSecret,
cache: cache,
cacheKeyPrefix: cacheKeyPrefix,
accessTokenLock: new(sync.Mutex),
}
}
// ResAccessToken struct
type ResAccessToken struct {
util.CommonError
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
}
// GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
func (ak *DefaultAccessToken) GetAccessToken(ctx context.Context) (accessToken string, err error) {
// 先从cache中取
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
accessToken, err = ak.cache.WithContext(ctx).GetString(accessTokenCacheKey)
if len(accessToken) > 0 {
return
}
//加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
ak.accessTokenLock.Lock()
defer ak.accessTokenLock.Unlock()
// 双检,防止重复从微信服务器获取
accessToken, err = ak.cache.WithContext(ctx).GetString(accessTokenCacheKey)
if len(accessToken) > 0 {
return
}
//cache失效,从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret))
if err != nil {
return
}
expires := resAccessToken.ExpiresIn - 1500
err = ak.cache.WithContext(ctx).Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
accessToken = resAccessToken.AccessToken
return
}
// WorkAccessToken 企业微信AccessToken 获取
type WorkAccessToken struct {
CorpID string
CorpSecret string
cacheKeyPrefix string
cache cache.ICache
accessTokenLock *sync.Mutex
}
// NewWorkAccessToken new WorkAccessToken
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.ICache) AccessTokenHandle {
if cache == nil {
panic("cache the not exist")
}
return &WorkAccessToken{
CorpID: corpID,
CorpSecret: corpSecret,
cache: cache,
cacheKeyPrefix: cacheKeyPrefix,
accessTokenLock: new(sync.Mutex),
}
}
// GetAccessToken 企业微信获取access_token,先从cache中获取,没有则从服务端获取
func (ak *WorkAccessToken) GetAccessToken(ctx context.Context) (accessToken string, err error) {
//加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
ak.accessTokenLock.Lock()
defer ak.accessTokenLock.Unlock()
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.CorpID)
accessToken, err = ak.cache.WithContext(ctx).GetString(accessTokenCacheKey)
if len(accessToken) > 0 {
return
}
//cache失效,从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
if err != nil {
return
}
expires := resAccessToken.ExpiresIn - 1500
err = ak.cache.WithContext(ctx).Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
accessToken = resAccessToken.AccessToken
return
}
// StableAccessToken 获取稳定版接口调用凭据(与getAccessToken获取的调用凭证完全隔离,互不影响)
// 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存,避免access_token争抢
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
type StableAccessToken struct {
appID string
appSecret string
cacheKeyPrefix string
cache cache.ICache
}
// NewStableAccessToken new StableAccessToken
func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.ICache) AccessTokenContextHandle {
if cache == nil {
panic("cache is need")
}
return &StableAccessToken{
appID: appID,
appSecret: appSecret,
cache: cache,
cacheKeyPrefix: cacheKeyPrefix,
}
}
// GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
func (ak *StableAccessToken) GetAccessToken(ctx context.Context) (accessToken string, err error) {
return ak.GetAccessTokenContext(context.Background())
}
// GetAccessTokenContext 获取access_token,先从cache中获取,没有则从服务端获取
func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
// 先从cache中取
accessTokenCacheKey := fmt.Sprintf("%s_stable_access_token_%s", ak.cacheKeyPrefix, ak.appID)
accessToken, err = ak.cache.WithContext(ctx).GetString(accessTokenCacheKey)
if len(accessToken) > 0 {
return
}
// cache失效,从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = ak.GetAccessTokenDirectly(ctx, false)
if err != nil {
return
}
expires := resAccessToken.ExpiresIn - 300
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
accessToken = resAccessToken.AccessToken
return
}
// GetAccessTokenDirectly 从微信获取access_token
func (ak *StableAccessToken) GetAccessTokenDirectly(ctx context.Context, forceRefresh bool) (resAccessToken ResAccessToken, err error) {
b, err := util.PostJSONContext(ctx, stableAccessTokenURL, map[string]interface{}{
"grant_type": "client_credential",
"appid": ak.appID,
"secret": ak.appSecret,
"force_refresh": forceRefresh,
})
if err != nil {
return
}
if err = json.Unmarshal(b, &resAccessToken); err != nil {
return
}
if resAccessToken.ErrCode != 0 {
err = fmt.Errorf("get stable access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
return
}
return
}
// GetTokenFromServerContext 强制从微信服务器获取token
func GetTokenFromServerContext(ctx context.Context, url string) (resAccessToken ResAccessToken, err error) {
var body []byte
body, err = util.HTTPGetContext(ctx, url)
if err != nil {
return
}
err = json.Unmarshal(body, &resAccessToken)
if err != nil {
return
}
if resAccessToken.ErrCode != 0 {
err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
return
}
return
}