Django PayPal IPN Processing

The code below is for Python 3 and Django 1.7. Set the IPN encoding to UTF-8 in PayPal.

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
import urllib.parse
import requests
def post(self, request):
paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'
query = 'cmd=_notify-validate'
for key, value in request.POST.items():
query += '&%s=%s' % (key, urllib.parse.quote(value))
res = requests.post(paypal_url, data=query, timeout=10)
if res.text == 'VERIFIED':
# Extract POST variables here
payment_status = request.POST.get('payment_status')
if payment_status == 'Completed':
# Successful payment
elif payment_status == 'Reversed' or payment_status == 'Refunded':
# Payment reversed