-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoauth.go
56 lines (43 loc) · 1.19 KB
/
oauth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package gopaypal
import (
"encoding/json"
"net/http"
"time"
)
type oauthResponse struct {
Scope []string `json:"scope"`
Nonce string `json:"nonce"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
AppID string `json:"app_id"`
ExpiresIn int `json"expires_in"`
Expires time.Time `json:"-"`
}
// GetAccessToken gets the OAuth2 token from the PayPal endpoint
func (c *Client) GetAccessToken() (*oauthResponse, error) {
// Set grant_type
buff := []byte("grant_type=client_credentials")
// Create new gopaypal basic request
req, err := c.BasicRequest(OAuthURL, buff, http.MethodPost)
if err != nil {
return nil, err
}
// Set basic HTTP authentication
req.SetBasicAuth(c.clientID, c.secret)
// Execute request
res, err := c.Execute(req)
if err != nil {
return nil, err
}
// Parse response as JSON
oauthres := oauthResponse{}
// Unmarshal response
if json.Unmarshal(res, &oauthres); err != nil {
return nil, err
}
// Set client access token
c.AccessToken = &oauthres
// Set token expires in time
c.AccessToken.Expires = time.Now().Add(time.Duration(c.AccessToken.ExpiresIn))
return &oauthres, nil
}