- Author:
- santos22
- Posted:
- March 18, 2020
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
Third party services (e.g. Stripe) optionally sign webhook events to verify it is them sending events. If the third party you use does not provide an SDK or official library for verifying signatures, you can manually verify the signature with this snippet.
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 | # urls.py
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from .views import WebhookView
urlpatterns = [
url(r'^webhook$', csrf_exempt(WebhookView.as_view())),
]
# views.py
import base64
import hashlib
import hmac
from django.conf import settings
from django.http import HttpResponse
from django.views import View
def verify(request):
signature = str.encode(request.META['HTTP_WEBHOOK_SIGNATURE'])
digest = hmac.new(
key=str.encode(settings.WEBHOOK_SECRET),
msg=request.body,
digestmod=hashlib.sha1).digest()
expected_signature = base64.b64encode(digest)
return hmac.compare_digest(signature, expected_signature)
class WebhookView(View):
def dispatch(self, request, *args, **kwargs):
if not verify(request):
return HttpResponse(status=400)
return super().dispatch(request, *args, **kwargs)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.