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.
5 from decimal import Decimal
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
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 as BillingAgreementModel, BillingPlan
17 def paypal_form(request):
19 if not request.user.is_authenticated():
20 return HttpResponseForbidden()
21 form = PaypalSubscriptionForm(data=request.POST)
23 amount = form.cleaned_data['amount']
25 approval_url = agreement_approval_url(amount)
26 except PaypalError as e:
27 return render(request, 'paypal/error_page.html', {'error': e.message})
28 return HttpResponseRedirect(approval_url)
30 form = PaypalSubscriptionForm()
31 return render(request, 'paypal/form.html', {'form': form})
35 def paypal_return(request):
36 token = request.GET.get('token')
39 if not BillingAgreementModel.objects.filter(token=token):
40 resource = execute_agreement(token)
42 amount = int(Decimal(resource.plan.payment_definitions[0].amount['value']))
43 plan = BillingPlan.objects.get(amount=amount)
44 active = check_agreement(resource.id)
45 BillingAgreementModel.objects.create(
46 agreement_id=resource.id, user=request.user, plan=plan, active=active, token=token)
47 return render(request, 'paypal/return.html', {'resource': resource})
50 def paypal_cancel(request):
51 return render(request, 'paypal/cancel.html', {})