Skip to content

Commit

Permalink
增加自定义获取access_token的方法
Browse files Browse the repository at this point in the history
  • Loading branch information
royalrick committed Sep 8, 2021
1 parent e921a43 commit 6919c16
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
26 changes: 15 additions & 11 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,22 @@ func (cli *Client) AccessToken() (string, error) {
return data.(string), nil
}

rsp, err := cli.GetAccessToken()
if err != nil {
return "", err
}

if err := rsp.GetResponseError(); err != nil {
return "", err
if cli.accessTokenGetter != nil {
token, expireIn := cli.accessTokenGetter()
cli.cache.Set(key, token, time.Duration(expireIn))
return token, nil
} else {
rsp, err := cli.GetAccessToken()
if err != nil {
return "", err
}

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

cli.cache.Set(key, rsp.AccessToken, time.Duration(rsp.ExpiresIn))

return rsp.AccessToken, nil
}

func (cli *Client) GetAccessToken() (*TokenResponse, error) {
Expand Down
12 changes: 12 additions & 0 deletions weapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,13 @@ type Client struct {
appid string
// 小程序后台配置: 小程序密钥
secret string
// 用户自定义获取access_token的方法
accessTokenGetter AccessTokenGetter
}

// 用户自定义获取access_token的方法
type AccessTokenGetter func() (token string, expireIn uint)

// 初始化客户端并用自定义配置替换默认配置
func NewClient(appid, secret string, opts ...func(*Client)) *Client {
cli := &Client{
Expand Down Expand Up @@ -83,6 +88,13 @@ func WithCache(cc cache.Cache) func(*Client) {
}
}

// 自定义获取access_token的方法
func WithAccessTokenSetter(getter AccessTokenGetter) func(*Client) {
return func(cli *Client) {
cli.accessTokenGetter = getter
}
}

// 自定义日志
func WithLogger(logger logger.Logger) func(*Client) {
return func(cli *Client) {
Expand Down

0 comments on commit 6919c16

Please sign in to comment.