-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
519 lines (446 loc) · 14.6 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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package dpo
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/xml"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"strings"
"time"
)
const (
defaultUA = "go-dpo: https://github.com/golang-malawi/go-dpo"
)
// Client struct represents a client and it's configuration for working with the DPO API.
// The client provides functions to initiate, verify, cancel and revoke payment tokens.
// The client uses a basic net/http http.Client.
type Client struct {
Debug bool // Determines whether to use test or live url
Token string // Credentials key for the company
http *http.Client
UserAgent string
maxAttempts int // Maximum number of attempts per operation
GenerateRef func() string
RedirectURL string // RedirectURL the url to redirect to when payment flow completes
BackURL string // BackURL is the url to redirect to when payment fails or is cancelled
}
// defaultCompanyRefGenerator is a function that generates a string that can be used as a Transaction ID.
func defaultCompanyRefGenerator() string {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
// TODO: default to some other random string scheme
panic(err) // TODO: don't panic in a library
}
return base64.RawURLEncoding.EncodeToString(b)
}
// xmlMarshallWithHeader marshals dat into XML with the xml header prepended.
func xmlMarshalWithHeader(data any) ([]byte, error) {
xmlstring, err := xml.Marshal(data) // xml.MarshalIndent(data, "", " ")
if err != nil {
return nil, err
}
xmlstring = []byte(xml.Header + string(xmlstring))
return xmlstring, nil
}
// xmlMarshalWithHeaderDebug for debugging, pretty prints the marshalled XML.
func xmlMarshalWithHeaderDebug(data any) ([]byte, error) {
xmlstring, err := xml.MarshalIndent(data, "", " ")
if err != nil {
return nil, err
}
xmlstring = []byte(xml.Header + string(xmlstring))
return xmlstring, nil
}
// MakePaymentURL creates a URL which should be passed to the User to redirect to the DPO system to complete the payment.
// Requires a non-nil token created using client.CreateToken.
func (c *Client) MakePaymentURL(token *CreateTokenResponse) string {
if token == nil {
return ""
}
if c.Debug {
return fmt.Sprintf("%s?ID=%s", testPayURL, token.TransToken)
}
return fmt.Sprintf("%s?ID=%s", livePayURL, token.TransToken)
}
// NewClient creates a new testing/debug client for 3G service.
// companyToken the token to use for API calls.
// debug whether to enable debug-mode or not - debug mode uses the test URLs instead of live URLs.
func NewClient(companyToken string, debug bool) *Client {
return &Client{
Debug: debug,
Token: companyToken,
UserAgent: defaultUA,
maxAttempts: 5, // other DPO libraries use 10: see - TODO: add link
GenerateRef: defaultCompanyRefGenerator,
RedirectURL: "",
BackURL: "",
http: &http.Client{
Timeout: 30 * time.Second,
},
}
}
// NewLiveClient creates a new Client that has debug set to false.
// companyToken the token to use for API calls.
func NewLiveClient(companyToken string) *Client {
return NewClient(companyToken, false)
}
// NewDebugClient creates a new Client that has debug set to true.
// companyToken the token to use for API calls.
func NewDebugClient(companyToken string) *Client {
return NewClient(companyToken, false)
}
// SetUserAgent sets the user agent to be used with all HTTP requests to the DPO API.
func (c *Client) SetUserAgent(userAgent string) {
if userAgent == "" {
c.UserAgent = defaultUA
return
}
c.UserAgent = userAgent
}
// SetRedirectURL sets the redirect URL which is used for all requests that require a redirect url,
// in most cases this can be overridden by using a similar function call on the request type.
func (c *Client) SetRedirectURL(url string) {
c.RedirectURL = url
}
// SetBackURL sets the back/cancel URL which is used for all requests that require a back url,
// in most cases this can be overridden by using a similar function call on the request type.
func (c *Client) SetBackURL(url string) {
c.BackURL = url
}
// CreateToken creates a token that can be used to perform payments. This is the first step in the payment flow with DPO.
// Once the token is created it must be verified using client.VerifyToken.
func (c *Client) CreateToken(token *CreateTokenRequest) (*CreateTokenResponse, error) {
if token == nil {
return nil, fmt.Errorf("token must not be nil")
}
var url string
var xmlData []byte
var err error
if c.Debug {
url = testAPIURL
xmlData, err = xmlMarshalWithHeaderDebug(token)
} else {
url = liveAPIURL
xmlData, err = xmlMarshalWithHeader(token)
}
if err != nil {
return nil, fmt.Errorf("failed to form XML request: %s got: %v", string(xmlData), err)
}
if c.Debug {
fmt.Printf("using request body: %s\n", string(xmlData))
}
r := bytes.NewReader(xmlData)
req, err := http.NewRequest("POST", url, r)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("Content-Type", "application/xml")
req.Header.Add("Cache-control", "no-cache")
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %s got: %v", string(bodyData), err)
}
if c.Debug {
fmt.Printf("got response body: %s\n", string(bodyData))
}
var tokenResponse CreateTokenResponse
if resp.StatusCode == http.StatusOK {
err = xml.Unmarshal(bodyData, &tokenResponse)
if err != nil {
return nil, fmt.Errorf("failed unmarshal response: %v", err)
}
if tokenResponse.IsError() {
return nil, fmt.Errorf("failed to charge card: %s", tokenResponse.ResultExplanation)
}
return &tokenResponse, nil
}
return nil, fmt.Errorf("invalid response code:%d body: %s", resp.StatusCode, string(bodyData))
}
// VerifyToken verifies the token with DPO site to prepare it for use for actual payment process.
func (c *Client) VerifyToken(token *CreateTokenResponse) (*VerifyTokenResponse, error) {
verifyRequest := &VerifyTokenRequest{
Request: "verifyToken",
CompanyToken: c.Token,
TransactionToken: token.TransToken,
}
var url string
var xmlData []byte
var err error
if c.Debug {
url = testAPIURL
xmlData, err = xmlMarshalWithHeaderDebug(verifyRequest)
} else {
url = liveAPIURL
xmlData, err = xmlMarshalWithHeader(verifyRequest)
}
if err != nil {
return nil, fmt.Errorf("failed to form XML request: %s got: %v", string(xmlData), err)
}
if c.Debug {
fmt.Printf("using request body: %s\n", string(xmlData))
}
r := bytes.NewReader(xmlData)
created := false
maxAttempts := c.maxAttempts
for i := 0; !created && i < maxAttempts; i++ {
req, err := http.NewRequest("POST", url, r)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("Content-Type", "application/xml")
req.Header.Add("Cache-control", "no-cache")
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %s got: %v", string(bodyData), err)
}
if c.Debug {
fmt.Printf("got response body: %s\n", string(bodyData))
}
var verifyTokenResponse VerifyTokenResponse
if resp.StatusCode == http.StatusOK {
err = xml.Unmarshal(bodyData, &verifyTokenResponse)
if err != nil {
return nil, fmt.Errorf("failed unmarshal response: %v", err)
}
// if verifyTokenResponse == "900".IsError() {
// return nil, fmt.Errorf("failed to charge card: %s", verifyTokenResponse.ResultExplanation)
// }
return &verifyTokenResponse, nil
} else if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil, fmt.Errorf("invalid response code:%d body: %s", resp.StatusCode, string(bodyData))
}
}
return nil, fmt.Errorf("failed to process request after %d attempts", c.maxAttempts)
}
// ChargeCreditCard is used for charging a card directly. Do not use this yet.
func (c *Client) ChargeCreditCard(cardHolder, cardNumber, cvv, cardExpiry string, token *CreateTokenResponse) (*ChargeCreditCardResponse, error) {
if token == nil {
return nil, fmt.Errorf("failed to get token: nil value passed as 'token'")
}
transactionToken := token.TransToken
if transactionToken == "" {
return nil, fmt.Errorf("failed to get token")
}
cardRequest := &ChargeCreditCardRequest{
CompanyToken: c.Token,
Request: opChargeTokenCreditCard,
TransactionToken: token.TransToken,
CreditCardNumber: cardNumber,
// The API doesn't accept an expiry with MM/YY it requires MMYY
CreditCardExpiry: strings.ReplaceAll(cardExpiry, "/", ""),
CreditCardCVV: cvv,
CardHolderName: cardHolder,
ThreeD: ThreeDRequest{
Enrolled: "Y",
Paresstatus: "Y",
Eci: "05",
Xid: "",
Cavv: "",
Signature: "_",
Veres: "AUTHENTICATION_SUCCESSFUL",
Pares: "",
},
}
var url string
var xmlData []byte
var err error
if c.Debug {
url = testAPIURL
xmlData, err = xmlMarshalWithHeaderDebug(cardRequest)
} else {
url = liveAPIURL
xmlData, err = xmlMarshalWithHeader(cardRequest)
}
if err != nil {
return nil, fmt.Errorf("failed to form XML request: %s got: %v", string(xmlData), err)
}
if c.Debug {
fmt.Printf("using request body: %s\n", string(xmlData))
}
r := bytes.NewReader(xmlData)
req, err := http.NewRequest("POST", url, r)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("Content-Type", "application/xml")
req.Header.Add("Cache-control", "no-cache")
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %s got: %v", string(bodyData), err)
}
if c.Debug {
fmt.Printf("got response body: %s\n", string(bodyData))
}
var cardResponse ChargeCreditCardResponse
if resp.StatusCode == http.StatusOK {
err = xml.Unmarshal(bodyData, &cardResponse)
if err != nil {
return nil, fmt.Errorf("failed unmarshal response: %v", err)
}
if cardResponse.IsError() {
return nil, fmt.Errorf("failed to charge card: %s", cardResponse.Explanation)
}
return &cardResponse, nil
}
return nil, fmt.Errorf("invalid response code:%d body: %s", resp.StatusCode, string(bodyData))
}
// CancelToken initiates token cancellations - NOT YET IMPLEMENTED
func (c *Client) CancelToken(tokenStr string) (*CancelTokenResponse, error) {
cancelRequest := &CancelTokenRequest{
Request: "cancelToken",
CompanyToken: c.Token,
Token: tokenStr,
}
var url string
var xmlData []byte
var err error
if c.Debug {
url = testAPIURL
xmlData, err = xmlMarshalWithHeaderDebug(cancelRequest)
} else {
url = liveAPIURL
xmlData, err = xmlMarshalWithHeader(cancelRequest)
}
if err != nil {
return nil, fmt.Errorf("failed to form XML request: %s got: %v", string(xmlData), err)
}
if c.Debug {
fmt.Printf("using request body: %s\n", string(xmlData))
}
r := bytes.NewReader(xmlData)
created := false
maxAttempts := c.maxAttempts
for i := 0; !created && i < maxAttempts; i++ {
req, err := http.NewRequest("POST", url, r)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("Content-Type", "application/xml")
req.Header.Add("Cache-control", "no-cache")
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %s got: %v", string(bodyData), err)
}
if c.Debug {
fmt.Printf("got response body: %s\n", string(bodyData))
}
var cancelTokenResponse CancelTokenResponse
if resp.StatusCode == http.StatusOK {
err = xml.Unmarshal(bodyData, &cancelTokenResponse)
if err != nil {
return nil, fmt.Errorf("failed unmarshal response: %v", err)
}
switch cancelTokenResponse.Result {
case "000":
return &cancelTokenResponse, nil
case "999", "804", "950":
default:
return &cancelTokenResponse, fmt.Errorf("dpo error: %s", cancelTokenResponse.ResultExplanation)
}
} else if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil, fmt.Errorf("invalid response code:%d body: %s", resp.StatusCode, string(bodyData))
}
}
return nil, fmt.Errorf("failed to process request after %d attempts", c.maxAttempts)
}
// RefundToken initiates token refunds - NOT YET IMPLEMENTED
func (c *Client) RefundToken(tokenStr string, refundAmount *big.Float, refundRef, description string, requiresApproval bool) (*RefundTokenResponse, error) {
refundApproval := 0
if requiresApproval {
refundApproval = 1
}
refundRequest := &RefundTokenRequest{
CompanyToken: c.Token,
Request: "refundToken",
Token: tokenStr,
RefundAmount: big.Float{},
RefundDetails: description,
RefundRef: refundRef,
RefundApproval: int8(refundApproval),
}
var url string
var xmlData []byte
var err error
if c.Debug {
url = testAPIURL
xmlData, err = xmlMarshalWithHeaderDebug(refundRequest)
} else {
url = liveAPIURL
xmlData, err = xmlMarshalWithHeader(refundRequest)
}
if err != nil {
return nil, fmt.Errorf("failed to form XML request: %s got: %v", string(xmlData), err)
}
if c.Debug {
fmt.Printf("using request body: %s\n", string(xmlData))
}
r := bytes.NewReader(xmlData)
created := false
maxAttempts := c.maxAttempts
for i := 0; !created && i < maxAttempts; i++ {
req, err := http.NewRequest("POST", url, r)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("Content-Type", "application/xml")
req.Header.Add("Cache-control", "no-cache")
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %s got: %v", string(bodyData), err)
}
if c.Debug {
fmt.Printf("got response body: %s\n", string(bodyData))
}
var refundTokenResponse RefundTokenResponse
if resp.StatusCode == http.StatusOK {
err = xml.Unmarshal(bodyData, &refundTokenResponse)
if err != nil {
return nil, fmt.Errorf("failed unmarshal response: %v", err)
}
switch refundTokenResponse.Result {
case "000":
return &refundTokenResponse, nil
case "801", "802", "803", "804", "950", "999":
default:
return &refundTokenResponse, fmt.Errorf("dpo error: %s", refundTokenResponse.ResultExplanation)
}
} else if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil, fmt.Errorf("invalid response code:%d body: %s", resp.StatusCode, string(bodyData))
}
}
return nil, fmt.Errorf("failed to process request after %d attempts", c.maxAttempts)
}