Skip to content

Commit

Permalink
Fixed some bugs when creating a subscription. All creating works for …
Browse files Browse the repository at this point in the history
…customers and subscriptions and you can load all from chargify as well. You now have to use the internal pychargify library as I have fixed some bugs for adding subscriptions
  • Loading branch information
gdoermann committed Aug 3, 2010
1 parent dbc9b68 commit c93e32e
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 19 deletions.
48 changes: 35 additions & 13 deletions chargify/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from django.contrib.auth.models import User
from django.db import models
from chargify.pychargify.api import ChargifyNotFound
import logging
log = logging.getLogger("chargify")

class ChargifyBaseModel(object):
""" You can change the gateway/subdomain used by
Expand Down Expand Up @@ -124,19 +126,28 @@ def _reference(self):

def save(self, save_api = False, **kwargs):
if save_api:
saved = False
try:
saved, customer = self.api.save()
except ChargifyNotFound:
api = self.api
api.id = None
saved, customer = api.save()

if saved:
log.debug("Customer Saved")
return self.load(customer, commit=True) # object save happens after load
else:
log.debug("Customer Not Saved")
log.debug(customer)
self.user.save()
return super(Customer, self).save(**kwargs)

def load(self, api, commit=True):
if not self.id or api.modified_at > self.chargify_updated_at:
if not self.id or not self.chargify_id or api.modified_at > self.chargify_updated_at:
log.debug('Loading Customer API: %s' %(api))
log.debug('Customer ID: %s' %(api.id))
self.chargify_id = api.id
try:
if self.user:
self.first_name = api.first_name
Expand All @@ -154,6 +165,8 @@ def load(self, api, commit=True):
self.chargify_created_at = api.created_at
if commit:
return self.save()
else:
log.debug('Not loading api')
return self

def update(self, commit = True):
Expand Down Expand Up @@ -418,10 +431,19 @@ def _product_handle(self):
def save(self, save_api = False, *args, **kwargs):
if save_api:
if self.customer.chargify_id is None:
log.debug('Saving Customer')
self.customer.save(save_api = True)
customer = self.customer
log.debug("Returned Customer: %s" %(customer))
log.debug('Customer ID: %s' %(customer.chargify_id))
self.customer = customer
if self.product.chargify_id is None:
self.product.save(save_api = True)
log.debug('Saving Product')
product = self.product.save(save_api = True)
log.debug("Returned Product : %s" %(product))
self.product = product
api = self.api
log.debug('Saving API')
saved, subscription = api.save()
if saved:
return self.load(subscription, commit=True) # object save happens after load
Expand All @@ -431,14 +453,14 @@ def load(self, api, commit=True):
self.chargify_id = api.id
self.state = api.state
self.balance_in_cents = api.balance_in_cents
self.current_period_started_at = api.current_period_started_at
self.current_period_ends_at = api.current_period_ends_at
self.trial_started_at = api.trial_started_at
self.trial_ended_at = api.trial_ended_at
self.activated_at = api.activated_at
self.expires_at = api.expires_at
self.created_at = api.created_at
self.updated_at = api.updated_at
# self.current_period_started_at = api.current_period_started_at
# self.current_period_ends_at = api.current_period_ends_at
# self.trial_started_at = api.trial_started_at
# self.trial_ended_at = api.trial_ended_at
# self.activated_at = api.activated_at
# self.expires_at = api.expires_at
# self.created_at = api.created_at
# self.updated_at = api.updated_at
try:
c = Customer.objects.get(chargify_id = api.customer.id)
except:
Expand Down Expand Up @@ -473,11 +495,11 @@ def upgrade(self, product):
def _api(self, node_name = ''):
""" Load data into chargify api object """
subscription = self.gateway.Subscription(node_name)
subscription.id = self.chargify_id
subscription.product_handle = self.product_handle
if self.chargify_id:
subscription.id = self.chargify_id
subscription.product = self.product.api
subscription.product_handle = self.product_handle
subscription.customer = self.customer._api('customer_attributes')
subscription.credit_card = self.credit_card._api('credit_card_attributes')
print subscription.id, subscription.product_handle, subscription.product.id, subscription.customer.id, subscription.customer.reference
return subscription
api = property(_api)
52 changes: 46 additions & 6 deletions chargify/pychargify/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,40 @@
exit()

from xml.dom import minidom
import logging

log = logging.getLogger("pychargify.api")

class ChargifyError(Exception):
"""
A Chargify Releated error
@license GNU General Public License
"""
pass
def __init__(self, xml = None, **kwargs):
self.xml = xml
if xml:
self.errors = self._parse_errors(xml)

def _get_node_text(self, node):
s = ''
if node.nodeType == node.TEXT_NODE:
val = node.data
if val.strip():
s += val
else:
for child in node.childNodes:
s += self._get_node_text(child)
return s
def _parse_errors(self, xml):
dom = minidom.parseString(xml)
nodes = dom.getElementsByTagName('errors')
errors = []
for node in nodes:
for child in node.childNodes:
val = self._get_node_text(child)
if val.strip():
errors.append(val)
return errors

class ChargifyUnAuthorized(ChargifyError):
"""
Expand Down Expand Up @@ -202,7 +228,7 @@ def _get(self, url):

# Unprocessable Entity Error
elif response.status == 422:
raise ChargifyUnProcessableEntity()
raise ChargifyUnProcessableEntity(response.read())

# Generic Server Errors
elif response.status in [405, 500]:
Expand Down Expand Up @@ -245,6 +271,12 @@ def _request(self, method, url, data = '' ):

http.send(data)
response = http.getresponse()
val = ''
try:
val = response.read()
log.log(5, "Server Response: %s" %(val))
except:
pass

# Unauthorized Error
if response.status == 401:
Expand All @@ -260,13 +292,12 @@ def _request(self, method, url, data = '' ):

# Unprocessable Entity Error
elif response.status == 422:
raise ChargifyUnProcessableEntity()
raise ChargifyUnProcessableEntity(val)

# Generic Server Errors
elif response.status in [405, 500]:
raise ChargifyServerError()

return response.read()
raise ChargifyServerError(val)
return val

def _save(self, url, node_name):
"""
Expand Down Expand Up @@ -337,6 +368,15 @@ def getSubscriptions(self):
obj = ChargifySubscription(self.api_key, self.sub_domain)
return obj.getByCustomerId(self.id)

def _toxml(self, dom):
if self.id is not None:
node = minidom.Element("customer_id")
node_txt = dom.createTextNode(str(self.id))
node.appendChild(node_txt)
return node
else:
return super(ChargifyCustomer, self)._toxml(dom)

def save(self):
return self._save('customers', 'customer')

Expand Down

0 comments on commit c93e32e

Please sign in to comment.