Login

Verify events sent to your webhook endpoints

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.