Skip to content

Commit

Permalink
Add class methods to webhook handler and webhook view
Browse files Browse the repository at this point in the history
  • Loading branch information
Awoyalejohn committed Aug 4, 2022
1 parent 4c84078 commit 8ec5bfc
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 4 deletions.
2 changes: 2 additions & 0 deletions checkout/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from django.urls import path
from checkout.views import Checkout, CheckoutSuccess
from .webhooks import webhook

urlpatterns = [
path('', Checkout.as_view(), name='checkout'),
path('checkout_success/<order_number>', CheckoutSuccess.as_view(), name='checkout_success'),
path('wh/>', webhook, name='webhook'),
]
21 changes: 19 additions & 2 deletions checkout/webhook_handler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.http import HttpResponse


class StripeWebhookHandler:
class StripeWH_Handler:
"""Handle Stripe webhooks"""

def __init__(self, request):
Expand All @@ -11,7 +11,24 @@ 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
"""
return HttpResponse(
content=f'Webhook received: {event["type"]}',
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)



54 changes: 54 additions & 0 deletions checkout/webhooks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt

from checkout.webhook_handler import StripeWH_Handler

import stripe

@require_POST
@csrf_exempt
def webhook(request):
"""Listen for webhooks from Stripe"""
# Setup
wh_secret = settings.STRIPE_WH_SECRET
stripe.api_key = settings.STRIPE_SECRET_KEY

# Get 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
5 changes: 3 additions & 2 deletions graphicsdesignspace/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['graphics-design-space.herokuapp.com', '127.0.0.1']
ALLOWED_HOSTS = ['graphics-design-space.herokuapp.com', '127.0.0.1', 'localhost']


# Application definition
Expand Down Expand Up @@ -191,4 +191,5 @@
DISCOUNT_PERCENTAGE = 10
STRIPE_CURRENCY = 'gbp'
STRIPE_PUBLIC_KEY = os.getenv('STRIPE_PUBLIC_KEY')
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY')
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY')
STRIPE_WH_SECRET = os.getenv('STRIPE_WH_SECRET')

0 comments on commit 8ec5bfc

Please sign in to comment.