diff --git a/paypal/client.go b/paypal/client.go index 7ebe884d..2be931fd 100644 --- a/paypal/client.go +++ b/paypal/client.go @@ -2,6 +2,8 @@ package paypal import ( "context" + "github.com/go-pay/gopay/pkg/xlog" + "time" "github.com/go-pay/gopay" "github.com/go-pay/gopay/pkg/util" @@ -34,10 +36,26 @@ func NewClient(clientid, secret string, isProd bool) (client *Client, err error) DebugSwitch: gopay.DebugOff, hc: xhttp.NewClient(), } - _, err = client.GetAccessToken() + token, err := client.GetAccessToken() if err != nil { return nil, err } + // 在到期结束前的一半时间内,自动刷新token + go func(token *AccessToken) { + ticker := time.NewTicker(time.Duration(token.ExpiresIn/2) * time.Second) + for { + select { + case <-ticker.C: + tokenNew, err := client.GetAccessToken() + if err != nil { + xlog.Errorf("PayPal GetAccessToken Error: %s", err.Error()) + continue + } + client.AccessToken = tokenNew.AccessToken + } + } + }(token) + return client, nil }