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, redirect
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})
35 def paypal_init(request, key):
36 schedule = get_object_or_404(Schedule, key=key)
37 schedule.method = 'paypal'
38 schedule.save(update_fields=['method'])
39 app = request.GET.get('app')
40 return redirect(agreement_approval_url(schedule.amount, schedule.key, app=app))
44 def paypal_return(request, key, app=False):
45 schedule = get_object_or_404(Schedule, key=key)
47 token = request.GET.get('token')
50 if not BillingAgreement.objects.filter(token=token):
51 resource = execute_agreement(token)
53 amount = int(Decimal(resource.plan.payment_definitions[0].amount['value']))
54 plan = BillingPlan.objects.get(amount=amount)
55 active = check_agreement(resource.id) or False
56 BillingAgreement.objects.create(
57 agreement_id=resource.id, schedule=schedule, plan=plan, active=active, token=token)
63 if getattr(resource, 'error', None):
64 return HttpResponseAppRedirect('wolnelekturyapp://paypal_error')
66 return HttpResponseAppRedirect('wolnelekturyapp://paypal_return')
68 return HttpResponseRedirect(schedule.get_thanks_url())
71 def paypal_cancel(request):
72 return render(request, 'paypal/cancel.html', {})