forked from getyouridx/pychargify
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.py
776 lines (621 loc) · 23.2 KB
/
api.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
766
767
768
769
770
771
772
773
774
775
776
# -*- coding: utf-8 -*-
'''
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Created on Nov 20, 2009
Author: Paul Trippett (paul@pyhub.com)
'''
import httplib
import base64
import time
import datetime
import iso8601
import inspect
from itertools import chain
from xml.dom import minidom
try:
import json
except Exception, e:
try:
import simplejson as json
except Exception, e:
try:
# For AppEngine users
import django.utils.simplejson as json
except Exception, e:
print "No Json library found... Exiting."
exit()
class ChargifyError(Exception):
"""
A Chargify Releated error
@license GNU General Public License
"""
pass
class ChargifyUnAuthorized(ChargifyError):
"""
Returned when API authentication has failed.
@license GNU General Public License
"""
pass
class ChargifyForbidden(ChargifyError):
"""
Returned by valid endpoints in our application that have not been
enabled for API use.
@license GNU General Public License
"""
pass
class ChargifyNotFound(ChargifyError):
"""
The requested resource was not found.
@license GNU General Public License
"""
pass
class ChargifyUnProcessableEntity(ChargifyError):
"""
Sent in response to a POST (create) or PUT (update) request
that is invalid.
@license GNU General Public License
"""
pass
class ChargifyServerError(ChargifyError):
"""
Signals some other error
@license GNU General Public License
"""
pass
class ChargifyBase(object):
"""
The ChargifyBase class provides a common base for all classes
in this module
@license GNU General Public License
"""
class Meta:
listing = None
__ignore__ = ['api_key', 'sub_domain', 'base_host', 'request_host',
'id', '__xmlnodename__', 'Meta']
api_key = ''
sub_domain = ''
base_host = '.chargify.com'
request_host = ''
def __init__(self, apikey, subdomain):
"""
Initialize the Class with the API Key and SubDomain for Requests
to the Chargify API
"""
self.api_key = apikey
self.sub_domain = subdomain
self.request_host = self.sub_domain + self.base_host
def __get_xml_value(self, nodelist):
"""
Get the Text Value from an XML Node
"""
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc
def __get_object_from_node(self, node, obj_type=''):
"""
Copy values from a node into a new Object
"""
if obj_type == '':
constructor = globals()[self.__name__]
else:
constructor = globals()[obj_type]
obj = constructor(self.api_key, self.sub_domain)
for childnodes in node.childNodes:
if childnodes.nodeType == 1 and not childnodes.nodeName == '':
if childnodes.nodeName in self.__attribute_types__:
obj.__setattr__(childnodes.nodeName,
self._applyS(childnodes.toxml(encoding='utf-8'),
self.__attribute_types__[childnodes.nodeName],
childnodes.nodeName))
else:
node_value = self.__get_xml_value(childnodes.childNodes)
if "type" in childnodes.attributes.keys():
node_type = childnodes.attributes["type"]
if node_value:
if node_type.nodeValue == 'datetime':
node_value = datetime.datetime.fromtimestamp(
iso8601.parse(node_value))
obj.__setattr__(childnodes.nodeName, node_value)
return obj
def fix_xml_encoding(self, xml):
"""
Chargify encodes non-ascii characters in CP1252.
Decodes and re-encodes with xml characters.
Strips out whitespace "text nodes".
"""
return unicode(''.join([i.strip() for i in xml.split('\n')])
.encode('utf-8', 'xmlcharrefreplace'), 'utf-8')
def _applyS(self, xml, obj_type, node_name):
"""
Apply the values of the passed xml data to the a class
"""
dom = minidom.parseString(xml)
nodes = dom.getElementsByTagName(node_name)
if nodes.length == 1:
return self.__get_object_from_node(nodes[0], obj_type)
def _applyA(self, xml, obj_type, node_name):
"""
Apply the values of the passed data to a new class of the current type
"""
dom = minidom.parseString(xml)
nodes = dom.getElementsByTagName(node_name)
objs = []
for node in nodes:
objs.append(self.__get_object_from_node(node, obj_type))
return objs
def _toxml(self, dom):
"""
Return a XML Representation of the object
"""
element = minidom.Element(self.__xmlnodename__)
for property, value in self.__dict__.iteritems():
if not property in self.__ignore__ and not inspect.isfunction(value):
if property in self.__attribute_types__:
element.appendChild(value._toxml(dom))
else:
node = minidom.Element(property)
node_txt = dom.createTextNode(value.encode('ascii', 'xmlcharrefreplace'))
node.appendChild(node_txt)
element.appendChild(node)
return element
def _get(self, url):
"""
Handle HTTP GETs to the API
"""
return self._request('GET', url)
def _post(self, url, data):
"""
Handle HTTP POST's to the API
"""
return self._request('POST', url, data)
def _put(self, url, data):
"""
Handle HTTP PUT's to the API
"""
return self._request('PUT', url, data)
def _delete(self, url, data):
"""
Handle HTTP DELETE's to the API
"""
return self._request('DELETE', url, data)
def _request(self, method, url, data=None):
"""
Handled the request and sends it to the server
"""
http = httplib.HTTPSConnection(self.request_host)
http.putrequest(method, url)
http.putheader("Authorization", "Basic %s" % self._get_auth_string())
http.putheader("User-Agent", "pychargify")
http.putheader("Host", self.request_host)
http.putheader("Accept", "application/xml")
if data:
http.putheader("Content-Length", str(len(data)))
http.putheader("Content-Type", 'text/xml; charset="UTF-8"')
http.endheaders()
if data:
http.send(data)
response = http.getresponse()
r = response.read()
# Unauthorized Error
if response.status == 401:
raise ChargifyUnAuthorized()
# Forbidden Error
elif response.status == 403:
raise ChargifyForbidden()
# Not Found Error
elif response.status == 404:
raise ChargifyNotFound()
# Unprocessable Entity Error
elif response.status == 422:
raise ChargifyUnProcessableEntity()
# Generic Server Errors
elif response.status in [405, 500]:
raise ChargifyServerError()
return self.fix_xml_encoding(r)
def _save(self, url, node_name):
"""
Save the object using the passed URL as the API end point
"""
dom = minidom.Document()
dom.appendChild(self._toxml(dom))
request_made = {
'day': datetime.datetime.today().day,
'month': datetime.datetime.today().month,
'year': datetime.datetime.today().year
}
if self.id:
obj = self._applyS(self._put('/' + url + '/' + self.id + '.xml',
dom.toxml(encoding="utf-8")), self.__name__, node_name)
if obj:
if type(obj.updated_at) == datetime.datetime:
if (obj.updated_at.day == request_made['day']) and \
(obj.updated_at.month == request_made['month']) and \
(obj.updated_at.year == request_made['year']):
self.saved = True
return (True, obj)
return (False, obj)
else:
obj = self._applyS(self._post('/' + url + '.xml',
dom.toxml(encoding="utf-8")), self.__name__, node_name)
if obj:
if type(obj.updated_at) == datetime.datetime:
if (obj.updated_at.day == request_made['day']) and \
(obj.updated_at.month == request_made['month']) and \
(obj.updated_at.year == request_made['year']):
return (True, obj)
return (False, obj)
def _get_auth_string(self):
return base64.encodestring('%s:%s' % (self.api_key, 'x'))[:-1]
def getAll(self):
if self.Meta.listing:
return self._applyA(self._get('/%s.xml' % self.Meta.listing),
self.__name__, self.__xmlnodename__)
raise NotImplementedError('Subclass is missing Meta class attribute listing')
def getById(self, id):
if self.Meta.listing:
return self._applyS(self._get('/%s/%s.xml' % (self.Meta.listing, str(id))),
self.__name__, self.__xmlnodename__)
raise NotImplementedError('Subclass is missing Meta class attribute listing')
def __get_by_attribute__(self, key, value):
if self.Meta.listing:
return self._applyS(self._get('/%s/lookup.xml?%s=%s' %(self.Meta.listing,
str(key), str(value))), self.__name__, self.__xmlnodename__)
raise NotImplementedError('Subclass is missing Meta class attribute listing')
def save(self):
if self.Meta.listing:
return self._save(self.Meta.listing, self.__xmlnodename__)
raise NotImplementedError('Subclass is missing Meta class attribute listing')
class CompoundKeyMixin:
def getByCompoundKey(self, parent_id, sub_id):
if 'compound_key' in self.Meta.__dict__.keys():
_cb, _a = (self._applyA, ('/%s' % self.Meta.compound_key[2])) \
if len(self.Meta.compound_key) == 3 else (self._applyS, '')
return _cb(self._get('/%s.xml' % ('/'.join(['%s/%s' % i
for i in zip(self.Meta.compound_key[:2],
(str(parent_id), str(sub_id)))]) + _a)),
self.__name__, self.__xmlnodename__)
raise NotImplementedError('Subclass is missing Meta class attribute compound key')
class ChargifyCustomer(ChargifyBase):
"""
Represents Chargify Customers
@license GNU General Public License
"""
class Meta:
listing = 'customers'
__name__ = 'ChargifyCustomer'
__attribute_types__ = {}
__xmlnodename__ = 'customer'
id = None
first_name = ''
last_name = ''
email = ''
organization = ''
reference = ''
created_at = None
modified_at = None
def __init__(self, apikey, subdomain):
super(ChargifyCustomer, self).__init__(apikey, subdomain)
self.getByReference = lambda v: self.__get_by_attribute__('reference', v)
def getSubscriptions(self):
obj = ChargifySubscription(self.api_key, self.sub_domain)
return obj.getByCustomerId(self.id)
class CustomerAttributes(ChargifyCustomer):
__xmlnodename__ = 'customer_attributes'
class ChargifyProductFamily(ChargifyBase):
"""
Represents Chargify Product Families
@license GNU General Public License
"""
class Meta:
listing = 'product_families'
__name__ = 'ChargifyProductFamily'
__attribute_types__ = {}
__xmlnodename__ = 'product_family'
id = None
accounting_code = None
description = ''
handle = ''
name = ''
def getComponents(self):
obj = ChargifyProductFamilyComponent(self.api_key, self.sub_domain)
return obj.getByProductFamilyId(self.id)
class ChargifyProductFamilyComponent(ChargifyBase):
__name__ = 'ChargifyProductFamilyComponent'
__attribute_types__ = {}
__xmlnodename__ = 'component'
id = None
name = ''
kind = ''
product_family_id = 0
price_per_unit_in_cents = 0
pricing_scheme = ''
unit_name = None
updated_at = None
created_at = None
def getByProductFamilyId(self, id):
return self._applyA(self._get('/product_families/' + str(id) + '/components.xml'),
self.__name__, self.__xmlnodename__)
class ChargifyProduct(ChargifyBase):
"""
Represents Chargify Products
@license GNU General Public License
"""
class Meta:
listing = 'products'
__name__ = 'ChargifyProduct'
__attribute_types__ = {
'product_family': 'ChargifyProductFamily',
}
__xmlnodename__ = 'product'
id = None
price_in_cents = 0
name = ''
handle = ''
product_family = None
accounting_code = ''
interval_unit = ''
interval = 0
def getByHandle(self, handle):
return self._applyS(self._get('/products/handle/' + str(handle) +
'.xml'), self.__name__, self.__xmlnodename__)
def getPaymentPageUrl(self):
return ('https://' + self.request_host + '/h/' +
self.id + '/subscriptions/new')
def getPriceInDollars(self):
return round(float(self.price_in_cents) / 100, 2)
def getFormattedPrice(self):
return "$%.2f" % (self.getPriceInDollars())
class ChargifySubscription(ChargifyBase):
"""
Represents Chargify Subscriptions
@license GNU General Public License
"""
class Meta:
listing = 'subscriptions'
__name__ = 'ChargifySubscription'
__attribute_types__ = {
'customer': 'ChargifyCustomer',
'product': 'ChargifyProduct',
'credit_card': 'ChargifyCreditCard'
}
__xmlnodename__ = 'subscription'
id = None
state = ''
balance_in_cents = 0
current_period_started_at = None
current_period_ends_at = None
trial_started_at = None
trial_ended_attrial_ended_at = None
activated_at = None
expires_at = None
created_at = None
updated_at = None
customer = None
product = None
product_handle = ''
credit_card = None
def getComponents(self):
"""
Gets the subscription components
"""
obj = ChargifySubscriptionComponent(self.api_key, self.sub_domain)
return obj.getBySubscriptionId(self.id)
def getComponent(self, component_id):
"""
Gets the status of a quantity based component..
"""
obj = ChargifySubscriptionComponent(self.api_key, self.sub_domain)
return obj.getByCompoundKey(self.id, component_id)
def getByCustomerId(self, customer_id):
return self._applyA(self._get('/customers/' + str(customer_id) +
'/subscriptions.xml'), self.__name__, 'subscription')
def getBySubscriptionId(self, subscription_id):
#Throws error if more than element is returned
i, = self._applyA(self._get('/subscriptions/' + str(subscription_id) +
'.xml'), self.__name__, 'subscription')
return i
def resetBalance(self):
self._put("/subscriptions/" + self.id + "/reset_balance.xml", '')
def reactivate(self):
self._put("/subscriptions/" + self.id + "/reactivate.xml", "")
def upgrade(self, toProductHandle):
xml = """<?xml version="1.0" encoding="UTF-8"?>
<subscription>
<product_handle>%s</product_handle>
</subscription>""" % (toProductHandle)
#end improper indentation
return self._applyS(self._put("/subscriptions/" + self.id + ".xml",
xml), self.__name__, "subscription")
def unsubscribe(self, message):
xml = """<?xml version="1.0" encoding="UTF-8"?>
<subscription>
<cancellation_message>
%s
</cancellation_message>
</subscription>""" % (message)
self._delete("/subscriptions/" + self.id + ".xml", xml)
class ChargifyCreditCard(ChargifyBase):
"""
Represents Chargify Credit Cards
"""
__name__ = 'ChargifyCreditCard'
__attribute_types__ = {}
__xmlnodename__ = 'credit_card_attributes'
first_name = ''
last_name = ''
full_number = ''
masked_card_number = ''
expiration_month = ''
expiration_year = ''
cvv = ''
type = ''
billing_address = ''
billing_city = ''
billing_state = ''
billing_zip = ''
billing_country = ''
def save(self, subscription):
path = "/subscriptions/%s.xml" % (subscription.id)
data = u'<?xml version="1.0" encoding="UTF-8"?><subscription><credit_card_attributes>%s</credit_card_attributes></subscription>' % (
''.join([u'<%s>%s</%s>' % (k, v, k) for (k, v) in self.__dict__.items()
if not k.startswith('_') and k not in self.__ignore__]))
return self._applyS(self._put(path, data),
self.__name__, "subscription")
class ChargifySubscriptionComponent(ChargifyBase, CompoundKeyMixin):
"""
Represents Chargify Subscription Component
"""
class Meta:
compound_key = ('subscriptions', 'components')
__name__ = 'ChargifySubscriptionComponent'
__attribute_types__ = {}
__xmlnodename__ = 'component'
component_id = None
subscription_id = None
name = ''
kind = ''
unit_name = None
unit_balance = 0 # metered-component
allocatted_quantity = 0 # quantity-based-component
pricing_scheme = '' # quantity-based-component
enabled = True # on-off-component
def getBySubscriptionId(self, id):
return self._applyA(self._get('/subscriptions/' + str(id) + '/components.xml'),
self.__name__, self.__xmlnodename__)
def updateQuantity(self, quantity):
"""
Sets the quantity allocation for a given component id.
"""
if self.component_id is None or self.subscription_id is None:
raise ChargifyError()
if self.kind != 'quantity_based_component':
raise ChargifyError()
self.allocatted_quantity = quantity
data = '''<?xml version="1.0" encoding="UTF-8"?><component>
<allocated_quantity type="integer">%d</allocated_quantity>
</component>''' % self.allocatted_quantity
dom = minidom.parseString(self.fix_xml_encoding(
self._put('/subscriptions/%s/components/%s.xml' % (
str(self.subscription_id), str(self.component_id)), data)
))
def getUsages(self):
"""
Gets the subscription components
"""
if self.component_id is None or self.subscription_id is None:
raise ChargifyError()
if self.kind != 'metered_component':
raise ChargifyError()
obj = ChargifyComponentUsage(self.api_key, self.sub_domain)
return obj.getByCompoundKey(self.subscription_id, self.component_id)
def createUsage(self, quantity, memo=None):
"""
Creates metered usage for a given component id.
"""
if self.component_id is None or self.subscription_id is None:
raise ChargifyError()
if self.kind != 'metered_component':
raise ChargifyError()
data = '''<?xml version="1.0" encoding="UTF-8"?><usage>
<quantity>%d</quantity><memo>%s</memo></usage>''' % (
quantity, memo or "")
return self._applyA(
self._post('/subscriptions/%s/components/%s/usages.xml' % (
str(self.subscription_id), str(self.component_id)), data),
ChargifyComponentUsage.__name__,
ChargifyComponentUsage.__xmlnodename__)
class ChargifyComponentUsage(ChargifyBase, CompoundKeyMixin):
"""
Represents Chargify Subscription Component Usage
"""
class Meta:
compound_key = ('subscriptions', 'components', 'usages')
__name__ = 'ChargifyComponentUsage'
__attribute_types__ = {}
__xmlnodename__ = 'usage'
id = None
quantity = 0
memo = ''
class ChargifyPostBack(ChargifyBase):
"""
Represents Chargify API Post Backs
@license GNU General Public License
"""
subscriptions = []
def __init__(self, apikey, subdomain, postback_data):
ChargifyBase.__init__(apikey, subdomain)
if postback_data:
self._process_postback_data(postback_data)
def _process_postback_data(self, data):
"""
Process the Json array and fetches the Subscription Objects
"""
csub = ChargifySubscription(self.api_key, self.sub_domain)
postdata_objects = json.loads(data)
for obj in postdata_objects:
self.subscriptions.append(csub.getBySubscriptionId(obj))
class Chargify:
"""
The Chargify class provides the main entry point to the Charify API
@license GNU General Public License
"""
api_key = ''
sub_domain = ''
def __init__(self, apikey, subdomain):
self.api_key = apikey
self.sub_domain = subdomain
def Customer(self):
return ChargifyCustomer(self.api_key, self.sub_domain)
def CustomerAttributes(self):
return CustomerAttributes(self.api_key, self.sub_domain)
def Product(self):
return ChargifyProduct(self.api_key, self.sub_domain)
def Component(self):
return ChargifyProductFamilyComponent(self.api_key,
self.sub_domain)
def ProductFamily(self):
return ChargifyProductFamily(self.api_key, self.sub_domain)
def Subscription(self):
return ChargifySubscription(self.api_key, self.sub_domain)
def SubscriptionComponent(self):
return ChargifySubscriptionComponent(self.api_key,
self.sub_domain)
def ComponentUsage(self):
return ChargifyComponentUsage(self.api_key, self.sub_domain)
def CreditCard(self):
return ChargifyCreditCard(self.api_key, self.sub_domain)
def PostBack(self, postbackdata):
return ChargifyPostBack(self.api_key, self.sub_domain, postbackdata)
@property
def Customers(self):
return ChargifyCustomer(self.api_key, self.sub_domain)
@property
def Products(self):
return ChargifyProduct(self.api_key, self.sub_domain)
@property
def Components(self):
return ChargifyProductFamilyComponent(self.api_key, self.sub_domain)
@property
def ProductFamilies(self):
return ChargifyProductFamily(self.api_key, self.sub_domain)
@property
def Subscriptions(self):
return ChargifySubscription(self.api_key, self.sub_domain)
@property
def SubscriptionComponents(self):
return ChargifySubscriptionComponent(self.api_key, self.sub_domain)
@property
def ComponentUsages(self):
return ChargifyComponentUsage(self.api_key, self.sub_domain)