From 6919c165288bc1097b048d9f9cdaaa28b2f0d67a Mon Sep 17 00:00:00 2001 From: Medivh Date: Wed, 8 Sep 2021 08:25:51 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=87=AA=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E8=8E=B7=E5=8F=96access=5Ftoken=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- auth.go | 26 +++++++++++++++----------- weapp.go | 12 ++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) 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) {