-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
93 lines (69 loc) · 1.99 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
package pay
import (
"bytes"
"context"
"encoding/json"
"net/http"
"time"
)
type Doer interface {
Do(r *http.Request) (*http.Response, error)
}
type Client struct {
BaseURL string
ApiKey string
HttpClient Doer
}
type GovUKPayTime time.Time
func (g *GovUKPayTime) UnmarshalText(b []byte) error {
t, err := time.Parse(time.RFC3339Nano, string(b))
if err != nil {
return err
}
*g = GovUKPayTime(t)
return nil
}
func (g GovUKPayTime) MarshalText() ([]byte, error) {
return []byte(g.Format(time.RFC3339Nano)), nil
}
func (g GovUKPayTime) Format(s string) string {
return time.Time(g).Format(s)
}
func (c *Client) CreatePayment(ctx context.Context, body CreatePaymentBody) (CreatePaymentResponse, error) {
data, _ := json.Marshal(body)
reader := bytes.NewReader(data)
req, err := http.NewRequestWithContext(ctx, "POST", c.BaseURL+"/v1/payments", reader)
if err != nil {
return CreatePaymentResponse{}, err
}
req.Header.Add("Authorization", "Bearer "+c.ApiKey)
req.Header.Add("Content-Type", "application/json")
resp, err := c.HttpClient.Do(req)
if err != nil {
return CreatePaymentResponse{}, err
}
defer resp.Body.Close()
var createPaymentResp CreatePaymentResponse
if err := json.NewDecoder(resp.Body).Decode(&createPaymentResp); err != nil {
return CreatePaymentResponse{}, err
}
return createPaymentResp, nil
}
func (c *Client) GetPayment(ctx context.Context, paymentId string) (GetPaymentResponse, error) {
req, err := http.NewRequestWithContext(ctx, "GET", c.BaseURL+"/v1/payments/"+paymentId, nil)
if err != nil {
return GetPaymentResponse{}, err
}
req.Header.Add("Authorization", "Bearer "+c.ApiKey)
req.Header.Add("Content-Type", "application/json")
resp, err := c.HttpClient.Do(req)
if err != nil {
return GetPaymentResponse{}, err
}
defer resp.Body.Close()
var getPaymentResponse GetPaymentResponse
if err := json.NewDecoder(resp.Body).Decode(&getPaymentResponse); err != nil {
return GetPaymentResponse{}, err
}
return getPaymentResponse, nil
}