paypale/auth.go

58 lines
1.8 KiB
Go
Raw Normal View History

2015-10-15 10:47:36 +02:00
package paypalsdk
import (
2015-10-30 08:02:32 +01:00
"bytes"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
2015-10-15 10:47:36 +02:00
)
// GetAuthorizationCodeURL returns URL where we need to redirect user
// After signin in PayPal get authorization_code on redirectURI
func (c *Client) GetAuthorizationCodeURL(redirectURI string, scopes []string) (string, error) {
2015-10-30 08:02:32 +01:00
if redirectURI == "" {
return "", errors.New("redirectURI cannot be empty")
}
2015-10-15 10:47:36 +02:00
2015-10-30 08:02:32 +01:00
if len(scopes) == 0 {
scopes = []string{"profile", "email"}
}
2015-10-15 10:47:36 +02:00
2015-11-17 04:03:46 +01:00
return strings.Replace(c.APIBase, "api.", "", -1) + "/webapps/auth/protocol/openidconnect/v1/authorize?client_id=" +
2015-10-30 08:02:32 +01:00
url.QueryEscape(c.ClientID) + "&response_type=code&scope=" + strings.Join(scopes, "+") +
"&redirect_uri=" + url.QueryEscape(redirectURI), nil
2015-10-15 10:47:36 +02:00
}
2015-10-16 12:00:57 +02:00
2015-10-30 08:02:32 +01:00
// GetAccessToken returns struct of TokenResponse
2015-10-16 12:00:57 +02:00
// Client must to get an authorization code before
// redirectURI must match with redirectURI sent to GetAuthorizationCodeURL
2015-10-30 08:02:32 +01:00
func (c *Client) GetAccessToken(authorizationCode string, redirectURI string) (*TokenResponse, error) {
if authorizationCode == "" {
return &TokenResponse{}, errors.New("authorizationCode cannot be empty")
}
if redirectURI == "" {
return &TokenResponse{}, errors.New("redirectURI cannot be empty")
}
buf := bytes.NewBuffer([]byte("grant_type=authorization_code&code=" + url.QueryEscape(authorizationCode) + "&redirect_uri=" + url.QueryEscape(redirectURI)))
req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", c.APIBase, "/v1/identity/openidconnect/tokenservice"), buf)
if err != nil {
return &TokenResponse{}, err
}
req.SetBasicAuth(c.ClientID, c.Secret)
req.Header.Set("Content-type", "application/x-www-form-urlencoded")
t := TokenResponse{}
err = c.Send(req, &t)
// Set Token fur current Client
if t.Token != "" {
c.Token = &t
}
return &t, err
2015-10-16 12:00:57 +02:00
}