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"

資源和進一步閱讀: