generated from Code-Institute-Org/gitpod-full-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebhooks.py
54 lines (44 loc) · 1.65 KB
/
webhooks.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
from django.conf import settings
from django.http import HttpResponse
from checkout.webhook_handler import StripeWH_Handler
import stripe
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
@require_POST
@csrf_exempt
def webhook(request):
""" Listen for webhooks from Stripe """
# Define Stripe Credentials Here
wh_secret = settings.STRIPE_WH_SECRET
stripe.api_key = settings.STRIPE_SECRET_KEY
# Fetch the webhook data and verify its signature
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, wh_secret
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
except Exception as e:
return HttpResponse(content=e, status=400)
# Set up a webhook handler
handler = StripeWH_Handler(request)
# Map webhook events to relevant handler functions
event_map = {
'payment_intent.succeeded': handler.handle_payment_intent_succeeded,
'payment_intent.payment_failed': handler.handle_payment_intent_payment_failed,
}
# Get the webhook type from Stripe
event_type = event['type']
# If there's a handler for it, get it from the event map
# Use the generic one by default
event_handler = event_map.get(event_type, handler.handle_event)
# Call the event handler with the event
response = event_handler(event)
return response