paypal fix
[wolnelektury.git] / src / paypal / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from decimal import Decimal
6
7 from django.contrib.auth.decorators import login_required
8 from django.http import Http404
9 from django.http.response import HttpResponseRedirect, HttpResponseForbidden
10 from django.shortcuts import render
11
12 from api.piston_patch import HttpResponseAppRedirect
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 as BillingAgreementModel, 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': e.message})
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, app=False):
37     token = request.GET.get('token')
38     if not token:
39         raise Http404
40     if not BillingAgreementModel.objects.filter(token=token):
41         resource = execute_agreement(token)
42         if resource.id:
43             amount = int(Decimal(resource.plan.payment_definitions[0].amount['value']))
44             plan = BillingPlan.objects.get(amount=amount)
45             active = check_agreement(resource.id)
46             BillingAgreementModel.objects.create(
47                 agreement_id=resource.id, user=request.user, plan=plan, active=active, token=token)
48     else:
49         resource = None
50     if app:
51         if getattr(resource, 'error'):
52             return HttpResponseAppRedirect('wolnelekturyapp://paypal_error')
53         else:
54             return HttpResponseAppRedirect('wolnelekturyapp://paypal_return')
55     else:
56         return render(request, 'paypal/return.html', {'resource': resource})
57
58
59 def paypal_cancel(request):
60     return render(request, 'paypal/cancel.html', {})