generated from songquanpeng/gin-template
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathaccess-token-store.go
75 lines (67 loc) · 1.63 KB
/
access-token-store.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
package common
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
)
type accessTokenStore struct {
AccessToken string
Mutex sync.RWMutex
ExpirationSeconds int
}
type response struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
var s accessTokenStore
func InitAccessTokenStore() {
go func() {
for {
RefreshAccessToken()
s.Mutex.RLock()
sleepDuration := Max(s.ExpirationSeconds, 60)
s.Mutex.RUnlock()
time.Sleep(time.Duration(sleepDuration) * time.Second)
}
}()
}
func RefreshAccessToken() {
// https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
client := http.Client{
Timeout: 5 * time.Second,
}
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WeChatAppID, WeChatAppSecret), nil)
if err != nil {
SysError(err.Error())
return
}
responseData, err := client.Do(req)
if err != nil {
SysError("failed to refresh access token: " + err.Error())
return
}
defer responseData.Body.Close()
var res response
err = json.NewDecoder(responseData.Body).Decode(&res)
if err != nil {
SysError("failed to decode response: " + err.Error())
return
}
s.Mutex.Lock()
s.AccessToken = res.AccessToken
s.ExpirationSeconds = res.ExpiresIn
s.Mutex.Unlock()
SysLog("access token refreshed")
}
func GetAccessTokenAndExpirationSeconds() (string, int) {
s.Mutex.RLock()
defer s.Mutex.RUnlock()
return s.AccessToken, s.ExpirationSeconds
}
func GetAccessToken() string {
s.Mutex.RLock()
defer s.Mutex.RUnlock()
return s.AccessToken
}