Upgrades.
[wolnelektury.git] / src / paypal / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from decimal import Decimal
5
6 from django.contrib.auth.decorators import login_required
7 from django.http import Http404
8 from django.http.response import HttpResponseRedirect, HttpResponseForbidden
9 from django.shortcuts import get_object_or_404, render
10
11 from api.utils import HttpResponseAppRedirect
12 from club.models import Schedule
13 from paypal.forms import PaypalSubscriptionForm
14 from paypal.rest import execute_agreement, check_agreement, agreement_approval_url, PaypalError
15 from paypal.models import BillingAgreement, BillingPlan
16
17
18 def paypal_form(request, app=False):
19     if request.POST:
20         if not request.user.is_authenticated:
21             return HttpResponseForbidden()
22         form = PaypalSubscriptionForm(data=request.POST)
23         if form.is_valid():
24             amount = form.cleaned_data['amount']
25             try:
26                 approval_url = agreement_approval_url(amount, app=app)
27             except PaypalError as e:
28                 return render(request, 'paypal/error_page.html', {'error': str(e)})
29             return HttpResponseRedirect(approval_url)
30     else:
31         form = PaypalSubscriptionForm()
32     return render(request, 'paypal/form.html', {'form': form})
33
34
35 @login_required
36 def paypal_return(request, key, app=False):
37     schedule = get_object_or_404(Schedule, key=key)
38     
39     token = request.GET.get('token')
40     if not token:
41         raise Http404
42     if not BillingAgreement.objects.filter(token=token):
43         resource = execute_agreement(token)
44         if resource.id:
45             amount = int(Decimal(resource.plan.payment_definitions[0].amount['value']))
46             plan = BillingPlan.objects.get(amount=amount)
47             active = check_agreement(resource.id) or False
48             BillingAgreement.objects.create(
49                 agreement_id=resource.id, schedule=schedule, plan=plan, active=active, token=token)
50             if active:
51                 schedule.set_payed()
52     else:
53         resource = None
54     if app:
55         if getattr(resource, 'error', None):
56             return HttpResponseAppRedirect('wolnelekturyapp://paypal_error')
57         else:
58             return HttpResponseAppRedirect('wolnelekturyapp://paypal_return')
59     else:
60         return HttpResponseRedirect(schedule.get_thanks_url())
61
62
63 def paypal_cancel(request):
64     return render(request, 'paypal/cancel.html', {})