Skip to content

Commit

Permalink
feat: get access token automatically (#261)
Browse files Browse the repository at this point in the history
  • Loading branch information
spyth committed Feb 1, 2024
1 parent 26473c3 commit 5fddf59
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 23 deletions.
2 changes: 0 additions & 2 deletions README.md
Expand Up @@ -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
Expand Down
18 changes: 8 additions & 10 deletions client.go
Expand Up @@ -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()
Expand Down
18 changes: 7 additions & 11 deletions client_test.go
Expand Up @@ -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()
Expand Down

0 comments on commit 5fddf59

Please sign in to comment.