generated from Code-Institute-Org/gitpod-full-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
webhook_handler.py
164 lines (149 loc) · 6.44 KB
/
webhook_handler.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
from django.http import HttpResponse
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from .models import Order, OrderLineItem
from products.models import Product
from profiles.models import UserProfile
import json
import time
import stripe
class StripeWH_Handler:
"""Handle Stripe webhooks"""
def __init__(self, request):
self.request = request
def _send_confirmation_email(self, order):
"""Send the user a confirmation email"""
cust_email = order.email
subject = render_to_string(
'checkout/confirmation_emails/confirmation_email_subject.txt',
{'order': order})
body = render_to_string(
'checkout/confirmation_emails/confirmation_email_body.txt',
{'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL})
send_mail(
subject,
body,
settings.DEFAULT_FROM_EMAIL,
[cust_email]
)
def handle_event(self, event):
"""
Handle a generic/unknown/unexpected webhook event
"""
return HttpResponse(
content=f'Unhandled webhook received: {event["type"]}',
status=200)
def handle_payment_intent_succeeded(self, event):
"""
Handle the payment_intent.succeeded webhook from Stripe
"""
intent = event.data.object
pid = intent.id
bag = intent.metadata.bag
save_info = intent.metadata.save_info
# Get the Charge object
stripe_charge = stripe.Charge.retrieve(
intent.latest_charge
)
billing_details = stripe_charge.billing_details # updated # noqa
shipping_details = intent.shipping
grand_total = round(stripe_charge.amount / 100, 2) # updated # noqa
# Clean data in the shipping details
for field, value in shipping_details.address.items():
if value == "":
shipping_details.address[field] = None
# Update profile information if save_info was checked
profile = None
username = intent.metadata.username
if username != 'AnonymousUser':
profile = UserProfile.objects.get(user__username=username)
if save_info:
profile.default_phone_number = shipping_details.phone
profile.default_country = shipping_details.address.country
profile.default_postcode = shipping_details.address.postal_code
profile.default_town_or_city = shipping_details.address.city
profile.default_street_address1 = shipping_details.address.line1 # noqa
profile.default_street_address2 = shipping_details.address.line2 # noqa
profile.default_county = shipping_details.address.state
profile.save()
order_exists = False
attempt = 1
while attempt <= 5:
try:
order = Order.objects.get(
full_name__iexact=shipping_details.name,
email__iexact=billing_details.email,
phone_number__iexact=shipping_details.phone,
country__iexact=shipping_details.address.country,
postcode__iexact=shipping_details.address.postal_code,
town_or_city__iexact=shipping_details.address.city,
street_address1__iexact=shipping_details.address.line1,
street_address2__iexact=shipping_details.address.line2,
county__iexact=shipping_details.address.state,
grand_total=grand_total,
original_bag=bag,
stripe_pid=pid,
)
order_exists = True
break
except Order.DoesNotExist:
attempt += 1
time.sleep(1)
if order_exists:
self._send_confirmation_email(order)
return HttpResponse(
content=f'Webhook received: {event["type"]} | SUCCESS: Verified order already in database', # noqa
status=200)
else:
order = None
try:
order = Order.objects.create(
full_name=shipping_details.name,
user_profile=profile,
email=billing_details.email,
phone_number=shipping_details.phone,
country=shipping_details.address.country,
postcode=shipping_details.address.postal_code,
town_or_city=shipping_details.address.city,
street_address1=shipping_details.address.line1,
street_address2=shipping_details.address.line2,
county=shipping_details.address.state,
original_bag=bag,
stripe_pid=pid,
)
for item_id, item_data in json.loads(bag).items():
product = Product.objects.get(id=item_id)
if isinstance(item_data, int):
order_line_item = OrderLineItem(
order=order,
product=product,
quantity=item_data,
)
order_line_item.save()
else:
for size, quantity in item_data['items_by_size'].items(): # noqa
order_line_item = OrderLineItem(
order=order,
product=product,
quantity=quantity,
product_size=size,
)
order_line_item.save()
except Exception as e:
if order:
order.delete()
return HttpResponse(
content=f'Webhook received: {event["type"]} | ERROR: {e}',
status=500)
self._send_confirmation_email(order)
return HttpResponse(
content=f'Webhook received: {event["type"]} | SUCCESS: Created order in webhook',
status=200)
def handle_payment_intent_payment_failed(self, event):
"""
Handle the payment_intent.payment_failed webhook from Stripe
"""
return HttpResponse(
content=f'Webhook received: {event["type"]}',
status=200)