This repository has been archived by the owner on Feb 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
101 lines (81 loc) · 2 KB
/
client.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package paypalnvp
import (
"bytes"
"fmt"
"net/http"
"github.com/vidsy/go-paypalnvp/payload"
)
const (
baseAPIEndpoint = "https://%s.paypal.com/nvp"
sandboxAPISignatureRequestPrefix = "api-3t.sandbox"
apiSignatureRequestPrefix = "api-3t"
//APIVersion version of the API to use.
APIVersion = "2.3"
// Sandsbox environment
Sandbox = "sandbox"
// Live environment
Live = "live"
)
type (
// Client struct used to interact with the NVP API.
Client struct {
client TransportClient
environment string
User string
Password string
Signature string
}
// TransportClient interface for client providing HTTP transport
// functionality.
TransportClient interface {
Do(req *http.Request) (resp *http.Response, err error)
}
)
// NewClient Creates a new client.
func NewClient(client TransportClient, environment string, user string, password string, signature string) *Client {
if client == nil {
client = &http.Client{}
}
return &Client{client, environment, user, password, signature}
}
// Execute performs the NVP request and returns the results.
func (c Client) Execute(item payload.Serializer) (*Response, error) {
item.SetCredentials(
c.User,
c.Password,
c.Signature,
APIVersion,
)
data, err := item.Serialize()
if err != nil {
return nil, err
}
httpResponse, err := c.perform(data)
if err != nil {
return nil, err
}
response, err := NewResponse(httpResponse)
if err != nil {
return nil, err
}
return response, nil
}
func (c Client) perform(serializedData string) (*http.Response, error) {
request, _ := http.NewRequest(
"POST",
c.generateEndpoint(),
bytes.NewBuffer([]byte(serializedData)),
)
response, err := c.client.Do(request)
if err != nil {
return nil, err
}
return response, nil
}
func (c Client) generateEndpoint() string {
endpointPrefix := sandboxAPISignatureRequestPrefix
if c.environment == Live {
endpointPrefix = apiSignatureRequestPrefix
}
return fmt.Sprintf(baseAPIEndpoint, endpointPrefix)
}