Skip to content

Commit

Permalink
Add simple stripe webhook
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan committed Mar 28, 2023
1 parent f91333d commit 1033eb3
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ To run unit tests:

For migrations, add `BF_ADMIN_USERNAME` and `BF_ADMIN_PASSWORD` to virtual environment to create admin user.

## Stripe

For a webhook you need to configure stripe settings in a dashboard.

## Notes

### Methodology
Expand Down
5 changes: 5 additions & 0 deletions api/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.urls import path, include

urlpatterns = [
path('v1/', include('api.v1.urls'), name='v1'),
]
Empty file added api/v1/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions api/v1/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.urls import path

from api.v1.views import StripeWebhook

urlpatterns = [
path('webhooks/stripe/', StripeWebhook.as_view(), name='stripe_webhook'),
]
31 changes: 31 additions & 0 deletions api/v1/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from http import HTTPStatus
import json

from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt

import stripe


@method_decorator(csrf_exempt, name='dispatch')
class StripeWebhook(View):
def post(self, request, *args, **kwargs):
try:
sig_header = request.headers['Stripe-Signature']
except KeyError:
return HttpResponse(status=HTTPStatus.FORBIDDEN)

try:
event = stripe.Webhook.construct_event(
request.body, sig_header, settings.STRIPE_ENDPOINT_SECRET
)
except ValueError as e:
raise PermissionDenied()
except stripe.error.SignatureVerificationError as verification_err:
return HttpResponse(status=HTTPStatus.FORBIDDEN)

return HttpResponse(status=HTTPStatus.OK)
1 change: 1 addition & 0 deletions core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
path('robots.txt', TemplateView.as_view(template_name='base/robots.txt', content_type='text/plain'), name='robots'),
path('payments/', include('payments.urls')),
path('docs/', include('docs.urls')),
path('api/', include('api.urls')),
]


Expand Down

0 comments on commit 1033eb3

Please sign in to comment.