- 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
- Browser-native date input field by kytta 1 month ago
- Generate and render HTML Table by LLyaudet 1 month, 1 week ago
- My firs Snippets by GutemaG 1 month, 1 week ago
- FileField having auto upload_to path by junaidmgithub 2 months, 2 weeks ago
- LazyPrimaryKeyRelatedField by LLyaudet 2 months, 3 weeks ago
Comments
Please login first before commenting.