diff --git a/rowers/braintreestuff.py b/rowers/braintreestuff.py index 3db632db..57ab9185 100644 --- a/rowers/braintreestuff.py +++ b/rowers/braintreestuff.py @@ -13,6 +13,8 @@ queue = django_rq.get_queue('default') queuelow = django_rq.get_queue('low') queuehigh = django_rq.get_queue('low') +from braintree.exceptions.invalid_signature_error import InvalidSignatureError + from rowers.utils import myqueue from rowers.tasks import ( handle_send_email_transaction, @@ -52,17 +54,37 @@ else: from rowers.models import Rower,PaidPlan, CoachingGroup from rowers.utils import ProcessorCustomerError +def process_webhook(notification): + if notification.kind == 'subscription_charged_successfully': + subscription_id = notification.subscription.id + rs = Rower.objects.filter(subscription_id=subscription_id) + if rs.count == 0: + return 0 + else: + r = rs[0] + fakturoid_contact_id = fakturoid.get_contacts(r) + if not fakturoid_contact_id: + fakturoid_contact_id = fakturoid.create_contact(rower) + transactions = result.subscription.transactions + if transactions: + amount = transactions[0].amount + fakturoid.create_invoice(r,amount) + return 1 + + return 0 + def webhook(request): try: webhook_notification = gateway.webhook_notification.parse( str(request.POST['bt_signature']), request.POST['bt_payload']) - except: - print(sys.exc_info()) + except InvalidSignatureError: + return 4 - # Example values for webhook notification properties - print(webhook_notification.kind) # "subscription_went_past_due" - print(webhook_notification.timestamp) # "Sun Jan 1 00:00:00 UTC 2012" + result = process_webhook(webhook_notification) + + + return result def create_customer(rower,force=False): if not rower.customer_id or force: diff --git a/rowers/fakturoid.py b/rowers/fakturoid.py index bcb50190..705fed74 100644 --- a/rowers/fakturoid.py +++ b/rowers/fakturoid.py @@ -56,7 +56,10 @@ def create_contact(rower): res = requests.post(contacts_url, data=json.dumps(post_data), auth=auth,headers=headers) - return res + if res.status_code not in [200,201]: + return 0 + + return res.json()['id'] # this should be triggered by a Braintree webhook def create_invoice(rower,amount,braintreeid,send=False): diff --git a/rowers/views/paymentviews.py b/rowers/views/paymentviews.py index bb0629ce..d322e325 100644 --- a/rowers/views/paymentviews.py +++ b/rowers/views/paymentviews.py @@ -8,7 +8,10 @@ from rowers.views.statements import * @csrf_exempt def braintree_webhook_view(request): if request.method == 'POST': - braintreestuff.webhook(request) + result = braintreestuff.webhook(request) + if result == 4: + raise PermissionDenied("Not allowed") + return HttpResponse('') def paidplans_view(request):