forked from recurly/recurly-client-python
/
__init__.py
765 lines (590 loc) · 20.5 KB
/
__init__.py
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
import logging
from six.moves.urllib.parse import urljoin
from xml.etree import ElementTree
import defusedxml.ElementTree
import recurly
import recurly.js as js
from recurly.errors import *
from recurly.resource import Resource, Money, PageError
"""
Recurly's Python client library is an interface to its REST API.
Please see the Recurly API documentation for more information:
http://docs.recurly.com/api/
"""
__version__ = '2.2.5'
BASE_URI = 'https://%s.recurly.com/v2/'
"""The API endpoint to send requests to."""
SUBDOMAIN = 'api'
"""The subdomain of the site authenticating API requests."""
API_KEY = None
"""The API key to use when authenticating API requests."""
CA_CERTS_FILE = None
"""A file contianing a set of concatenated certificate authority certs
for validating the server against."""
DEFAULT_CURRENCY = 'USD'
"""The currency to use creating `Money` instances when one is not specified."""
SOCKET_TIMEOUT_SECONDS = None
"""The number of seconds after which to timeout requests to the Recurly API.
If unspecified, the global default timeout is used."""
def base_uri():
if SUBDOMAIN is None:
raise ValueError('recurly.SUBDOMAIN not set')
return BASE_URI % SUBDOMAIN
class Address(Resource):
nodename = 'address'
attributes = (
'address1',
'address2',
'city',
'state',
'zip',
'country',
'phone'
)
class Account(Resource):
"""A customer account."""
member_path = 'accounts/%s'
collection_path = 'accounts'
nodename = 'account'
attributes = (
'account_code',
'username',
'email',
'first_name',
'last_name',
'company_name',
'vat_number',
'tax_exempt',
'entity_use_code',
'accept_language',
'created_at',
)
_classes_for_nodename = {'address': Address}
sensitive_attributes = ('number', 'verification_value',)
def to_element(self):
elem = super(Account, self).to_element()
# Make sure the account code is always included in a serialization.
if 'account_code' not in self.__dict__: # not already included
try:
account_code = self.account_code
except AttributeError:
pass
else:
elem.append(self.element_for_value('account_code', account_code))
if 'billing_info' in self.__dict__:
elem.append(self.billing_info.to_element())
if 'address' in self.__dict__:
elem.append(self.address.to_element())
return elem
@classmethod
def all_active(cls, **kwargs):
"""Return a `Page` of active customer accounts.
This is a convenience method for `Account.all(state='active')`.
"""
return cls.all(state='active', **kwargs)
@classmethod
def all_closed(cls, **kwargs):
"""Return a `Page` of closed customer accounts.
This is a convenience method for `Account.all(state='closed')`.
"""
return cls.all(state='closed', **kwargs)
@classmethod
def all_past_due(cls, **kwargs):
"""Return a `Page` of past-due customer accounts.
This is a convenience method for `Account.all(state='past_due').
"""
return cls.all(state='past_due', **kwargs)
@classmethod
def all_subscribers(cls, **kwargs):
"""Return a `Page` of customer accounts that are subscribers.
This is a convenience method for `Account.all(state='subscriber').
"""
return cls.all(state='subscriber', **kwargs)
@classmethod
def all_non_subscribers(cls, **kwargs):
"""Return a `Page` of customer accounts that are not subscribers.
This is a convenience method for `Account.all(state='non_subscriber').
"""
return cls.all(state='non_subscriber', **kwargs)
def __getattr__(self, name):
if name == 'billing_info':
try:
billing_info_url = self._elem.find('billing_info').attrib['href']
except (AttributeError, KeyError):
raise AttributeError(name)
resp, elem = BillingInfo.element_for_url(billing_info_url)
return BillingInfo.from_element(elem)
try:
return super(Account, self).__getattr__(name)
except AttributeError:
if name == 'address':
self.address = Address()
return self.address
else:
raise AttributeError(name)
def charge(self, charge):
"""Charge (or credit) this account with the given `Adjustment`."""
url = urljoin(self._url, '%s/adjustments' % self.account_code)
return charge.post(url)
def invoice(self):
"""Create an invoice for any outstanding adjustments this account has."""
url = urljoin(self._url, '%s/invoices' % self.account_code)
response = self.http_request(url, 'POST')
if response.status != 201:
self.raise_http_error(response)
response_xml = response.read()
logging.getLogger('recurly.http.response').debug(response_xml)
elem = defusedxml.ElementTree.fromstring(response_xml)
invoice = Invoice.from_element(elem)
invoice._url = response.getheader('Location')
return invoice
def build_invoice(self):
"""Preview an invoice for any outstanding adjustments this account has."""
url = urljoin(self._url, '%s/invoices/preview' % self.account_code)
response = self.http_request(url, 'POST')
if response.status != 200:
self.raise_http_error(response)
response_xml = response.read()
logging.getLogger('recurly.http.response').debug(response_xml)
elem = ElementTree.fromstring(response_xml)
invoice = Invoice.from_element(elem)
return invoice
def notes(self):
"""Fetch Notes for this account."""
url = urljoin(self._url, '%s/notes' % self.account_code)
return Note.paginated(url)
def reopen(self):
"""Reopen a closed account."""
url = urljoin(self._url, '%s/reopen' % self.account_code)
response = self.http_request(url, 'PUT')
if response.status != 200:
self.raise_http_error(response)
response_xml = response.read()
logging.getLogger('recurly.http.response').debug(response_xml)
self.update_from_element(
defusedxml.ElementTree.fromstring(response_xml))
def subscribe(self, subscription):
"""Create the given `Subscription` for this existing account."""
url = urljoin(self._url, '%s/subscriptions' % self.account_code)
return subscription.post(url)
def update_billing_info(self, billing_info):
"""Change this account's billing information to the given `BillingInfo`."""
url = urljoin(self._url, '%s/billing_info' % self.account_code)
response = billing_info.http_request(url, 'PUT', billing_info,
{'Content-Type': 'application/xml; charset=utf-8'})
if response.status == 200:
pass
elif response.status == 201:
billing_info._url = response.getheader('Location')
else:
billing_info.raise_http_error(response)
response_xml = response.read()
logging.getLogger('recurly.http.response').debug(response_xml)
billing_info.update_from_element(
defusedxml.ElementTree.fromstring(response_xml))
class BillingInfo(Resource):
"""A set of billing information for an account."""
nodename = 'billing_info'
attributes = (
'type',
'first_name',
'last_name',
'number',
'verification_value',
'year',
'month',
'start_month',
'start_year',
'issue_number',
'company',
'address1',
'address2',
'city',
'state',
'zip',
'country',
'phone',
'vat_number',
'ip_address',
'ip_address_country',
'card_type',
'first_six',
'last_four',
'paypal_billing_agreement_id',
'amazon_billing_agreement_id',
'token_id',
)
sensitive_attributes = ('number', 'verification_value')
xml_attribute_attributes = ('type',)
class Coupon(Resource):
"""A coupon for a customer to apply to their account."""
member_path = 'coupons/%s'
collection_path = 'coupons'
nodename = 'coupon'
attributes = (
'coupon_code',
'name',
'discount_type',
'discount_percent',
'discount_in_cents',
'redeem_by_date',
'invoice_description',
'single_use',
'applies_for_months',
'max_redemptions',
'applies_to_all_plans',
'created_at',
'plan_codes',
'hosted_description',
)
@classmethod
def value_for_element(cls, elem):
if not elem or elem.tag != 'plan_codes' or elem.attrib.get('type') != 'array':
return super(Coupon, cls).value_for_element(elem)
return [code_elem.text for code_elem in elem]
@classmethod
def element_for_value(cls, attrname, value):
if attrname != 'plan_codes':
return super(Coupon, cls).element_for_value(attrname, value)
elem = ElementTree.Element(attrname)
elem.attrib['type'] = 'array'
for code in value:
code_el = ElementTree.Element('plan_code')
code_el.text = code
elem.append(code_el)
return elem
@classmethod
def all_redeemable(cls, **kwargs):
"""Return a `Page` of redeemable coupons.
This is a convenience method for `Coupon.all(state='redeemable')`.
"""
return cls.all(state='redeemable', **kwargs)
@classmethod
def all_expired(cls, **kwargs):
"""Return a `Page` of expired coupons.
This is a convenience method for `Coupon.all(state='expired')`.
"""
return cls.all(state='expired', **kwargs)
@classmethod
def all_maxed_out(cls, **kwargs):
"""Return a `Page` of coupons that have been used the maximum
number of times.
This is a convenience method for `Coupon.all(state='maxed_out')`.
"""
return cls.all(state='maxed_out', **kwargs)
class Redemption(Resource):
"""A particular application of a coupon to a customer account."""
nodename = 'redemption'
attributes = (
'account_code',
'single_use',
'total_discounted_in_cents',
'currency',
'created_at',
)
class TaxDetail(Resource):
"""A charge's tax breakdown"""
nodename = 'taxdetail'
inherits_currency = True
attributes = (
'name',
'type',
'tax_rate',
'tax_in_cents',
)
class Adjustment(Resource):
"""A charge or credit applied (or to be applied) to an account's invoice."""
nodename = 'adjustment'
member_path = 'adjustments/%s'
attributes = (
'uuid',
'description',
'accounting_code',
'quantity',
'unit_amount_in_cents',
'discount_in_cents',
'tax_in_cents',
'total_in_cents',
'currency',
'tax_exempt',
'tax_details',
'start_date',
'end_date',
'created_at',
'type',
)
xml_attribute_attributes = ('type',)
_classes_for_nodename = {'tax_detail': TaxDetail,}
class Invoice(Resource):
"""A payable charge to an account for the customer's charges and
subscriptions."""
member_path = 'invoices/%s'
collection_path = 'invoices'
nodename = 'invoice'
attributes = (
'uuid',
'state',
'invoice_number',
'po_number',
'vat_number',
'subtotal_in_cents',
'tax_in_cents',
'tax_type',
'tax_rate',
'total_in_cents',
'currency',
'created_at',
'line_items',
'transactions',
)
@classmethod
def all_open(cls, **kwargs):
"""Return a `Page` of open invoices.
This is a convenience method for `Invoice.all(state='open')`.
"""
return cls.all(state='open', **kwargs)
@classmethod
def all_collected(cls, **kwargs):
"""Return a `Page` of collected invoices.
This is a convenience method for `Invoice.all(state='collected')`.
"""
return cls.all(state='collected', **kwargs)
@classmethod
def all_failed(cls, **kwargs):
"""Return a `Page` of failed invoices.
This is a convenience method for `Invoice.all(state='failed')`.
"""
return cls.all(state='failed', **kwargs)
@classmethod
def all_past_due(cls, **kwargs):
"""Return a `Page` of past-due invoices.
This is a convenience method for `Invoice.all(state='past_due')`.
"""
return cls.all(state='past_due', **kwargs)
@classmethod
def pdf(cls, uuid):
"""Return a PDF of the invoice identified by the UUID
This is a raw string, which can be written to a file with:
`
with open('invoice.pdf', 'w') as invoice_file:
invoice_file.write(recurly.Invoice.pdf(uuid))
`
"""
url = urljoin(base_uri(), cls.member_path % (uuid,))
pdf_response = cls.http_request(url, headers={'Accept': 'application/pdf'})
return pdf_response.read()
class Subscription(Resource):
"""A customer account's subscription to your service."""
member_path = 'subscriptions/%s'
collection_path = 'subscriptions'
nodename = 'subscription'
attributes = (
'uuid',
'state',
'plan_code',
'coupon_code',
'quantity',
'activated_at',
'canceled_at',
'starts_at',
'expires_at',
'current_period_started_at',
'current_period_ends_at',
'trial_started_at',
'trial_ends_at',
'unit_amount_in_cents',
'tax_in_cents',
'tax_type',
'tax_rate',
'total_billing_cycles',
'remaining_billing_cycles',
'timeframe',
'currency',
'subscription_add_ons',
'account',
'pending_subscription',
'net_terms',
'collection_method',
'po_number',
'first_renewal_date',
'bulk'
)
sensitive_attributes = ('number', 'verification_value', 'bulk')
def preview(self):
if hasattr(self, '_url'):
url = self._url + '/preview'
return self.post(url)
else:
url = urljoin(recurly.base_uri(), self.collection_path) + '/preview'
return self.post(url)
def _update(self):
if not hasattr(self, 'timeframe'):
self.timeframe = 'now'
return super(Subscription, self)._update()
def __getpath__(self, name):
if name == 'plan_code':
return 'plan/plan_code'
else:
return name
class Transaction(Resource):
"""An immediate one-time charge made to a customer's account."""
member_path = 'transactions/%s'
collection_path = 'transactions'
nodename = 'transaction'
attributes = (
'uuid',
'action',
'account',
'currency',
'amount_in_cents',
'tax_in_cents',
'status',
'reference',
'test',
'voidable',
'description',
'refundable',
'cvv_result',
'avs_result',
'avs_result_street',
'avs_result_postal',
'created_at',
'details',
'transaction_error',
'type',
)
xml_attribute_attributes = ('type',)
sensitive_attributes = ('number', 'verification_value',)
def _handle_refund_accepted(self, response):
if response.status != 202:
self.raise_http_error(response)
self._refund_transaction_url = response.getheader('Location')
return self
def get_refund_transaction(self):
"""Retrieve the refund transaction for this transaction, immediately
after refunding.
After calling `refund()` to refund a transaction, call this method to
retrieve the new transaction representing the refund.
"""
try:
url = self._refund_transaction_url
except AttributeError:
raise ValueError("No refund transaction is available for this transaction")
resp, elem = self.element_for_url(url)
value = self.value_for_element(elem)
return value
def refund(self, **kwargs):
"""Refund this transaction.
Calling this method returns the refunded transaction (that is,
``self``) if the refund was successful, or raises a `ResponseError` if
an error occurred requesting the refund. After a successful call to
`refund()`, to retrieve the new transaction representing the refund,
use the `get_refund_transaction()` method.
"""
# Find the URL and method to refund the transaction.
try:
selfnode = self._elem
except AttributeError:
raise AttributeError('refund')
url, method = None, None
for anchor_elem in selfnode.findall('a'):
if anchor_elem.attrib.get('name') == 'refund':
url = anchor_elem.attrib['href']
method = anchor_elem.attrib['method'].upper()
if url is None or method is None:
raise AttributeError("refund") # should do something more specific probably
actionator = self._make_actionator(url, method, extra_handler=self._handle_refund_accepted)
return actionator(**kwargs)
class Plan(Resource):
"""A service level for your service to which a customer account
can subscribe."""
member_path = 'plans/%s'
collection_path = 'plans'
nodename = 'plan'
attributes = (
'plan_code',
'name',
'description',
'success_url',
'cancel_url',
'display_donation_amounts',
'display_quantity',
'display_phone_number',
'bypass_hosted_confirmation',
'unit_name',
'payment_page_tos_link',
'plan_interval_length',
'plan_interval_unit',
'trial_interval_length',
'trial_interval_unit',
'accounting_code',
'created_at',
'tax_exempt',
'unit_amount_in_cents',
'setup_fee_in_cents',
)
def get_add_on(self, add_on_code):
"""Return the `AddOn` for this plan with the given add-on code."""
url = urljoin(self._url, '%s/add_ons/%s' % (self.plan_code, add_on_code))
resp, elem = AddOn.element_for_url(url)
return AddOn.from_element(elem)
def create_add_on(self, add_on):
"""Make the given `AddOn` available to subscribers on this plan."""
url = urljoin(self._url, '%s/add_ons' % self.plan_code)
return add_on.post(url)
class AddOn(Resource):
"""An additional benefit a customer subscribed to a particular plan
can also subscribe to."""
nodename = 'add_on'
attributes = (
'add_on_code',
'name',
'display_quantity_on_hosted_page',
'display_quantity',
'default_quantity',
'accounting_code',
'unit_amount_in_cents',
'created_at',
)
class SubscriptionAddOn(Resource):
"""A plan add-on as added to a customer's subscription.
Use these instead of `AddOn` instances when specifying a
`Subscription` instance's `subscription_add_ons` attribute.
"""
nodename = 'subscription_add_on'
inherits_currency = True
attributes = (
'add_on_code',
'quantity',
'unit_amount_in_cents',
)
class Note(Resource):
"""A customer account's notes."""
nodename = 'note'
collection_path = 'notes'
attributes = (
'message',
'created_at',
)
@classmethod
def from_element(cls, elem):
new_note = Note()
for child_el in elem:
if not child_el.tag:
continue
setattr(new_note, child_el.tag, child_el.text)
return new_note
Resource._learn_nodenames(locals().values())
def objects_for_push_notification(notification):
"""Decode a push notification with the given body XML.
Returns a dictionary containing the constituent objects of the push
notification. The kind of push notification is given in the ``"type"``
member of the returned dictionary.
"""
notification_el = defusedxml.ElementTree.fromstring(notification)
objects = {'type': notification_el.tag}
for child_el in notification_el:
tag = child_el.tag
res = Resource.value_for_element(child_el)
objects[tag] = res
return objects