Heroku上的Python应用程序无法打开条纹支付页面

oxosxuxt  于 2022-11-13  发布在  Python
关注(0)|答案(2)|浏览(141)

我正在尝试将Stripe payments集成到flutter web应用中。为此,我编写了一个python脚本,并将其托管在heroku上:

import json
import os
import stripe
from flask import Flask, render_template, jsonify, request
from flask_cors import CORS

# This is your test secret API key.
stripe.api_key = 'sk_test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

app = Flask(__name__, static_folder='public',static_url_path='', template_folder='public') 
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

def calculate_order_amount(items):
    # Replace this constant with a calculation of the order's amount
    # Calculate the order total on the server to prevent
    # people from directly manipulating the amount on the client
    return 1400

@app.route('/create-payment-intent', methods=['POST'])
def create_payment():
    print('Processing checkout')
    request_data = request.data
    request_data = json.loads(request_data.decode('utf-8'))
    print(request_data)

    try:
        parking = request_data['parking']

        items = [
                {
                    'price_data': {
                        'currency':'aud',
                        'product_data': {
                            'name': parking['name'],
                        },
                        'unit_amount': parking['amount'],
                    },
                    'quantity':1,
                }
            ],
        print(request.data)
        # Create a PaymentIntent with the order amount and currency
        intent = stripe.PaymentIntent.create(
            amount=40*100,
            currency='aud',
            payment_method_types=["card"],
        )
        return jsonify({
            'clientSecret': intent['client_secret']
        })
    except Exception as e:
        print('Error Occured: {}'.format(e))
        return jsonify(error=str(e)), 403
        
if __name__ == '__main__':
    app.run(port=4242)

在我的Flutter应用程序中,我正在做以下操作:

var url = Uri.parse('https://spaceshuttleparking-checkout.herokuapp.com/create-payment-intent');
final response = await http.post(
headers:{
  "Accept": "application/json",
  "Access-Control-Allow-Origin": "*"
 },
url,
body: json.encode(
     {
       'parking':{
          'name':parking.name,
          'amount':parking.amount,
              }
       }
       )).then((value) {
         print(value.body);
         print(value.statusCode);
         print(value.request);
        });

在我的flutter应用程序中,我得到了以下输出:

200
POST https://spaceshuttleparking-checkout.herokuapp.com/create-payment-intent
{"clientSecret":"pi_3LXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}

在heroku日志上,我得到以下内容:

2022-09-12T07:49:08.216994+00:00 app[web.1]: Processing checkout
2022-09-12T07:49:08.238030+00:00 app[web.1]: {'parking': {'name': 'Undercover Park & Fly', 'amount': 38}}
2022-09-12T07:49:08.238031+00:00 app[web.1]: b'{"parking":{"name":"Undercover Park & Fly","amount":38}}'
2022-09-12T07:49:08.647809+00:00 heroku[router]: at=info method=POST path="/create-payment-intent" host=spaceshuttleparking-checkout.herokuapp.com request_id=43b4cc48-c3a1-44ec-b240-821901183e5b fwd="119.18.0.79" dyno=web.1 connect=0ms service=431ms status=200 bytes=291 protocol=https
2022-09-12T07:49:08.647485+00:00 app[web.1]: 10.1.32.94 - - [12/Sep/2022:07:49:08 +0000] "POST /create-payment-intent HTTP/1.1" 200 80 "http://localhost:8620/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.33"

我是超级新的东西,所以我不知道我错过了什么。为什么服务器不打开条纹结帐页?

qaxu7uf2

qaxu7uf21#

我不知道intent是否用于打开checkout页面。你可以尝试使用stripe.checkout对象。这是从他们的文档中提取的一些代码:

@app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
  session = stripe.checkout.Session.create(
    line_items=[{
      'price_data': {
        'currency': 'usd',
        'product_data': {
          'name': 'T-shirt',
        },
        'unit_amount': 2000,
      },
      'quantity': 1,
    }],
    mode='payment',
    success_url='https://example.com/success',
    cancel_url='https://example.com/cancel',
  )

  return redirect(session.url, code=303)
wsewodh2

wsewodh22#

您需要配置CORS标头服务器( flask )端。
有关在Flask中执行此操作的更多信息,请参见此答案:Python Flask Cors Issue
一些建议:
正如你也提到,你是新的,这是处理条纹支付的东西,请阅读文件的 flask 和 flask CORS有关安全运行。
第一个问题是避免使用Flask.run()(在您的例子中是app.run()),而是使用一个生产就绪的WSGI服务器。关于如何做到这一点,请参见flask文档的以下部分:https://flask.palletsprojects.com/en/2.2.x/tutorial/deploy/#run-with-a-production-server
其次,如果您正在实现Flask CORS,请确保实现一些CSRF缓解措施。https://testdriven.io/blog/csrf-flask/

相关问题