【问题标题】:Python app on heroku dosn't open the Stripe Payment pageheroku 上的 Python 应用程序无法打开 Stripe 支付页面
【发布时间】:2022-09-23 05:28:05
【问题描述】:

我正在尝试将 Stripe 支付集成到一个颤振的网络应用程序中。为此,我编写了一个我在 heroku 上托管的 python 脚本:

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)

在我的颤振应用程序中,我正在这样做:

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);
        });

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

    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\"

我对这些东西超级陌生,所以我不确定我错过了什么。为什么服务器不打开条带结帐页面?

标签: python flutter dart heroku flutter-web


【解决方案1】:

我不知道是否使用意图打开结帐页面。 您可以尝试使用 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)

【讨论】:

  • 感谢您的回答。仍然没有任何反应。我不断收到 XMLHttpRequest 错误。由于 CORS 错误,Chrome 的控制台会抛出阻塞。我正在使用 Flask 的 CORS 包并发送“Accept”:“application/json”、“Access-Control-Allow-Origin”:“*”、“Access-Origin-Allow-Methods”:“GET、DELETE、HEAD、 OPTIONS, POST" 与发布请求,但是错误并没有消失。
  • CORS 是一个服务器问题,因此如果您在发布请求中放置接受标头并不重要。唯一重要的是响应中的标头。您可以尝试创建一个新项目并复制粘贴完整的文档代码以获得一个工作示例。
  • 谢谢..我的问题没有解决,但您确实正确回答了问题。所以我会将其标记为已接受。
【解决方案2】:

您需要配置 CORS 标头服务器(Flask)端。

有关在 Flask 中执行此操作的更多信息,请参阅此答案:Python Flask Cors Issue


一些建议:

正如您还提到您是新手,它正在处理 Stripe 支付的东西,请阅读 Flask 和 Flask CORS 有关安全运行的文档。

第一个问题是避免使用Flask.run()(在您的示例中为app.run()),而是使用生产就绪的WSGI服务器。请参阅烧瓶文档的这一部分以了解如何执行此操作:https://flask.palletsprojects.com/en/2.2.x/tutorial/deploy/#run-with-a-production-server

其次,如果您正在实施 Flask CORS,请务必实施一些 CSRF 缓解措施。一篇不错的文章可以在这里找到:https://testdriven.io/blog/csrf-flask/

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 1970-01-01
    • 2023-04-11
    • 2020-09-16
    • 2018-04-23
    • 2018-03-30
    • 2018-03-27
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多