1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from decimal import Decimal
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
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
18 def paypal_form(request, app=False):
20 if not request.user.is_authenticated:
21 return HttpResponseForbidden()
22 form = PaypalSubscriptionForm(data=request.POST)
24 amount = form.cleaned_data['amount']
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)
31 form = PaypalSubscriptionForm()
32 return render(request, 'paypal/form.html', {'form': form})
36 def paypal_return(request, key, app=False):
37 schedule = get_object_or_404(Schedule, key=key)
39 token = request.GET.get('token')
42 if not BillingAgreement.objects.filter(token=token):
43 resource = execute_agreement(token)
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)
55 if getattr(resource, 'error', None):
56 return HttpResponseAppRedirect('wolnelekturyapp://paypal_error')
58 return HttpResponseAppRedirect('wolnelekturyapp://paypal_return')
60 return HttpResponseRedirect(schedule.get_thanks_url())
63 def paypal_cancel(request):
64 return render(request, 'paypal/cancel.html', {})