paypal subscriptions - stub
[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
10 from django.shortcuts import render
11
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
15
16
17 @login_required
18 def paypal_form(request):
19     if request.POST:
20         form = PaypalSubscriptionForm(data=request.POST)
21         if form.is_valid():
22             amount = form.cleaned_data['amount']
23             try:
24                 approval_url = agreement_approval_url(amount)
25             except PaypalError as e:
26                 return render(request, 'paypal/error_page.html', {'error': e.message})
27             return HttpResponseRedirect(approval_url)
28     else:
29         form = PaypalSubscriptionForm()
30     return render(request, 'paypal/form.html', {'form': form})
31
32
33 @login_required
34 def paypal_return(request):
35     token = request.GET.get('token')
36     if not token:
37         raise Http404
38     if not BillingAgreementModel.objects.filter(token=token):
39         resource = execute_agreement(token)
40         if resource.id:
41             amount = int(Decimal(resource.plan.payment_definitions[0].amount['value']))
42             plan = BillingPlan.objects.get(amount=amount)
43             active = check_agreement(resource.id)
44             BillingAgreementModel.objects.create(
45                 agreement_id=resource.id, user=request.user, plan=plan, active=active, token=token)
46     return render(request, 'paypal/return.html', {'resource': resource})
47
48
49 def paypal_cancel(request):
50     return render(request, 'paypal/cancel.html', {})