An example how to run stripe out of the box with wsgi from a single file.
At first, please install the python stripe API, i.e. with pip:
pip install --user stripe
Create payment.py
which creates a WSGI webserver at port 8000 out of the box
html = """
<html>
<body>
<p>%(output)s</p>
</body>
</html>
"""
form = """
<form action="" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_6pRNASCoBOKtIshFeQd4XMUh"
data-amount="999"
data-name="Stripe.com"
data-description="Hello World"
data-locale="auto">
</script>
</form>
"""
def application(environ, start_response):
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
request_body = environ['wsgi.input'].read(request_body_size)
post = parse_qs(request_body)
out = ''
if post:
print post
token = post.get('stripeToken', [''])[0]
token = escape(token)
if token:
import stripe
stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"
try:
charge = stripe.Charge.create(
amount="999",
currency="usd",
source=token,
description="Hello World",
)
out = '<pre>charge: %s</pre>' % (charge,)
except Exception as e:
print 'Exception %s' % (str(e),)
else:
out = 'missing in post: token'
else:
out = form
response_body = html % {
'output': out,
}
status = '200 OK'
response_headers = [('content-type', 'text/html;charset=utf-8')]
start_response(status, response_headers)
return [response_body]
from wsgiref.simple_server import make_server
from cgi import parse_qs, escape
httpd = make_server('', 8000, application)
httpd.serve_forever()
Please note:
Run the script
python payment.py
Navigate with your browser to
http://localhost:8000/
After clicking the Pay-Button and entering the credit card number (4242424242424242) the form is posted with the token. So the payment could be processed and finally the charge
object will be printed into the browser, which contains:
...
"paid": true,
"description": "Hello World",
"status": "succeeded"
Resources and further reading: