Skip to content

Instantly share code, notes, and snippets.

@czekan
Last active December 24, 2015 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czekan/6825821 to your computer and use it in GitHub Desktop.
Save czekan/6825821 to your computer and use it in GitHub Desktop.
PayPal IPN message verification. Example is in Flask, but it should be easy to move it to other framework. It is encoding proof :), so when paypal send you a message with encoded characters it will handle it smoothly. If you want to move it to different framework remember that 'request.data' is a string in Flask not a unicode.
import urllib
import urlparse
from flask import request
from your_app import app
# set it to True in production mode
app.config['PAYPAL_LIVE'] = False
PP_SCR_LIVE_URL = 'https://www.paypal.com/cgi-bin/webscr'
PP_SCR_SANDBOX_URL = 'https://www.sandbox.paypal.com/cgi-bin/webscr'
PP_SCR_URL = PP_SCR_LIVE_URL if app.config['PAYPAL_LIVE'] else PP_SCR_SANDBOX_URL
def verify_ipn_message(data):
verify_string = 'cmd=_notify-validate&%s' % data
response = urllib.urlopen(PP_SCR_URL, data=verify_string)
return response.read() == 'VERIFIED', verify_string
@app.route('/paypal/ipn', methods=['POST'])
def ipn():
verified, verify_string = verify_ipn_message(request.data)
if verified:
# Do something with received message if it is valid
print "PayPal transaction was verified successfully."
# eg. parse it
data = urlparse.parse_qs(verify_string)
# or create a dict:
# data = dict(urlparse.parse_qsl(verify_string))
print "IPN message: ", data
return "Paypal IPN message verified.", 200
else:
# Do something if it is invalid
return "Paypal IPN message could not be verified.", 403
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment