-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathservice.go
324 lines (296 loc) · 8.17 KB
/
service.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
// Copyright 2014 Mathias Monnerville. All rights reserved.
// Use of this source code is governed by a GPL
// license that can be found in the LICENSE file.
// Package mango is a library for the MangoPay service v2.
//
// MangoPay is a platform that allows to accept payments and manage e-money
// using wallets. See http://www.mangopay.com.
//
// First, create an account with a unique Id to authenticate to the service:
//
// conf, err := mango.RegisterClient("myclientid", "My Company",
// "[email protected]", mango.Sandbox)
// if err != nil {
// panic(err)
// }
//
// Or use existing credentials:
//
// conf, err := mango.NewConfig("myclientid", "My Company",
// "[email protected]", "passwd", "sandbox")
//
// Then, choose an authentication mode (OAuth2.0 or Basic) to use with the service:
//
// service, err := mango.NewMangoPay(conf, mango.OAuth)
package mango
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"
"time"
)
// Request execution environment (production or sandbox).
type ExecEnvironment int
const (
Production ExecEnvironment = iota
Sandbox
)
// Base URLs to execution environements
var rootURLs = map[ExecEnvironment]string{
Production: "https://api.mangopay.com/v2/",
Sandbox: "https://api.sandbox.mangopay.com/v2/",
}
// The default HTTP client to use with the MangoPay api.
var DefaultClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{MaxVersion: tls.VersionTLS12},
},
}
// The Mangopay service.
type MangoPay struct {
clientId string // MangoPay partner ID
password string
env ExecEnvironment // Live or testing env
rootURL *url.URL // Base API URL for the current execution environment
verbosity Level
authMethod AuthMode
// To track the current token during its lifetime
oauth *oAuth2
}
// ProcessIdent identifies the current operation.
type ProcessIdent struct {
Id string
Tag string
CreationDate int64
}
// ProcessReply holds commong fields part of MangoPay API replies.
type ProcessReply struct {
ProcessIdent
Status string
ResultCode string
ResultMessage string
ExecutionDate int64
}
type HTTPError struct {
Code int
Message string
Details map[string]interface{}
}
func (e HTTPError) Error() string {
return fmt.Sprintf("Code: %d, Message: %s, Details: %s", e.Code, e.Message, e.Details)
}
// NewMangoPay creates a suitable environment for accessing
// the web service. Default verbosity level is set to Info, which can be
// changed through the use of Option().
func NewMangoPay(auth *Config, mode AuthMode) (*MangoPay, error) {
if auth == nil {
return nil, errors.New("nil config")
}
if auth.Env == "sandbox" {
auth.env = Sandbox
} else if auth.Env == "production" {
auth.env = Production
} else {
return nil, errors.New("unknown exec environment: " + auth.Env)
}
u, err := url.Parse(rootURLs[auth.env])
if err != nil {
return nil, err
}
return &MangoPay{auth.ClientId, auth.Passphrase, auth.env, u, Info, mode, nil}, nil
}
// Option set various options like verbosity etc.
func (m *MangoPay) Option(opts ...option) {
for _, opt := range opts {
opt(m)
}
}
// request prepares and sends a well formatted HTTP request to the
// mangopay service.
func (s *MangoPay) request(ma mangoAction, data JsonObject) (*http.Response, error) {
mr, ok := mangoRequests[ma]
if !ok {
return nil, errors.New("Action not implemented.")
}
// Create the submit url
path := mr.Path
if mr.PathValues != nil {
// Substitute path variables, if any
for name := range mr.PathValues {
if _, ok := data[name]; !ok {
return nil, errors.New(fmt.Sprintf("missing keyword %s", name))
}
path = strings.Replace(path, "{{"+name+"}}", fmt.Sprintf("%v", data[name]), -1)
}
} else {
path = mr.Path
}
body, err := json.Marshal(data)
if err != nil {
return nil, err
}
resp, err := s.rawRequest(mr.Method, "application/json",
fmt.Sprintf("%s%s%s", s.rootURL, s.clientId, path), body, true)
return resp, err
}
// rawRequest sends an HTTP request with method method to an arbitrary URI.
func (s *MangoPay) rawRequest(method, contentType string, uri string, body []byte, useAuth bool) (*http.Response, error) {
if contentType == "" {
return nil, errors.New("empty request's content type")
}
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, u.String(), strings.NewReader(string(body)))
if err != nil {
return nil, err
}
// Set header for basic auth
if useAuth {
if s.authMethod == BasicAuth {
req.Header.Set("Authorization", basicAuthorization(s.clientId, s.password))
} else {
o, err := oAuthAuthorization(s)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", o)
}
}
req.Header.Set("Content-Type", contentType)
if s.verbosity == Debug {
fmt.Println(">>>>>>>>>>>>>>>>>>>>>> DEBUG REQUEST")
fmt.Printf("%s %s\n\n", req.Method, req.URL.String())
for k, v := range req.Header {
for _, j := range v {
fmt.Printf("%s: %v\n", k, j)
}
}
rb := string(body)
if rb != "null" {
fmt.Printf("\n%s\n", rb)
}
fmt.Println("\nSending request ...")
fmt.Println("<<<<<<<<<<<<<<<<<<<<<< DEBUG REQUEST")
}
// Send request
resp, err := NewDefaultHTTPClientRetryWrap(DefaultClient).do(req)
// Handle response status code
if err == nil && resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
j := JsonObject{}
err = s.unMarshalJSONResponse(resp, &j)
if err != nil {
return nil, err
}
HTTPErr := HTTPError{
Code: resp.StatusCode,
}
if msg, ok := j["Message"]; ok {
HTTPErr.Message = msg.(string)
} else {
HTTPErr.Message = fmt.Sprintf("Response body: '%s'", j)
}
if details, ok := j["errors"]; ok {
if HTTPErr.Details, ok = details.(map[string]interface{}); !ok {
HTTPErr.Details = map[string]interface{}{"Error": "Error details returned is not map[string]interface{}"}
}
}
err = HTTPErr
}
return resp, err
}
// Unmarshal a JSON HTTP response into an instance.
func (m *MangoPay) unMarshalJSONResponse(resp *http.Response, v interface{}) error {
if resp == nil {
return errors.New("can't unmarshal nil response")
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if m.verbosity == Debug {
fmt.Println(">>>>>>>>>>>>>>>>>>>>>> DEBUG RESPONSE")
fmt.Printf("Status code: %d\n\n", resp.StatusCode)
for k, v := range resp.Header {
for _, j := range v {
fmt.Printf("%s: %v\n", k, j)
}
}
fmt.Printf("\n%s\n", string(b))
fmt.Println("<<<<<<<<<<<<<<<<<<<<<< DEBUG RESPONSE")
}
if err := json.Unmarshal(b, v); err != nil {
return errors.New(fmt.Sprintf("error: %s, Mangopay server response: %s", err.Error(), string(b)))
}
return nil
}
// Generic request for any object.
func (m *MangoPay) anyRequest(o interface{}, action mangoAction, data JsonObject) (interface{}, error) {
resp, err := m.request(action, data)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusNoContent {
return nil, nil
}
t := reflect.TypeOf(o)
if t.Kind() == reflect.Ptr {
v := reflect.ValueOf(o)
t = reflect.Indirect(v).Type()
}
ins := reflect.New(t).Interface()
if err := m.unMarshalJSONResponse(resp, ins); err != nil {
return nil, err
}
return ins, nil
}
func unixTimeToString(t int64) string {
if t > 0 {
return time.Unix(t, 0).String()
}
return "Never"
}
// Use reflection to print data structures.
func struct2string(c interface{}) string {
var b bytes.Buffer
e := reflect.ValueOf(c).Elem()
for i := 0; i < e.NumField(); i++ {
sfield := e.Type().Field(i)
// Skip unexported fields
if sfield.PkgPath != "" {
continue
}
name := sfield.Name
val := e.Field(i).Interface()
// Handle embedded types
if sfield.Anonymous {
b.Write([]byte(struct2string(e.Field(i).Addr().Interface())))
} else {
if name == "CreationDate" || name == "ExecutionDate" ||
name == "Birthday" {
val = unixTimeToString(val.(int64))
}
b.Write([]byte(fmt.Sprintf("%-24s: %v\n", name, val)))
}
}
return b.String()
}
func consumerId(c Consumer) string {
id := ""
switch c.(type) {
case *LegalUser:
id = c.(*LegalUser).Id
case *NaturalUser:
id = c.(*NaturalUser).Id
}
return id
}