More banners and stats.
[wolnelektury.git] / src / paypal / rest.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 datetime import timedelta
5
6 import paypalrestsdk
7 import pytz
8 from django.contrib.sites.models import Site
9 from django.urls import reverse
10 from django.utils import timezone
11 from django.conf import settings
12 from .models import BillingPlan, BillingAgreement
13
14 paypalrestsdk.configure(settings.PAYPAL_CONFIG)
15
16
17 class PaypalError(Exception):
18     pass
19
20
21 def absolute_url(url_name):
22     return "http://%s%s" % (Site.objects.get_current().domain, reverse(url_name))
23
24
25 def create_plan(amount):
26     billing_plan = paypalrestsdk.BillingPlan({
27         "name": "Cykliczna darowizna na Wolne Lektury: %s zł" % amount,
28         "description": "Cykliczna darowizna na wsparcie Wolnych Lektur",
29         "merchant_preferences": {
30             "auto_bill_amount": "yes",
31             "return_url": absolute_url('paypal_return'),
32             "cancel_url": absolute_url('paypal_cancel'),
33             # "initial_fail_amount_action": "continue",
34             "max_fail_attempts": "3",
35         },
36         "payment_definitions": [
37             {
38                 "amount": {
39                     "currency": "PLN",
40                     "value": str(amount),
41                 },
42                 "cycles": "0",
43                 "frequency": "MONTH",
44                 "frequency_interval": "1",
45                 "name": "Cykliczna darowizna",
46                 "type": "REGULAR",
47             }
48         ],
49         "type": "INFINITE",
50     })
51
52     if not billing_plan.create():
53         raise PaypalError(billing_plan.error)
54     if not billing_plan.activate():
55         raise PaypalError(billing_plan.error)
56     plan, created = BillingPlan.objects.get_or_create(amount=amount, defaults={'plan_id': billing_plan.id})
57     return plan.plan_id
58
59
60 def get_link(links, rel):
61     for link in links:
62         if link.rel == rel:
63             return link.href
64
65
66 def create_agreement(amount, app=False):
67     try:
68         plan = BillingPlan.objects.get(amount=amount)
69     except BillingPlan.DoesNotExist:
70         plan_id = create_plan(amount)
71     else:
72         plan_id = plan.plan_id
73     start = (timezone.now() + timedelta(0, 3600*24)).astimezone(pytz.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
74     billing_agreement = paypalrestsdk.BillingAgreement({
75         "name": "Subskrypcja klubu WL",
76         "description": "Stałe wsparcie Wolnych Lektur kwotą %s złotych" % amount,
77         "start_date": start,
78         "plan": {
79             "id": plan_id,
80         },
81         "payer": {
82             "payment_method": "paypal"
83         },
84     })
85     if app:
86         billing_agreement['override_merchant_preferences'] = {
87             'return_url': absolute_url('paypal_app_return'),
88         }
89
90     response = billing_agreement.create()
91     if response:
92         return billing_agreement
93     else:
94         raise PaypalError(billing_agreement.error)
95
96
97 def agreement_approval_url(amount, app=False):
98     agreement = create_agreement(amount, app=app)
99     return get_link(agreement.links, 'approval_url')
100
101
102 def get_agreement(agreement_id):
103     try:
104         return paypalrestsdk.BillingAgreement.find(agreement_id)
105     except paypalrestsdk.ResourceNotFound:
106         return None
107
108
109 def check_agreement(agreement_id):
110     a = get_agreement(agreement_id)
111     if a:
112         return a.state == 'Active'
113
114
115 def user_is_subscribed(user):
116     agreements = BillingAgreement.objects.filter(user=user)
117     return any(agreement.check_agreement() for agreement in agreements)
118
119
120 def execute_agreement(token):
121     return paypalrestsdk.BillingAgreement.execute(token)