-
Notifications
You must be signed in to change notification settings - Fork 1
/
gocardless.go
301 lines (259 loc) · 7.8 KB
/
gocardless.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
package gocardless
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/mitchellh/mapstructure"
"strings"
)
const (
// library version
version = "1.1"
// defaultHTTPTimeout is the default timeout on the http client
defaultHTTPTimeout = 40 * time.Second
baseURL = "https://api-sandbox.gocardless.com"
// User agent used when communicating with the Gocardless API.
userAgent = "gocardless-webhook-service/" + version
goCardlessApiVersion = "2015-07-06"
acceptJsonType = "application/json"
)
//func main() {
//
// apiKey := "sandbox_o55p5OowBX59Rd8aDR7c_25LQdBTHRaACeVnqj0o"
//
// //second param is an optional http client, allowing overriding of the HTTP client to use.
// //This is useful if you're running in a Google AppEngine environment
// //where the http.DefaultClient is not available.
// client := NewClient(apiKey, nil)
// client.LoggingEnabled = true
//
// subscriptionsListReq := &SubscriptionListRequest{
// Limit: 100,
// }
// // list all subscriptions
// _, err := client.Subscription.ListSubscriptions(subscriptionsListReq)
// if err != nil {
// fmt.Sprintf("The error while getting list of subscriptions is :%s", err.Error())
// }
//
//}
type service struct {
client *Client
}
// Client manages communication with the GoCardless API
type Client struct {
common service // Reuse a single struct instead of allocating one for each service on the heap.
client *http.Client // HTTP client used to communicate with the API.
// the API Key used to authenticate all GoCardless API requests
key string
secret string // don't know if this is necessary though
baseURL *url.URL
logger Logger
BankDetailsLookup *BankDetailsLookupService
Creditor *CreditorService
CreditorBankAccount *CreditorBankAccountService
Customer *CustomerService
CustomerBankAccount *CustomerBankAccountService
Event *EventService
Mandate *MandateService
MandatePdf *MandatePdfService
Payout *PayoutService
Payment *PaymentService
RedirectFlow *RedirectFlowService
Refund *RefundService
Subscription *SubscriptionService
LoggingEnabled bool
Logger Logger
}
type Logger interface {
Printf(format string, v ...interface{})
}
type Metadata map[string]interface{}
// Response represents arbitrary response data
type Response map[string]interface{}
// RequestValues aliased to url.Values as a workaround
type RequestValues url.Values
func (v RequestValues) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{}, 3)
for k, val := range v {
m[k] = val[0]
}
return json.Marshal(m)
}
type ListMeta struct {
Total int `json:"total"`
Skipped int `json:"skipped"`
PerPage int `json:"perPage"`
Page int `json:"page"`
PageCount int `json:"pageCount"`
}
// NewClient creates a new GoCardless API client with the given API key
// and HTTP client, allowing overriding of the HTTP client to use.
// This is useful if you're running in a Google AppEngine environment
// where the http.DefaultClient is not available.
func NewClient(key string, httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = &http.Client{Timeout: defaultHTTPTimeout}
}
u, _ := url.Parse(baseURL)
c := &Client{
client: httpClient,
key: key,
baseURL: u,
LoggingEnabled: true,
Logger: log.New(os.Stderr, "", log.LstdFlags),
}
c.common.client = c
c.BankDetailsLookup = (*BankDetailsLookupService)(&c.common)
c.Customer = (*CustomerService)(&c.common)
c.CustomerBankAccount = (*CustomerBankAccountService)(&c.common)
c.Creditor = (*CreditorService)(&c.common)
c.CreditorBankAccount = (*CreditorBankAccountService)(&c.common)
c.BankDetailsLookup = (*BankDetailsLookupService)(&c.common)
c.Event = (*EventService)(&c.common)
c.Mandate = (*MandateService)(&c.common)
c.MandatePdf = (*MandatePdfService)(&c.common)
c.Payout = (*PayoutService)(&c.common)
c.Payment = (*PaymentService)(&c.common)
c.RedirectFlow = (*RedirectFlowService)(&c.common)
c.Refund = (*RefundService)(&c.common)
c.Subscription = (*SubscriptionService)(&c.common)
return c
}
func (c *Client) Call(method string, path string, body, v interface{}) error {
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return err
}
}
u, _ := c.baseURL.Parse(path)
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
if c.LoggingEnabled {
c.Logger.Printf("Cannot create GoCardless request: %v\n", err)
}
return err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "Bearer "+c.key)
// this header sets the api version
req.Header.Set("GoCardless-Version", goCardlessApiVersion)
req.Header.Set("Accept", acceptJsonType)
if ua := req.Header.Get("User-Agent"); ua == "" {
req.Header.Set("User-Agent", userAgent)
} else {
req.Header.Set("User-Agent", userAgent+" "+ua)
}
if c.LoggingEnabled {
c.Logger.Printf("Requesting %v %v%v\n", req.Method, req.URL.Host, req.URL.Path)
}
start := time.Now()
resp, err := c.client.Do(req)
if err != nil {
return err
}
if c.LoggingEnabled {
c.Logger.Printf("Completed in %v\n", time.Since(start))
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
if c.LoggingEnabled {
c.Logger.Printf("Request to GoCardless failed: %v\n", err)
}
return err
}
var respMap Response
json.Unmarshal(respBody, &respMap)
fmt.Printf("RESPONSE %s \n %+v", u, string(respBody[:]))
if strings.Contains(resp.Status, "20") && resp.StatusCode >= 400 {
if c.LoggingEnabled {
c.Logger.Printf("GoCardless error: %v\n", err)
}
return responseToError(resp, respMap)
}
return checkResponse(respMap, v)
}
func (c *Client) ResolveCardBIN(bin int) (*Response, error) {
u := fmt.Sprintf("/decision/bin/%d", bin)
resp := &Response{}
err := c.Call("GET", u, nil, resp)
return resp, err
}
func (c *Client) CheckBalance(bin int) (*Response, error) {
resp := &Response{}
err := c.Call("GET", "balance", nil, resp)
return resp, err
}
func (c *Client) GetSessionTimeout() (*Response, error) {
resp := &Response{}
err := c.Call("GET", "/integration/payment_session_timeout", nil, resp)
return resp, err
}
func (c *Client) UpdateSessionTimeout(timeout int) (*Response, error) {
data := url.Values{}
data.Add("timeout", string(timeout))
resp := &Response{}
u := "/integration/payment_session_timeout"
err := c.Call("PUT", u, data, resp)
return resp, err
}
// INTERNALS
func paginateURL(path string, count, offset int) string {
return fmt.Sprintf("%s?perPage=%d&page=%d", path, count, offset)
}
func mapstruct(data interface{}, v interface{}) error {
config := &mapstructure.DecoderConfig{
Result: v,
TagName: "json",
WeaklyTypedInput: true,
}
decoder, err := mapstructure.NewDecoder(config)
if err = decoder.Decode(data); err != nil {
return err
}
return nil
}
func getTestKey() string {
key := os.Getenv("GOCARDLESS-KEY")
if len(key) == 0 {
panic("GOCARDLESS environment variable is not set\n")
}
return key
}
func responseToError(resp *http.Response, respMap Response) error {
err := &Error{
HTTPStatusCode: resp.StatusCode,
Message: respMap["message"].(string),
URL: resp.Request.URL,
}
if errorDetails, ok := respMap["errors"]; ok {
err.Errors = errorDetails.(map[string][]interface{})
}
return err
}
func checkResponse(respMap Response, v interface{}) error {
if data, ok := respMap["data"]; ok {
switch t := respMap["data"].(type) {
case map[string]interface{}:
return mapstruct(data, v)
default:
_ = t
return mapstruct(respMap, v)
}
}
// response data does not contain data node, return anyways
return mapstruct(respMap, v)
}