Last active
December 19, 2018 05:52
-
-
Save bpsagar/5e2c18acae3d60ccc9310b40874b782b to your computer and use it in GitHub Desktop.
Django view to verify Paypal webook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paypalrestsdk | |
from django.conf import settings | |
from django.http import JsonResponse | |
from django.utils.decorators import method_decorator | |
from django.views.decorators.csrf import csrf_exempt | |
from django.views.generic import View | |
paypalrestsdk.configure(dict( | |
mode=settings.PAYPAL_MODE, | |
client_id=settings.PAYPAL_CLIENT_ID, | |
client_secret=settings.PAYPAL_CLIENT_SECRET | |
)) | |
class PaypalWebhook(View): | |
""" | |
It is best to use the default View as we need to use `request.body` | |
that is unchanged. Also we need to exempt CSRF verification. | |
""" | |
def post(self, request): | |
event_body = request.body.decode('utf-8') | |
transmission_id = request.META.get('HTTP_PAYPAL_TRANSMISSION_ID') | |
timestamp = request.META.get('HTTP_PAYPAL_TRANSMISSION_TIME') | |
webhook_id = settings.PAYPAL_WEBHOOK_ID | |
actual_signature = request.META.get('HTTP_PAYPAL_TRANSMISSION_SIG') | |
cert_url = request.META.get('HTTP_PAYPAL_CERT_URL') | |
auth_algo = request.META.get('HTTP_PAYPAL_AUTH_ALGO') | |
success = paypalrestsdk.WebhookEvent.verify( | |
transmission_id, timestamp, webhook_id, event_body, cert_url, | |
actual_signature, auth_algo | |
) | |
if not success: | |
# Webhook verification failed | |
pass | |
# Handle webhook event | |
return JsonResponse({}) | |
@method_decorator(csrf_exempt) | |
def dispatch(self, *args, **kwargs): | |
return super(PaypalWebhook, self).dispatch(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment