-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpaypal-common.go
229 lines (199 loc) · 5.64 KB
/
paypal-common.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package payment
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"time"
)
// NewRequest constructs a request
// Convert payload to a JSON
func (c *PayPalClient) NewRequest(ctx context.Context, method, url string, payload interface{}) (*http.Request, error) {
var buf io.Reader
if payload != nil {
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequestWithContext(ctx, method, url, buf)
}
// SendWithAuth makes a request to the API and apply OAuth2 header automatically.
// If the access token soon to be expired or already expired, it will try to get a new one before
// making the main request
// client.Token will be updated when changed
func (c *PayPalClient) SendWithAuth(req *http.Request, v interface{}) error {
c.Lock()
// 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()
return err
}
}
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()
return c.Send(req, v)
}
// SendWithBasicAuth makes a request to the API using clientID:secret basic auth
func (c *PayPalClient) SendWithBasicAuth(req *http.Request, v interface{}) error {
req.SetBasicAuth(c.ClientID, c.Secret)
return c.Send(req, v)
}
// SetReturnRepresentation enables verbose response
// Verbose response: https://developer.paypal.com/docs/api/orders/v2/#orders-authorize-header-parameters
func (c *PayPalClient) SetReturnRepresentation() {
c.returnRepresentation = true
}
// Send makes a request to the API, the response body will be
// unmarshalled into v, or if v is an io.Writer, the response will
// be written to it without decoding
func (c *PayPalClient) Send(req *http.Request, v interface{}) error {
var (
err error
resp *http.Response
data []byte
)
// Set default headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
if c.returnRepresentation {
req.Header.Set("Prefer", "return=representation")
}
resp, err = c.Client.Do(req)
c.log(req, resp)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
errResp := &ErrorResponse{Response: resp}
data, err = ioutil.ReadAll(resp.Body)
if err == nil && len(data) > 0 {
json.Unmarshal(data, errResp)
}
return errResp
}
if v == nil {
return nil
}
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
return nil
}
return json.NewDecoder(resp.Body).Decode(v)
}
// log will dump request and response to the log file
func (c *PayPalClient) log(r *http.Request, resp *http.Response) {
if c.Log != nil {
var (
reqDump string
respDump []byte
)
if r != nil {
reqDump = fmt.Sprintf("%s %s. Data: %s", r.Method, r.URL.String(), r.Form.Encode())
}
if resp != nil {
respDump, _ = httputil.DumpResponse(resp, true)
}
c.Log.Write([]byte(fmt.Sprintf("Request: %s\nResponse: %s\n", reqDump, string(respDump))))
}
}
// Error method implementation for ErrorResponse struct
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %s, %+v", r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.Message, r.Details)
}
// GetUpdatePatch for catalog (product)
func (product *Product) GetUpdatePatch() []Patch {
return []Patch{
{
Operation: "replace",
Path: "/description",
Value: product.Description,
},
{
Operation: "replace",
Path: "/category",
Value: product.Category,
},
{
Operation: "replace",
Path: "/image_url",
Value: product.ImageUrl,
},
{
Operation: "replace",
Path: "/home_url",
Value: product.HomeUrl,
},
}
}
// GetUpdatePatch for billing plan (Subscription)
func (subPlan *SubscriptionPlan) GetUpdatePatch() []Patch {
result := []Patch{
{
Operation: "replace",
Path: "/description",
Value: subPlan.Description,
},
}
if subPlan.Taxes != nil {
result = append(result, Patch{
Operation: "replace",
Path: "/taxes/percentage",
Value: subPlan.Taxes.Percentage,
})
}
if subPlan.PaymentPreferences != nil {
if subPlan.PaymentPreferences.SetupFee != nil {
result = append(result, Patch{
Operation: "replace",
Path: "/payment_preferences/setup_fee",
Value: subPlan.PaymentPreferences.SetupFee,
},
)
}
result = append(result, []Patch{{
Operation: "replace",
Path: "/payment_preferences/auto_bill_outstanding",
Value: subPlan.PaymentPreferences.AutoBillOutstanding,
},
{
Operation: "replace",
Path: "/payment_preferences/payment_failure_threshold",
Value: subPlan.PaymentPreferences.PaymentFailureThreshold,
},
{
Operation: "replace",
Path: "/payment_preferences/setup_fee_failure_action",
Value: subPlan.PaymentPreferences.SetupFeeFailureAction,
}}...)
}
return result
}
// GetUpdatePatch for billing subscription
func (sub *Subscription) GetUpdatePatch() []Patch {
result := []Patch{
{
Operation: "replace",
Path: "/billing_info/outstanding_balance",
Value: sub.BillingInfo.OutstandingBalance,
},
}
return result
}