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.rest import execute_agreement, check_agreement, agreement_approval_url
14 from paypal.models import BillingAgreement, BillingPlan
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))
26 def paypal_return(request, key, app=False):
27 schedule = get_object_or_404(Schedule, key=key)
29 token = request.GET.get('token')
32 if not BillingAgreement.objects.filter(token=token):
33 resource = execute_agreement(token)
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)
45 if getattr(resource, 'error', None):
46 return HttpResponseAppRedirect('wolnelekturyapp://paypal_error')
48 return HttpResponseAppRedirect('wolnelekturyapp://paypal_return')
50 return HttpResponseRedirect(schedule.get_thanks_url())
53 def paypal_cancel(request):
54 return render(request, 'paypal/cancel.html', {})