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. Treat empty value on DateRangeFilter as a filter for non filled dates by kmmbvnr 1 month ago
  2. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 months ago
  3. codigo alto nivel by MrRocklion 4 months ago
  4. Load template from specific app by Krzysiek555 4 months, 3 weeks ago
  5. PostgreSQL JSON subqueries by dolamroth 4 months, 3 weeks ago

Comments

Please login first before commenting.