From 5fddf59f71f061af1852aac2e5ccb18331156c5d Mon Sep 17 00:00:00 2001 From: Penny Date: Thu, 1 Feb 2024 17:07:34 +0800 Subject: [PATCH] feat: get access token automatically (#261) --- README.md | 2 -- client.go | 18 ++++++++---------- client_test.go | 18 +++++++----------- 3 files changed, 15 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 1883dda..e83b789 100644 --- a/README.md +++ b/README.md @@ -119,8 +119,6 @@ import "github.com/plutov/paypal/v4" // Create a client instance c, err := paypal.NewClient("clientID", "secretID", paypal.APIBaseSandBox) c.SetLog(os.Stdout) // Set log to terminal stdout - -accessToken, err := c.GetAccessToken(context.Background()) ``` ## Get authorization by ID diff --git a/client.go b/client.go index 9e5fd74..2c78739 100644 --- a/client.go +++ b/client.go @@ -143,18 +143,16 @@ func (c *Client) SendWithAuth(req *http.Request, v interface{}) error { // Note: Here we do not want to `defer c.Unlock()` because we need `c.Send(...)` // to happen outside of the locked section. - if c.Token != nil { - if !c.tokenExpiresAt.IsZero() && c.tokenExpiresAt.Sub(time.Now()) < RequestNewTokenBeforeExpiresIn { - // c.Token will be updated in GetAccessToken call - if _, err := c.GetAccessToken(req.Context()); err != nil { - // c.Unlock() - c.mu.Unlock() - return err - } + if c.Token == nil || (!c.tokenExpiresAt.IsZero() && time.Until(c.tokenExpiresAt) < RequestNewTokenBeforeExpiresIn) { + // c.Token will be updated in GetAccessToken call + if _, err := c.GetAccessToken(req.Context()); err != nil { + // c.Unlock() + c.mu.Unlock() + return err } - - req.Header.Set("Authorization", "Bearer "+c.Token.Token) } + + req.Header.Set("Authorization", "Bearer "+c.Token.Token) // Unlock the client mutex before sending the request, this allows multiple requests // to be in progress at the same time. // c.Unlock() diff --git a/client_test.go b/client_test.go index b67cd5a..4810b83 100644 --- a/client_test.go +++ b/client_test.go @@ -65,19 +65,15 @@ func (c *Client) sendWithAuth(req *http.Request, v interface{}) error { err := errors.New("TryLock succeeded inside sendWithAuth with mutex locked") return err } - - if c.Token != nil { - if !c.tokenExpiresAt.IsZero() && c.tokenExpiresAt.Sub(time.Now()) < RequestNewTokenBeforeExpiresIn { - // c.Token will be updated in GetAccessToken call - if _, err := c.GetAccessToken(req.Context()); err != nil { - // c.Unlock() - c.mu.Unlock() - return err - } + if c.Token == nil || (!c.tokenExpiresAt.IsZero() && time.Until(c.tokenExpiresAt) < RequestNewTokenBeforeExpiresIn) { + // c.Token will be updated in GetAccessToken call + if _, err := c.GetAccessToken(req.Context()); err != nil { + // c.Unlock() + c.mu.Unlock() + return err } - - req.Header.Set("Authorization", "Bearer "+c.Token.Token) } + req.Header.Set("Authorization", "Bearer "+c.Token.Token) // Unlock the client mutex before sending the request, this allows multiple requests // to be in progress at the same time. // c.Unlock()