-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgorecurly.go
1253 lines (1176 loc) · 32.9 KB
/
gorecurly.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Recurly Client Library for go
//Works with version 2 of API only
package gorecurly
//TODO: Do all tests, do with mock server, need to fix URL so that it can be overriden
//TODO: Check all comments when finished
//TODO: Change all paging to new request params
//TODO: Check that state is working with lists
//TODO: Introduce stubs for all resources
//TODO: PDF Invoice
//TODO: Recurly.js signing
//TODO: transparent post (probably not)
//TODO: Double check fields and make sure no new fields were added
//TODO: Option to add no auth to header "Recurly-Skip-Authorization: true"
//TODO: Maybe some examples fetching with goroutines
//TODO: Add a variable to test if subscription is in trial
//TODO: Custom function to calculate account balance
//TODO: Custom function to calculate next billing amt
//TODO: Discount in cents for coupons not working
//TODO: Handle push notifications
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
URL = "https://api.recurly.com/v2/"
libversion = "0.4"
libname = "Recurly-Go"
ACCOUNTS = "accounts"
ADJUSTMENTS = "adjustments"
BILLINGINFO = "billing_info"
COUPONS = "coupons"
COUPONREDEMPTIONS = "redemption"
INVOICES = "invoices"
PLANS = "plans"
PLANADDONS = "add_ons"
SUBSCRIPTIONS = "subscriptions"
TRANSACTIONS = "transactions"
)
//Generic Reader
type nopCloser struct {
io.Reader
}
//functions
//Initialize the Recurly package with your apikey and your jskey
func InitRecurly(apikey string, jskey string) *Recurly {
r := new(Recurly)
r.apiKey = apikey
r.JSKey = jskey
r.url = URL
return r
}
//interfaces
//Paging interface to allow Next,Prev,Start
type Pager interface {
getRawBody() []byte
}
//Recurly errors
var Error400 = errors.New("The request was invalid or could not be understood by the server. Resubmitting the request will likely result in the same error.")
var Error401 = errors.New("Your API key is missing or invalid.")
var Error402 = errors.New("Your Recurly account is in production mode but is not in good standing. Please pay any outstanding invoices.")
var Error403 = errors.New("The login is attempting to perform an action it does not have privileges to access. Verify your login credentials are for the appropriate account.")
var Error404 = errors.New("The resource was not found with the given identifier. The response body will explain which resource was not found.")
var Error405 = errors.New("The requested method is not valid at the given URL.")
var Error406 = errors.New("The request's Accept header is not set to application/xml")
var Error412 = errors.New("The request was unsuccessful because a condition was not met. For example, this message may be returned if you attempt to cancel a subscription for an account that has no subscription.")
var Error429 = errors.New("You have made too many API requests in the last hour. Future API requests will be ignored until the beginning of the next hour.")
//Recurly Generic Errors
type RecurlyError struct {
XMLName xml.Name `xml:"error"`
statusCode int
Symbol string `xml:"symbol"`
Description string `xml:"description"`
Details string `xml:"details"`
}
//Recurly Validation Errors Array
type RecurlyValidationErrors struct {
XMLName xml.Name `xml:"errors"`
statusCode int
Errors []RecurlyValidationError `xml:"error"`
}
//Recurly validation error
type RecurlyValidationError struct {
XMLName xml.Name `xml:"error"`
FieldName string `xml:"field,attr"`
Symbol string `xml:"symbol,attr"`
Description string `xml:",innerxml"`
}
//Parse Recurly XML to create a Recurly Error
func CreateRecurlyStandardError(resp *http.Response) (r RecurlyError) {
r.statusCode = resp.StatusCode
if xmlstring, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if xmlerr := xml.Unmarshal(xmlstring, &r); xmlerr != nil {
r.Description = string(xmlstring)
}
}
return r
}
//Parse Recurly XML to create a Validation Error
func CreateRecurlyValidationError(resp *http.Response) (r RecurlyValidationErrors) {
r.statusCode = resp.StatusCode
if xmlstring, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if xmlerr := xml.Unmarshal(xmlstring, &r); xmlerr != nil {
//r.Description = xmlerr.Error()
println(xmlerr.Error())
}
}
return r
}
//Filter to decide which error type to create
func createRecurlyError(resp *http.Response) error {
switch resp.StatusCode {
case 400:
return Error400
case 401:
return Error401
case 402:
return Error402
case 403:
return Error403
case 404:
return Error404
case 405:
return Error405
case 406:
return Error406
case 412:
return Error412
case 429:
return Error429
case 422:
return CreateRecurlyValidationError(resp)
}
return CreateRecurlyStandardError(resp)
}
//Formatted General Error
func (r RecurlyError) Error() string {
return fmt.Sprintf("Recurly Error: %s , %s %s Status Code: %v", r.Symbol, r.Description, r.Details, r.statusCode)
}
//Formatted Validation Error
func (r RecurlyValidationErrors) Error() string {
var rtnString string
for _, v := range r.Errors {
rtnString += v.FieldName + " " + v.Description + "\n"
}
return fmt.Sprintf("You have the following validation errors:\n%s", rtnString)
}
//Main Recurly Client
type Recurly struct {
apiKey, JSKey, url string
debug bool
}
//Set verbose debugging
func (r *Recurly) EnableDebug() {
r.debug = true
}
//Get a list of accounts
func (r *Recurly) GetAccounts(params ...url.Values) (AccountList, error) {
accountlist := AccountList{}
sendvars := accountlist.initParams(params)
if err := accountlist.initList(ACCOUNTS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(accountlist.getRawBody(), &accountlist); xmlerr == nil {
for k, _ := range accountlist.Account {
accountlist.Account[k].r = r
accountlist.Account[k].endpoint = ACCOUNTS
}
accountlist.r = r
return accountlist, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return accountlist, xmlerr
}
} else {
return accountlist, err
}
return accountlist, nil
}
//Get a list of adjustments for an account_code
func (r *Recurly) GetAdjustments(account_code string, params ...url.Values) (AdjustmentList, error) {
adjlist := AdjustmentList{}
sendvars := adjlist.initParams(params)
if err := adjlist.initList(ACCOUNTS+"/"+account_code+"/"+ADJUSTMENTS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(adjlist.getRawBody(), &adjlist); xmlerr == nil {
for k, _ := range adjlist.Adjustments {
adjlist.Adjustments[k].r = r
adjlist.Adjustments[k].endpoint = ADJUSTMENTS
}
adjlist.r = r
adjlist.AccountCode = account_code
return adjlist, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return adjlist, xmlerr
}
} else {
return adjlist, err
}
return adjlist, nil
}
//Get a list of coupons
func (r *Recurly) GetCoupons(params ...url.Values) (CouponList, error) {
cplist := CouponList{}
sendvars := cplist.initParams(params)
if err := cplist.initList(COUPONS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(cplist.getRawBody(), &cplist); xmlerr == nil {
for k, _ := range cplist.Coupons {
cplist.Coupons[k].r = r
cplist.Coupons[k].endpoint = COUPONS
}
cplist.r = r
return cplist, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return cplist, xmlerr
}
} else {
return cplist, err
}
return cplist, nil
}
//Get a list of invoices for an account_code
func (r *Recurly) GetAccountInvoices(account_code string, params ...url.Values) (AccountInvoiceList, error) {
invoicelist := AccountInvoiceList{}
sendvars := invoicelist.initParams(params)
if err := invoicelist.initList(ACCOUNTS+"/"+account_code+"/"+INVOICES, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(invoicelist.getRawBody(), &invoicelist); xmlerr == nil {
for k, _ := range invoicelist.Invoices {
invoicelist.Invoices[k].r = r
invoicelist.Invoices[k].endpoint = INVOICES
}
invoicelist.r = r
invoicelist.AccountCode = account_code
return invoicelist, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return invoicelist, xmlerr
}
} else {
return invoicelist, err
}
return invoicelist, nil
}
//Get a list of invoices
func (r *Recurly) GetInvoices(params ...url.Values) (InvoiceList, error) {
invoicelist := InvoiceList{}
sendvars := invoicelist.initParams(params)
if err := invoicelist.initList(INVOICES, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(invoicelist.getRawBody(), &invoicelist); xmlerr == nil {
for k, _ := range invoicelist.Invoices {
invoicelist.Invoices[k].r = r
invoicelist.Invoices[k].endpoint = INVOICES
}
invoicelist.r = r
return invoicelist, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return invoicelist, xmlerr
}
} else {
return invoicelist, err
}
return invoicelist, nil
}
//Get a list of Plans
func (r *Recurly) GetPlans(params ...url.Values) (PlanList, error) {
planlist := PlanList{}
sendvars := planlist.initParams(params)
if err := planlist.initList(PLANS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(planlist.getRawBody(), &planlist); xmlerr == nil {
for k, _ := range planlist.Plans {
planlist.Plans[k].r = r
planlist.Plans[k].endpoint = PLANS
}
planlist.r = r
return planlist, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return planlist, xmlerr
}
} else {
return planlist, err
}
return planlist, nil
}
//Get a list of add ons for a plan_code
func (r *Recurly) GetPlanAddOns(plan_code string, params ...url.Values) (planaddonlist PlanAddOnList, e error) {
sendvars := planaddonlist.initParams(params)
if err := planaddonlist.initList(PLANS+"/"+plan_code+"/add_ons", sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(planaddonlist.getRawBody(), &planaddonlist); xmlerr == nil {
for k, _ := range planaddonlist.AddOns {
planaddonlist.AddOns[k].r = r
}
planaddonlist.r = r
planaddonlist.PlanCode = plan_code
return
} else {
if r.debug {
println(xmlerr.Error())
}
return planaddonlist, xmlerr
}
} else {
return planaddonlist, err
}
return
}
//Get a list of subscriptions
func (r *Recurly) GetSubscriptions(params ...url.Values) (SubscriptionList, error) {
subs := SubscriptionList{}
sendvars := subs.initParams(params)
if err := subs.initList(SUBSCRIPTIONS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(subs.getRawBody(), &subs); xmlerr == nil {
for k, _ := range subs.Subscriptions {
subs.Subscriptions[k].r = r
subs.Subscriptions[k].endpoint = SUBSCRIPTIONS
}
subs.r = r
return subs, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return subs, xmlerr
}
} else {
return subs, err
}
return subs, nil
}
//Get a list of subscriptions for an account_code
func (r *Recurly) GetAccountSubscriptions(account_code string, params ...url.Values) (AccountSubscriptionList, error) {
subs := AccountSubscriptionList{}
sendvars := subs.initParams(params)
if err := subs.initList(ACCOUNTS+"/"+account_code+"/"+SUBSCRIPTIONS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(subs.getRawBody(), &subs); xmlerr == nil {
for k, _ := range subs.Subscriptions {
subs.Subscriptions[k].r = r
subs.Subscriptions[k].endpoint = SUBSCRIPTIONS
}
subs.r = r
subs.AccountCode = account_code
return subs, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return subs, xmlerr
}
} else {
return subs, err
}
return subs, nil
}
//Get a list of transactions
func (r *Recurly) GetTransactions(params ...url.Values) (TransactionList, error) {
subs := TransactionList{}
sendvars := subs.initParams(params)
if err := subs.initList(TRANSACTIONS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(subs.getRawBody(), &subs); xmlerr == nil {
for k, _ := range subs.Transactions {
subs.Transactions[k].r = r
subs.Transactions[k].endpoint = TRANSACTIONS
}
subs.r = r
return subs, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return subs, xmlerr
}
} else {
return subs, err
}
return subs, nil
}
//Get a list of transactions for an account_code
func (r *Recurly) GetAccountTransactions(account_code string, params ...url.Values) (AccountTransactionList, error) {
subs := AccountTransactionList{}
sendvars := subs.initParams(params)
if err := subs.initList(ACCOUNTS+"/"+account_code+"/"+TRANSACTIONS, sendvars, r); err == nil {
if xmlerr := xml.Unmarshal(subs.getRawBody(), &subs); xmlerr == nil {
for k, _ := range subs.Transactions {
subs.Transactions[k].r = r
subs.Transactions[k].endpoint = TRANSACTIONS
}
subs.r = r
subs.AccountCode = account_code
return subs, nil
} else {
if r.debug {
println(xmlerr.Error())
}
return subs, xmlerr
}
} else {
return subs, err
}
return subs, nil
}
//Get a single account by account_code
func (r *Recurly) GetAccount(account_code string) (account Account, err error) {
account = r.NewAccount()
if resp, err := r.createRequest(ACCOUNTS+"/"+account_code, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &account); xmlerr != nil {
account.B = nil
return account, xmlerr
}
//everything went fine
return account, nil
} else {
//return read error
return account, readerr
}
return account, nil
} else {
return account, createRecurlyError(resp)
}
} else {
return account, err
}
return account, nil
}
//Get a single adjustment by uuid
func (r *Recurly) GetAdjustment(uuid string) (adj Adjustment, err error) {
adj = r.NewAdjustment()
if resp, err := r.createRequest(ADJUSTMENTS+"/"+uuid, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &adj); xmlerr != nil {
return adj, xmlerr
}
//everything went fine
return adj, nil
} else {
//return read error
return adj, readerr
}
return adj, nil
} else {
return adj, createRecurlyError(resp)
}
} else {
return adj, err
}
return adj, nil
}
//Get a single coupon redemption by account_code
func (r *Recurly) GetCouponRedemption(account_code string) (red Redemption, err error) {
red.r = r
red.AccountCode = account_code
if resp, err := r.createRequest(ACCOUNTS+"/"+account_code+"/redemption", "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &red); xmlerr != nil {
return red, xmlerr
}
//everything went fine
return red, nil
} else {
//return read error
return red, readerr
}
return red, nil
} else {
return red, createRecurlyError(resp)
}
} else {
return red, err
}
return red, nil
}
//Get a single coupon by uuid
func (r *Recurly) GetCoupon(uuid string) (coupon Coupon, err error) {
coupon = r.NewCoupon()
if resp, err := r.createRequest(COUPONS+"/"+uuid, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &coupon); xmlerr != nil {
return coupon, xmlerr
}
//everything went fine
return coupon, nil
} else {
//return read error
return coupon, readerr
}
return coupon, nil
} else {
return coupon, createRecurlyError(resp)
}
} else {
return coupon, err
}
return coupon, nil
}
//Get invoice by uuid
func (r *Recurly) GetInvoice(uuid string) (invoice Invoice, err error) {
invoice = r.NewInvoice()
if resp, err := r.createRequest(INVOICES+"/"+uuid, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &invoice); xmlerr != nil {
return invoice, xmlerr
}
//everything went fine
return invoice, nil
} else {
//return read error
return invoice, readerr
}
return invoice, nil
} else {
return invoice, createRecurlyError(resp)
}
} else {
return invoice, err
}
return invoice, nil
}
//Get a single plan by plan_code
func (r *Recurly) GetPlan(plan_code string) (plan Plan, err error) {
plan = r.NewPlan()
if resp, err := r.createRequest(PLANS+"/"+plan_code, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &plan); xmlerr != nil {
return plan, xmlerr
}
//everything went fine
return plan, err
} else {
//return read error
return plan, readerr
}
return plan, nil
} else {
return plan, createRecurlyError(resp)
}
} else {
return plan, err
}
return plan, nil
}
//Get a single plan add on by plan_code and add_on_code
func (r *Recurly) GetPlanAddOn(plan_code, add_on_code string) (plan PlanAddOn, err error) {
plan = r.NewPlanAddOn()
if resp, err := r.createRequest(PLANS+"/"+plan_code+"/add_ons/"+add_on_code, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &plan); xmlerr != nil {
return plan, xmlerr
}
//everything went fine
return plan, err
} else {
//return read error
return plan, readerr
}
return plan, nil
} else {
return plan, createRecurlyError(resp)
}
} else {
return plan, err
}
return plan, nil
}
//Get a single subscription by uuid
func (r *Recurly) GetSubscription(uuid string) (sub Subscription, err error) {
sub = r.NewSubscription()
if resp, err := r.createRequest(SUBSCRIPTIONS+"/"+uuid, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &sub); xmlerr != nil {
return sub, xmlerr
}
//everything went fine
return sub, nil
} else {
//return read error
return sub, readerr
}
return sub, nil
} else {
return sub, createRecurlyError(resp)
}
} else {
return sub, err
}
return sub, nil
}
//Get a single transaction by uuid
func (r *Recurly) GetTransaction(uuid string) (tran Transaction, err error) {
tran = r.NewTransaction()
if resp, err := r.createRequest(TRANSACTIONS+"/"+uuid, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &tran); xmlerr != nil {
return tran, xmlerr
}
//everything went fine
return tran, nil
} else {
//return read error
return tran, readerr
}
return tran, nil
} else {
return tran, createRecurlyError(resp)
}
} else {
return tran, err
}
return tran, nil
}
//Create a new Account
func (r *Recurly) NewAccount() (account Account) {
account.r = r
account.endpoint = ACCOUNTS
return
}
//Create a new Adjustment
func (r *Recurly) NewAdjustment() (adj Adjustment) {
adj.r = r
adj.endpoint = ADJUSTMENTS
return
}
//Create new Billing Info
func (r *Recurly) NewBillingInfo() (bi BillingInfo) {
bi.r = r
bi.endpoint = BILLINGINFO
return
}
//Create a new Coupon
func (r *Recurly) NewCoupon() (c Coupon) {
c.r = r
c.endpoint = COUPONS
return
}
//Create a new Plan
func (r *Recurly) NewPlan() (plan Plan) {
plan.r = r
plan.SetupFeeInCents = new(CurrencyArray)
plan.UnitAmountInCents = new(CurrencyArray)
plan.endpoint = PLANS
return
}
//Create a new plan Add On
func (r *Recurly) NewPlanAddOn() (planAddOn PlanAddOn) {
planAddOn.r = r
planAddOn.UnitAmountInCents = new(CurrencyArray)
return
}
//Create a new Subscription
func (r *Recurly) NewSubscription() (subscription Subscription) {
subscription.r = r
subscription.endpoint = SUBSCRIPTIONS
return
}
//Create a new transaction
func (r *Recurly) NewTransaction() (transaction Transaction) {
transaction.r = r
transaction.endpoint = TRANSACTIONS
return
}
//Invoice Pending Charges on an account
func (r *Recurly) InvoicePendingCharges(account_code string) (invoice Invoice, e error) {
invoice.r = r
e = invoice.r.doCreate(&invoice, ACCOUNTS+"/"+account_code+"/invoices")
return
}
//Create a new Invoice
func (r *Recurly) NewInvoice() (invoice Invoice) {
invoice.r = r
invoice.endpoint = INVOICES
return
}
//Get a single accounts billing info by account_code
func (r *Recurly) GetBillingInfo(account_code string) (bi BillingInfo, err error) {
bi = r.NewBillingInfo()
if resp, err := r.createRequest(ACCOUNTS+"/"+account_code+"/"+BILLINGINFO, "GET", nil, nil); err == nil {
if resp.StatusCode == 200 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, &bi); xmlerr != nil {
return bi, xmlerr
}
//everything went fine
bi.Account.endpoint = ACCOUNTS
return bi, nil
} else {
//return read error
return bi, readerr
}
return bi, nil
} else {
return bi, createRecurlyError(resp)
}
} else {
return bi, err
}
return bi, nil
}
//Create a request to Recurly and return that response object
func (r *Recurly) createRequest(endpoint string, method string, params url.Values, msgbody []byte) (*http.Response, error) {
client := &http.Client{}
u, err := url.Parse(r.url + endpoint)
if err != nil {
return nil, err
}
u.RawQuery = u.RawQuery + params.Encode()
body := nopCloser{bytes.NewBufferString(string(msgbody))}
if r.debug {
fmt.Printf("Endpoint Requested: %s Method: %s Body: %s\n", u.String(), method, string(msgbody))
}
if req, err := http.NewRequest(method, u.String(), body); err != nil {
return nil, err
} else {
req.Header.Add("Accept", "application/xml")
req.Header.Add("Accept-Language", "en-US")
req.Header.Add("User-Agent", libname+" version="+libversion)
req.Header.Add("Content-Type", "application/xml; charset=utf-8")
req.ContentLength = int64(len(string(msgbody)))
req.SetBasicAuth(r.apiKey, "")
if resp, resperr := client.Do(req); resperr == nil {
return resp, nil
} else {
return nil, resperr
}
}
return nil, nil
}
//process create request and return the updated interface
func (r *Recurly) doCreateReturn(v, ret interface{}, endpoint string) (e error) {
if xmlstring, err := xml.MarshalIndent(v, "", " "); err == nil {
xmlstring = []byte(xml.Header + string(xmlstring))
if r.debug {
fmt.Printf("%s\n", xmlstring)
}
if resp, reqerr := r.createRequest(endpoint, "POST", nil, xmlstring); reqerr == nil {
if resp.StatusCode < 400 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, ret); xmlerr != nil {
return xmlerr
}
//everything went fine
return nil
} else {
//return read error
return readerr
}
return nil
} else {
return createRecurlyError(resp)
}
} else {
return reqerr
}
} else {
return err
}
return nil
}
//Create a resource from struct, uses POST method
func (r *Recurly) doCreate(v interface{}, endpoint string) error {
if xmlstring, err := xml.MarshalIndent(v, "", " "); err == nil {
xmlstring = []byte(xml.Header + string(xmlstring))
if r.debug {
fmt.Printf("%s\n", xmlstring)
}
if resp, reqerr := r.createRequest(endpoint, "POST", nil, xmlstring); reqerr == nil {
if resp.StatusCode < 400 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml
if xmlerr := xml.Unmarshal(body, v); xmlerr != nil {
return xmlerr
}
//everything went fine
return nil
} else {
//return read error
return readerr
}
return nil
} else {
return createRecurlyError(resp)
}
} else {
return reqerr
}
} else {
return err
}
return nil
}
//Update a resource from Struct, then return the updated object uses PUT method
func (r *Recurly) doUpdateReturn(v, ret interface{}, endpoint string) error {
if xmlstring, err := xml.MarshalIndent(v, "", " "); err == nil {
if v != nil {
xmlstring = []byte(xml.Header + string(xmlstring))
}
if r.debug {
fmt.Printf("%s\n", xmlstring)
}
if resp, reqerr := r.createRequest(endpoint, "PUT", nil, xmlstring); reqerr == nil {
if resp.StatusCode < 400 {
if body, readerr := ioutil.ReadAll(resp.Body); readerr == nil {
if r.debug {
println(resp.Status)
for k, _ := range resp.Header {
println(k + ":" + resp.Header[k][0])
}
fmt.Printf("%s\n", body)
fmt.Printf("Content-Length:%v\n", resp.ContentLength)
}
//load object xml