Skip to content

Commit

Permalink
add: 增加 helper function - StableAccessToken
Browse files Browse the repository at this point in the history
  • Loading branch information
royalrick committed Nov 12, 2023
1 parent 8f61fc6 commit 81b02e2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion auth/get_stable_access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type GetStableAccessTokenResponse struct {
}

// 获取稳定版接口调用凭据
// doc: https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/getStableAccessToken.html
// doc: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
func (cli *Auth) GetStableAccessToken(req *GetStableAccessTokenRequest) (*GetStableAccessTokenResponse, error) {

api, err := cli.conbineURI(apiGetStableAccessToken, nil, false)
Expand Down
34 changes: 34 additions & 0 deletions weapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,40 @@ func (cli *Client) AccessToken() (string, error) {
}
}

// 获取稳定版接口调用凭据
func (cli *Client) StableAccessToken(forceRefresh bool) (string, error) {

key := cli.tokenCacheKey()
data, ok := cli.cache.Get(key)
if ok {
return data.(string), nil
}

if cli.accessTokenGetter != nil {
token, expireIn := cli.accessTokenGetter(cli.appid, cli.secret)
cli.cache.Set(key, token, time.Duration(expireIn)*time.Second)
return token, nil
} else {

req := auth.GetStableAccessTokenRequest{
Appid: cli.appid,
Secret: cli.secret,
GrantType: "client_credential",
ForceRefresh: forceRefresh,
}
rsp, err := cli.NewAuth().GetStableAccessToken(&req)
if err != nil {
return "", err
}

if err := rsp.GetResponseError(); err != nil {
return "", err
}
cli.cache.Set(key, rsp.AccessToken, time.Duration(rsp.ExpiresIn)*time.Second)
return rsp.AccessToken, nil
}
}

// 拼凑完整的 URI
func (cli *Client) conbineURI(url string, req interface{}, withToken bool) (string, error) {

Expand Down

0 comments on commit 81b02e2

Please sign in to comment.