Locatizations.
[wolnelektury.git] / src / paypal / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from decimal import Decimal
5
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
10
11 from api.utils import HttpResponseAppRedirect
12 from club.models import Schedule
13 from paypal.rest import execute_agreement, check_agreement, agreement_approval_url
14 from paypal.models import BillingAgreement, BillingPlan
15
16
17 def paypal_init(request, key):
18     schedule = get_object_or_404(Schedule, key=key)
19     schedule.method = 'paypal'
20     schedule.save(update_fields=['method'])
21     app = request.GET.get('app')
22     return redirect(agreement_approval_url(schedule.amount, schedule.key, app=app))
23
24
25 @login_required
26 def paypal_return(request, key, app=False):
27     schedule = get_object_or_404(Schedule, key=key)
28     
29     token = request.GET.get('token')
30     if not token:
31         raise Http404
32     if not BillingAgreement.objects.filter(token=token):
33         resource = execute_agreement(token)
34         if resource.id:
35             amount = int(Decimal(resource.plan.payment_definitions[0].amount['value']))
36             plan = BillingPlan.objects.get(amount=amount)
37             active = check_agreement(resource.id) or False
38             BillingAgreement.objects.create(
39                 agreement_id=resource.id, schedule=schedule, plan=plan, active=active, token=token)
40             if active:
41                 schedule.set_payed()
42     else:
43         resource = None
44     if app:
45         if getattr(resource, 'error', None):
46             return HttpResponseAppRedirect('wolnelekturyapp://paypal_error')
47         else:
48             return HttpResponseAppRedirect('wolnelekturyapp://paypal_return')
49     else:
50         return HttpResponseRedirect(schedule.get_thanks_url())
51
52
53 def paypal_cancel(request):
54     return render(request, 'paypal/cancel.html', {})