More banners and stats.
[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 render
10
11 from api.utils import HttpResponseAppRedirect
12 from paypal.forms import PaypalSubscriptionForm
13 from paypal.rest import execute_agreement, check_agreement, agreement_approval_url, PaypalError
14 from paypal.models import BillingAgreement, BillingPlan
15
16
17 def paypal_form(request, app=False):
18     if request.POST:
19         if not request.user.is_authenticated:
20             return HttpResponseForbidden()
21         form = PaypalSubscriptionForm(data=request.POST)
22         if form.is_valid():
23             amount = form.cleaned_data['amount']
24             try:
25                 approval_url = agreement_approval_url(amount, app=app)
26             except PaypalError as e:
27                 return render(request, 'paypal/error_page.html', {'error': str(e)})
28             return HttpResponseRedirect(approval_url)
29     else:
30         form = PaypalSubscriptionForm()
31     return render(request, 'paypal/form.html', {'form': form})
32
33
34 @login_required
35 def paypal_return(request, app=False):
36     token = request.GET.get('token')
37     if not token:
38         raise Http404
39     if not BillingAgreement.objects.filter(token=token):
40         resource = execute_agreement(token)
41         if resource.id:
42             amount = int(Decimal(resource.plan.payment_definitions[0].amount['value']))
43             plan = BillingPlan.objects.get(amount=amount)
44             active = check_agreement(resource.id) or False
45             BillingAgreement.objects.create(
46                 agreement_id=resource.id, user=request.user, plan=plan, active=active, token=token)
47     else:
48         resource = None
49     if app:
50         if getattr(resource, 'error', None):
51             return HttpResponseAppRedirect('wolnelekturyapp://paypal_error')
52         else:
53             return HttpResponseAppRedirect('wolnelekturyapp://paypal_return')
54     else:
55         return render(request, 'paypal/return.html', {'resource': resource})
56
57
58 def paypal_cancel(request):
59     return render(request, 'paypal/cancel.html', {})