Python 中的 Hello World
如何从单个文件中使用 wsgi 运行条带的示例。
首先,请安装 python stripe API,即使用 pip:
pip install --user stripe
创建 payment.py
,它在端口 8000 开箱即可创建一个 WSGI 网络服务器
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()
请注意:
- 前端表单包含公钥
- 后端计费部分包含密钥。
运行脚本
python payment.py
使用浏览器导航到
http://localhost:8000/
单击付款按钮并输入信用卡号(4242424242424242)后,将使用令牌过帐表单。因此可以处理付款,最后将 charge
对象打印到浏览器中,其中包含:
...
"paid": true,
"description": "Hello World",
"status": "succeeded"
资源和进一步阅读:
- WSGI 帖子: http : //wsgi.tutorial.codepoint.net/parsing-the-request-post
- 前端表格: https : //stripe.com/docs/checkout/tutorial
- 后端费用: https : //stripe.com/docs/charges