-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaypal.go
339 lines (300 loc) · 9.06 KB
/
paypal.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package paypal
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
type Config struct {
OAuthAPI string `json:"oauth-api"`
OrderAPI string `json:"order-api"`
ClientID string `json:"client-id"`
Secret string `json:"secret"`
}
// Load unmarshals a json config file into a Config.
// If the file doesn't exist, it is created and an error is returned.
func Load(jsonPath string) (*Config, error) {
data, err := os.ReadFile(jsonPath)
if os.IsNotExist(err) {
return nil, Create(jsonPath)
}
if err != nil {
return nil, err
}
var config = &Config{}
if err := json.Unmarshal(data, config); err != nil {
return nil, err
}
if config.OAuthAPI == "" {
return nil, errors.New("missing oauth-api in paypal config file")
}
if config.OrderAPI == "" {
return nil, errors.New("missing order-api in paypal config file")
}
if config.ClientID == "" {
return nil, errors.New("missing client-id in paypal config file")
}
if config.Secret == "" {
return nil, errors.New("missing secret in paypal config file")
}
return config, nil
}
// Create creates an empty json config file with empty values and chmod 600, so someone can fill in easily.
// Create always returns an error.
func Create(jsonPath string) error {
data, err := json.Marshal(&Config{})
if err != nil {
return err
}
if err := os.WriteFile(jsonPath, data, 0600); err != nil {
return err
}
return fmt.Errorf("created empty config file: %s", jsonPath)
}
type AuthResult struct {
Scope string `json:"scope"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
AppID string `json:"app_id"`
ExpiresIn int `json:"expires_in"`
Nonce string `json:"nonce"`
}
type OrderRequest struct {
Intent string `json:"intent"`
PurchaseUnits []PurchaseUnit `json:"purchase_units"`
ApplicationContext ApplicationContext `json:"application_context"`
}
// See https://developer.paypal.com/docs/api/orders/v2/#definition-purchase_unit
type PurchaseUnit struct {
ReferenceID string `json:"reference_id,omitempty"` // "[ 1 .. 256 ] characters: The API caller-provided external ID for the purchase unit.", omitempty because paypal fails if it exists but is empty
Description string `json:"description"` // "[ 1 .. 127 ] characters: The purchase description."
InvoiceID string `json:"invoice_id"` // "[ 1 .. 127 ] characters: The API caller-provided external invoice ID for this order. Appears in both the payer's transaction history and the emails that the payer receives."
Amount Amount `json:"amount"`
}
type Amount struct {
CurrencyCode string `json:"currency_code"`
Value float64 `json:"value"`
}
type ApplicationContext struct {
ShippingPreference string `json:"shipping_preference"`
}
type GenerateOrderResponse struct {
ID string `json:"id"` // like "1AB23456CD789012E"
Status string `json:"status"` // like "CREATED"
Links []struct {
Href string `json:"href"`
Rel string `json:"rel"`
Method string `json:"method"`
} `json:"links"`
}
type SuccessResponse struct {
OrderID string `json:"id"`
}
// Auth gets an access token from the PayPal API.
func (config *Config) Auth() (*AuthResult, error) {
req, err := http.NewRequest(
http.MethodPost,
config.OAuthAPI,
bytes.NewBuffer([]byte("grant_type=client_credentials")),
)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(config.ClientID, config.Secret)
resp, err := (&http.Client{
Timeout: 10 * time.Second,
}).Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error getting auth: %s: %s", resp.Status, body)
}
var authResult = &AuthResult{}
return authResult, json.Unmarshal(body, authResult)
}
// CreateOrder calls PayPal to set up a transaction.
func (config *Config) CreateOrder(auth *AuthResult, description, invoiceID, referenceID string, euroCents int) (*GenerateOrderResponse, error) {
orderRequest := &OrderRequest{
Intent: "CAPTURE",
PurchaseUnits: []PurchaseUnit{
PurchaseUnit{
Amount: Amount{
CurrencyCode: "EUR",
Value: float64(euroCents) / 100.0,
},
Description: description,
InvoiceID: invoiceID,
ReferenceID: referenceID,
},
},
ApplicationContext: ApplicationContext{
ShippingPreference: "NO_SHIPPING",
},
}
orJson, err := json.Marshal(orderRequest)
if err != nil {
return nil, err
}
req, err := http.NewRequest(
http.MethodPost,
config.OrderAPI,
bytes.NewBuffer(orJson),
)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Authorization", "Bearer "+auth.AccessToken)
req.Header.Add("Content-Type", "application/json")
resp, err := (&http.Client{
Timeout: 10 * time.Second,
}).Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("error doing order: %s: %s", resp.Status, body)
}
generateOrderResponse := &GenerateOrderResponse{}
return generateOrderResponse, json.Unmarshal(body, generateOrderResponse)
}
type CaptureRequest struct {
OrderID string `json:"orderID"`
}
// Generated 2023-11-22 with json-to-go from docs (Shipping) and a real response (the rest).
// Note that PurchaseUnits does not contain the custom_id.
type CaptureResponse struct {
ID string `json:"id"`
Status string `json:"status"`
PaymentSource struct {
Paypal struct {
EmailAddress string `json:"email_address"`
AccountID string `json:"account_id"`
AccountStatus string `json:"account_status"`
Name struct {
GivenName string `json:"given_name"`
Surname string `json:"surname"`
} `json:"name"`
Address struct {
CountryCode string `json:"country_code"`
} `json:"address"`
} `json:"paypal"`
} `json:"payment_source"`
PurchaseUnits []struct {
ReferenceID string `json:"reference_id"`
Shipping struct {
Address struct {
AddressLine1 string `json:"address_line_1"`
AddressLine2 string `json:"address_line_2"`
AdminArea2 string `json:"admin_area_2"`
AdminArea1 string `json:"admin_area_1"`
PostalCode string `json:"postal_code"`
CountryCode string `json:"country_code"`
} `json:"address"`
} `json:"shipping"`
Payments struct {
Captures []struct {
ID string `json:"id"`
Status string `json:"status"`
Amount struct {
CurrencyCode string `json:"currency_code"`
Value string `json:"value"`
} `json:"amount"`
FinalCapture bool `json:"final_capture"`
SellerProtection struct {
Status string `json:"status"`
DisputeCategories []string `json:"dispute_categories"`
} `json:"seller_protection"`
SellerReceivableBreakdown struct {
GrossAmount struct {
CurrencyCode string `json:"currency_code"`
Value string `json:"value"`
} `json:"gross_amount"`
PaypalFee struct {
CurrencyCode string `json:"currency_code"`
Value string `json:"value"`
} `json:"paypal_fee"`
NetAmount struct {
CurrencyCode string `json:"currency_code"`
Value string `json:"value"`
} `json:"net_amount"`
} `json:"seller_receivable_breakdown"`
InvoiceID string `json:"invoice_id"`
Links []struct {
Href string `json:"href"`
Rel string `json:"rel"`
Method string `json:"method"`
} `json:"links"`
CreateTime time.Time `json:"create_time"`
UpdateTime time.Time `json:"update_time"`
} `json:"captures"`
} `json:"payments"`
} `json:"purchase_units"`
Payer struct {
Name struct {
GivenName string `json:"given_name"`
Surname string `json:"surname"`
} `json:"name"`
EmailAddress string `json:"email_address"`
PayerID string `json:"payer_id"`
Address struct {
CountryCode string `json:"country_code"`
} `json:"address"`
} `json:"payer"`
Links []struct {
Href string `json:"href"`
Rel string `json:"rel"`
Method string `json:"method"`
} `json:"links"`
}
// Capture calls PayPal to capture the order.
func (config *Config) Capture(auth *AuthResult, orderID string) (*CaptureResponse, error) {
req, err := http.NewRequest(
http.MethodPost,
ensureTrailingSlash(config.OrderAPI)+orderID+"/capture",
nil,
)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Authorization", "Bearer "+auth.AccessToken)
req.Header.Add("Content-Type", "application/json")
resp, err := (&http.Client{
Timeout: 10 * time.Second,
}).Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("error capturing: %s: %s", resp.Status, body)
}
captureResponse := &CaptureResponse{}
return captureResponse, json.Unmarshal(body, captureResponse)
}
func ensureTrailingSlash(s string) string {
if strings.HasSuffix(s, "/") {
return s
} else {
return s + "/"
}
}