-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
302 lines (239 loc) · 7.14 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
package mobilepay
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"time"
"github.com/google/go-querystring/query"
)
// https://mobilepaydev.github.io/MobilePay-Payments-API/docs/payments-refunds/create-payments
const (
LibraryVersion = "1.0.0"
DefaultBaseURL = "https://api.mobilepay.dk"
TestBaseUrl = "https://api.sandbox.mobilepay.dk"
userAgent = "mobilepay-go/" + LibraryVersion
mediaType = "application/json"
ibmClientIdHeaderKey = "x-ibm-client-id"
DefaultTimeout = 10 * time.Second
)
type Client struct {
// HTTP client used to communicate with the MobilePay App Payment API.
client *http.Client
// Base URL for API requests.
BaseURL *url.URL
// User agent for client
UserAgent string
// Optional function called after every successful request made to the Mobilepay API
onRequestCompleted RequestCompletionCallback
// Optional extra HTTP headers to set on every request to the API.
headers map[string]string
Logger LeveledLoggerInterface
// MobilePay API services used for communicating with the API.
Payment *PaymentServiceOp // we are using a struct over an interface to support multiple interfaces implemented by the struct properties.
Webhook WebhookService
}
func newDefaultHTTPClient() *http.Client {
return &http.Client{
Timeout: DefaultTimeout,
}
}
// RequestCompletionCallback defines the type of the request callback function
type RequestCompletionCallback func(*http.Request, *http.Response)
// ClientOpt are options for New.
type ClientOpt func(*Client) error
type Response struct {
*http.Response
}
// An ErrorResponse reports the error caused by an API request
type ErrorResponse struct {
// HTTP response that caused this error
Response *http.Response `json:"-"`
// Error message
Message string `json:"message,omitempty"`
Conflict *ConflictError `json:"conflict"`
StatusCode int `json:"statusCode"`
}
type ConflictError struct {
Code string `json:"code"`
Message string `json:"message"`
CorrelationID string `json:"correlationId"`
Origin string `json:"origin"`
}
type responseParser func(*http.Response) error
func newJSONParser(resource interface{}) responseParser {
return func(res *http.Response) error {
return json.NewDecoder(res.Body).Decode(resource)
}
}
// URL is the base url to the Mobilepay API.
// You can use the constants defined in this package: DefaultBaseURL or TestBaseUrl
type Config struct {
HTTPClient *http.Client
Logger LeveledLoggerInterface
URL string
}
func New(IbmClientId, apiKey string, config *Config) *Client {
if config.HTTPClient == nil {
config.HTTPClient = newDefaultHTTPClient()
}
if config.Logger == nil {
config.Logger = DefaultLeveledLogger
}
if config.URL == "" {
config.URL = DefaultBaseURL
}
baseURL, _ := url.Parse(config.URL)
c := &Client{
client: config.HTTPClient,
BaseURL: baseURL,
UserAgent: userAgent,
Logger: config.Logger,
}
// we wrap the refund service inside the payment service to follow a more RESTful approach
refundService := &RefundServiceOp{client: c}
c.Payment = &PaymentServiceOp{client: c, Refund: refundService}
c.Webhook = &WebhookServiceOp{client: c}
c.headers = make(map[string]string)
c.headers[ibmClientIdHeaderKey] = IbmClientId
c.headers["Authorization"] = fmt.Sprintf("Bearer %s", apiKey)
return c
}
func (c *Client) NewRequest(ctx context.Context, method, urlStr string, body interface{}) (*http.Request, error) {
var req *http.Request
u, err := c.BaseURL.Parse(urlStr)
if err != nil {
return nil, err
}
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
req, err = http.NewRequest(method, u.String(), nil)
if err != nil {
return nil, err
}
default:
buf := new(bytes.Buffer)
if body != nil {
err = json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err = http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", mediaType)
}
c.Logger.Infof("Requesting %v %v%v", req.Method, req.URL.Host, req.URL.Path)
for k, v := range c.headers {
req.Header.Add(k, v)
}
req.Header.Set("Accept", mediaType)
req.Header.Set("User-Agent", c.UserAgent)
return req, nil
}
func DoRequestWithClient(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
req = req.WithContext(ctx)
return client.Do(req)
}
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
origURL, err := url.Parse(s)
if err != nil {
return s, err
}
origValues := origURL.Query()
newValues, err := query.Values(opt)
if err != nil {
return s, err
}
for k, v := range newValues {
origValues[k] = v
}
origURL.RawQuery = origValues.Encode()
return origURL.String(), nil
}
func newResponse(r *http.Response) *Response {
response := Response{Response: r}
return &response
}
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) {
resp, err := DoRequestWithClient(ctx, c.client, req)
if err != nil {
return nil, err
}
if c.onRequestCompleted != nil {
c.onRequestCompleted(req, resp)
}
defer func() {
// Ensure the response body is fully read and closed
// before we reconnect, so that we reuse the same TCPConnection.
// Close the previous response's body. But read at least some of
// the body so if it's small the underlying TCP connection will be
// re-used. No need to check for errors: if it fails, the Transport
// won't reuse it anyway.
const maxBodySlurpSize = 2 << 10
if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
_, copyErr := io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
if copyErr != nil {
err = copyErr
}
}
if rerr := resp.Body.Close(); err == nil {
err = rerr
}
}()
response := newResponse(resp)
err = CheckResponse(resp)
if err != nil {
return response, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
if err != nil {
return nil, err
}
} else {
err = newJSONParser(v)(resp)
if err != nil {
return nil, err
}
}
}
return response, err
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %v",
r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.Message)
}
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r, StatusCode: r.StatusCode, Conflict: nil}
data, err := ioutil.ReadAll(r.Body)
if err == nil && len(data) > 0 {
// 400 and 500 errors use the same underlying type at Mobilepay.
conflictError := ConflictError{}
err := json.Unmarshal(data, &conflictError)
if err == nil {
errorResponse.Conflict = &conflictError
}
// if we can't decode the json response into our error struct or if its is empty
// return the raw body into the message property of the error.
if err != nil || (ConflictError{}) == conflictError {
errorResponse.Message = string(data)
}
}
return errorResponse
}