diff --git a/auth.go b/auth.go index 883732e..56f5f33 100644 --- a/auth.go +++ b/auth.go @@ -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) { diff --git a/weapp.go b/weapp.go index 0fd1448..eca8664 100644 --- a/weapp.go +++ b/weapp.go @@ -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{ @@ -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) {