-
-
Notifications
You must be signed in to change notification settings - Fork 995
/
Copy pathviews.py
359 lines (305 loc) · 12.5 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import decimal
import json
import logging
import stripe
from django.conf import settings
from django.contrib import messages
from django.core.mail import send_mail
from django.db import IntegrityError, transaction
from django.forms.models import modelformset_factory
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .forms import DjangoHeroForm, DonationForm, PaymentForm
from .models import DjangoHero, Donation, Payment, Testimonial
logger = logging.getLogger(__name__)
def index(request):
testimonial = Testimonial.objects.filter(is_active=True).order_by("?").first()
return render(
request,
"fundraising/index.html",
{
"testimonial": testimonial,
},
)
@require_POST
def configure_checkout_session(request):
"""
Configure the payment session for Stripe.
Return the Session ID.
Key attributes are:
- mode: payment (for one-time charge) or subscription
- line_items: including price_data because users configure the donation
price.
TODOs
- Standard amounts could use active Prices, rather than ad-hoc price_data.
- Tie Stripe customers to site User accounts.
- If a user is logged in, we can create the session for the correct
customer.
- Stripe's documented flows are VERY keen that we create the customer
first, although the session will do that if we don't.
- Allow selecting currency. (Smaller task.) Users receive an additional
charge making payments in foreign currencies. Stripe will convert all
payments without further charge.
"""
# Form data:
# - The interval: which determines the Product and the mode.
# - The amount: which goes to the Price data.
form = PaymentForm(request.POST)
if not form.is_valid():
data = {"success": False, "error": form.errors}
return JsonResponse(data)
amount = form.cleaned_data["amount"]
interval = form.cleaned_data["interval"]
product_details = settings.PRODUCTS[interval]
is_subscription = product_details.get("recurring", True)
price_data = {
"currency": "usd",
"unit_amount": amount * 100,
"product": product_details["product_id"],
}
if is_subscription:
price_data["recurring"] = {
"interval": product_details["interval"],
"interval_count": product_details["interval_count"],
}
try:
session = stripe.checkout.Session.create(
payment_method_types=["card"],
line_items=[{"price_data": price_data, "quantity": 1}],
mode="subscription" if is_subscription else "payment",
success_url=request.build_absolute_uri(reverse("fundraising:thank-you")),
cancel_url=request.build_absolute_uri(reverse("fundraising:index")),
# TODO: Drop this when updating API.
stripe_version="2020-08-27",
)
return JsonResponse({"success": True, "sessionId": session["id"]})
except Exception as e:
logger.exception("Error configuring Stripe session.")
return JsonResponse({"success": False, "error": str(e)})
def thank_you(request):
"""
Generic thank you page. In theory only reached via successful payment, but
no information is passed from Stripe to be sure.
"""
return render(request, "fundraising/thank-you.html", {})
# TODO: Use Stripe's customer portal.
@never_cache
def manage_donations(request, hero):
hero = get_object_or_404(DjangoHero, pk=hero)
recurring_donations = hero.donation_set.exclude(stripe_subscription_id="")
past_payments = (
Payment.objects.filter(donation__donor=hero)
.select_related("donation")
.order_by("-date")
)
ModifyDonationsFormset = modelformset_factory(Donation, form=DonationForm, extra=0)
if request.method == "POST":
hero_form = DjangoHeroForm(
data=request.POST,
files=request.FILES,
instance=hero,
)
modify_donations_formset = ModifyDonationsFormset(
request.POST, queryset=recurring_donations
)
if hero_form.is_valid() and modify_donations_formset.is_valid():
hero_form.save()
modify_donations_formset.save()
messages.success(request, _("Your information has been updated."))
else:
hero_form = DjangoHeroForm(instance=hero)
modify_donations_formset = ModifyDonationsFormset(queryset=recurring_donations)
return render(
request,
"fundraising/manage-donations.html",
{
"hero": hero,
"hero_form": hero_form,
"modify_donations_formset": modify_donations_formset,
"recurring_donations": recurring_donations,
"past_payments": past_payments,
"stripe_publishable_key": settings.STRIPE_PUBLISHABLE_KEY,
},
)
@require_POST
def update_card(request):
donation = get_object_or_404(Donation, id=request.POST["donation_id"])
try:
customer = stripe.Customer.retrieve(donation.stripe_customer_id)
subscription = customer.subscriptions.retrieve(donation.stripe_subscription_id)
subscription.source = request.POST["stripe_token"]
subscription.save()
except stripe.error.StripeError as e:
data = {"success": False, "error": str(e)}
else:
data = {"success": True}
return JsonResponse(data)
@require_POST
def cancel_donation(request, hero):
donation_id = request.POST.get("donation")
hero = get_object_or_404(DjangoHero, pk=hero)
donations = hero.donation_set.exclude(stripe_subscription_id="")
donation = get_object_or_404(donations, pk=donation_id)
customer = stripe.Customer.retrieve(donation.stripe_customer_id)
customer.subscriptions.retrieve(donation.stripe_subscription_id).delete()
donation.stripe_subscription_id = ""
donation.save()
messages.success(request, _("Your donation has been canceled."))
return redirect("fundraising:manage-donations", hero=hero.pk)
@require_POST
@csrf_exempt
def receive_webhook(request):
try:
data = json.loads(request.body.decode())
except ValueError:
return HttpResponse(status=422)
# For security, re-request the event object from Stripe.
try:
event = stripe.Event.retrieve(data["id"])
except stripe.error.InvalidRequestError:
return HttpResponse(status=422)
return WebhookHandler(event).handle()
class WebhookHandler:
def __init__(self, event):
self.event = event
def handle(self):
handlers = {
"invoice.payment_succeeded": self.payment_succeeded,
"invoice.payment_failed": self.payment_failed,
"customer.subscription.deleted": self.subscription_cancelled,
"checkout.session.completed": self.checkout_session_completed,
}
handler = handlers.get(self.event.type, lambda: HttpResponse(422))
if not self.event.data.object:
return HttpResponse(status=422)
try:
with transaction.atomic():
return handler()
except IntegrityError as e:
logger.error(f"Integrity error in webhook handler: {e}")
return HttpResponse(status=500)
except Exception as e:
logger.error(f"Error in webhook handler: {e}")
return HttpResponse(status=500)
def payment_succeeded(self):
invoice = self.event.data.object
# Ensure we haven't already processed this payment
if Payment.objects.filter(stripe_charge_id=invoice.charge).exists():
# We need a 2xx response otherwise Stripe will keep trying.
return HttpResponse()
donation = get_object_or_404(
Donation, stripe_subscription_id=invoice.subscription
)
amount = decimal.Decimal(invoice.total) / 100
if invoice.charge:
donation.payment_set.create(amount=amount, stripe_charge_id=invoice.charge)
return HttpResponse(status=201)
def subscription_cancelled(self):
subscription = self.event.data.object
donation = get_object_or_404(Donation, stripe_subscription_id=subscription.id)
donation.stripe_subscription_id = ""
donation.save()
mail_text = render_to_string(
"fundraising/email/subscription_cancelled.txt", {"donation": donation}
)
send_mail(
_("Payment cancelled"),
mail_text,
settings.DEFAULT_FROM_EMAIL,
[donation.donor.email],
)
return HttpResponse(status=204)
def payment_failed(self):
invoice = self.event.data.object
donation = get_object_or_404(
Donation, stripe_subscription_id=invoice.subscription
)
mail_text = render_to_string(
"fundraising/email/payment_failed.txt", {"donation": donation}
)
send_mail(
_("Payment failed"),
mail_text,
settings.DEFAULT_FROM_EMAIL,
[donation.donor.email],
)
return HttpResponse(status=204)
def get_donation_interval(self, session):
"""
Helper to determine Donation.interval from completed Stripe Session.
"""
if session.mode == "payment":
return "onetime"
# Access the interval via the attached price object.
# See https://stripe.com/docs/api/subscriptions/object
# TODO: remove stripe_version when updating account settings.
subscription = stripe.Subscription.retrieve(
session.subscription, stripe_version="2020-08-27"
)
recurrance = subscription["items"].data[0].price.recurring
if recurrance.interval == "year":
return "yearly"
elif recurrance.interval_count == 3:
return "quarterly"
else:
return "monthly"
def checkout_session_completed(self):
try:
"""
> Occurs when a Checkout Session has been successfully completed.
https://stripe.com/docs/api/events/types#event_types-checkout.session.completed
"""
session = self.event.data.object
if isinstance(session, dict):
session = stripe.util.convert_to_stripe_object(
session, stripe.api_key, None
)
# TODO: remove stripe_version when updating account settings.
customer = stripe.Customer.retrieve(
session.get("customer"), stripe_version="2020-08-27"
)
hero, _created = DjangoHero.objects.get_or_create(
stripe_customer_id=customer.id,
defaults={
"email": customer.email,
},
)
interval = self.get_donation_interval(session)
dollar_amount = decimal.Decimal(session.amount_total / 100).quantize(
decimal.Decimal(".01"), rounding=decimal.ROUND_HALF_UP
)
donation = Donation.objects.create(
donor=hero,
stripe_customer_id=customer.id,
receipt_email=customer.email,
subscription_amount=dollar_amount,
interval=interval,
stripe_subscription_id=session.subscription or "",
)
if interval == "onetime":
payment_intent = stripe.PaymentIntent.retrieve(session.payment_intent)
charge = payment_intent.charges.data[0]
donation.payment_set.create(
amount=dollar_amount,
stripe_charge_id=charge.id,
)
# Send an email message about managing your donation
message = render_to_string(
"fundraising/email/thank-you.html", {"donation": donation}
)
send_mail(
_("Thank you for your donation to the Django Software Foundation"),
message,
settings.FUNDRAISING_DEFAULT_FROM_EMAIL,
[donation.receipt_email],
)
return HttpResponse(status=204)
except IntegrityError as e:
logger.error(f"Integrity error during checkout session: {e}")
return HttpResponse(status=500)