package access_token import ( "encoding/json" "errors" "net/http" "time" "git.valavala.com/vala/development-kit-sdk/utils" "git.valavala.com/vala/development-kit-sdk/wechat-sdk/structs" ) var wechatStableAccessToken []*structs.WechatStableAccessToken type wechatStableAccessTokenMgr struct { } func NewWechatStableAccessTokenMgr() *wechatStableAccessTokenMgr { return &wechatStableAccessTokenMgr{} } func (m *wechatStableAccessTokenMgr) GetStableAccessToken(appConf *structs.WechatConf) (string, error) { if appConf == nil { return "", errors.New("conf is empty") } for i := range wechatStableAccessToken { if wechatStableAccessToken[i].Appid == appConf.AppId { if wechatStableAccessToken[i].AccessTokenExpiresAt > time.Now().Unix() && wechatStableAccessToken[i].AccessToken != "" { return wechatStableAccessToken[i].AccessToken, nil } break } } url := "https://api.weixin.qq.com/cgi-bin/stable_token" params := map[string]string{ "grant_type": "client_credential", "appid": appConf.AppId, "secret": appConf.AppSecret, } body, _ := json.Marshal(params) header := map[string]string{ "Content-Type": "application/json", } resp, err := utils.HttpRequest(http.MethodPost, url, header, body) if err != nil { return "", err } thisToken := &structs.WechatStableAccessToken{} _ = json.Unmarshal(resp, thisToken) thisToken.AccessTokenExpiresAt = time.Now().Unix() + int64(thisToken.ExpiresIn) thisToken.Appid = appConf.AppId if thisToken.AccessToken == "" { return "", errors.New(appConf.AppId + " access_token is empty") } var newTokens []*structs.WechatStableAccessToken for i := range wechatStableAccessToken { if wechatStableAccessToken[i].Appid == appConf.AppId { newTokens = append(newTokens, thisToken) continue } newTokens = append(newTokens, wechatStableAccessToken[i]) } wechatStableAccessToken = newTokens return thisToken.AccessToken, nil }