Skip to content

Instantly share code, notes, and snippets.

@picsoung
Created May 3, 2022 18:13
Show Gist options
  • Save picsoung/6203bc050c41a3580ed4248cd81e0cd6 to your computer and use it in GitHub Desktop.
Save picsoung/6203bc050c41a3580ed4248cd81e0cd6 to your computer and use it in GitHub Desktop.
Typeform Django webhook
import hashlib
import hmac
import json
import base64
import os
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseServerError
from django.views.decorators.csrf import csrf_exempt
from django.utils.encoding import force_bytes
@csrf_exempt
def webhook(request):
if request.method == 'POST':
receivedSignature = request.headers.get("typeform-signature")
header_signature = request.META.get('HTTP_TYPEFORM_SIGNATURE')
if header_signature is None:
return HttpResponseForbidden('Permission denied. Missing TF sig.')
sha_name, signature = header_signature.split('=', 1)
if sha_name != 'sha256':
return HttpResponseServerError('Operation not supported.', status=501)
is_valid = verifySignature(signature, request.body)
if(is_valid != True):
return HttpResponseForbidden('Permission denied.')
return HttpResponse('All good')
def verifySignature(receivedSignature: str, payload):
WEBHOOK_SECRET = "abc123" #os.environ.get('TYPEFORM_SECRET_KEY')
digest = hmac.new(WEBHOOK_SECRET.encode('utf-8'), payload, hashlib.sha256).digest()
e = base64.b64encode(digest).decode()
if(e == receivedSignature):
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment