Skip to content

Instantly share code, notes, and snippets.

@ojii
Created February 26, 2012 16:01
Show Gist options
  • Save ojii/1917459 to your computer and use it in GitHub Desktop.
Save ojii/1917459 to your computer and use it in GitHub Desktop.
paypalipn
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from raven.contrib.django.models import get_client
from registration.forms import IPNForm
import logging
import urllib2
URLS = {
True:'https://www.paypal.com/cgi-bin/webscr',
False: 'https://www.sandbox.paypal.com/cgi-bin/webscr',
}
@require_POST
@csrf_exempt
def ipn(request):
client = get_client()
client.captureMessage("IPN:request", data={'level': logging.INFO})
form = IPNForm(request.POST)
if form.is_valid():
client.captureMessage("IPN:form valid", data={'level': logging.INFO})
data = form.clean()
if verify(request, data.get('test_ipn', '-1') == '1', client):
client.captureMessage("IPN:verified", data={'level': logging.INFO})
form.save()
else:
client.captureMessage("IPN:verification failed", data={'level': logging.INFO})
else:
client.captureMessage("IPN:form invalid:%s" % form.errors.as_text(), data={'level': logging.INFO})
return HttpResponse('ok')
def verify(request, is_test, client):
client.captureMessage('IPN:verify:%s' % is_test)
data = 'cmd=_notify-validate&%s' % request.raw_post_data
client.captureMessage('IPN:data:%s' % data)
url = URLS[is_test]
client.captureMessage('IPN:url:%s' % url)
content = urllib2.urlopen(url, data).read()
client.captureMessage('IPN:verify:response:%s' % content)
return content.strip() == 'VERIFIED'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment