-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
111 lines (90 loc) · 2.63 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
package pay
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"github.com/ministryofjustice/opg-modernising-lpa/internal/event"
)
type Doer interface {
Do(r *http.Request) (*http.Response, error)
}
type Logger interface {
ErrorContext(ctx context.Context, msg string, args ...any)
}
type EventClient interface {
SendPaymentCreated(ctx context.Context, e event.PaymentCreated) error
}
type Client struct {
logger Logger
doer Doer
eventClient EventClient
baseURL string
apiKey string
}
func New(logger Logger, doer Doer, eventClient EventClient, baseURL, apiKey string) *Client {
return &Client{
logger: logger,
doer: doer,
eventClient: eventClient,
baseURL: baseURL,
apiKey: apiKey,
}
}
func (c *Client) CreatePayment(ctx context.Context, lpaUID string, body CreatePaymentBody) (*CreatePaymentResponse, error) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(body); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/v1/payments", &buf)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+c.apiKey)
req.Header.Add("Content-Type", "application/json")
resp, err := c.doer.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
data, _ := io.ReadAll(resp.Body)
c.logger.ErrorContext(ctx, "payment failed",
slog.String("body", string(data)),
slog.Int("statusCode", resp.StatusCode))
return nil, fmt.Errorf("expected 201 got %d", resp.StatusCode)
}
var createPaymentResp CreatePaymentResponse
if err := json.NewDecoder(resp.Body).Decode(&createPaymentResp); err != nil {
return nil, err
}
if err := c.eventClient.SendPaymentCreated(ctx, event.PaymentCreated{
UID: lpaUID,
PaymentID: createPaymentResp.PaymentID,
Amount: createPaymentResp.Amount,
}); err != nil {
return nil, err
}
return &createPaymentResp, nil
}
func (c *Client) GetPayment(ctx context.Context, paymentID string) (GetPaymentResponse, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, 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.doer.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
}