我正在尝试在我的 Heroku 网络应用程序中实现 Stripe 支付系统。您可以在下面看到一个 html 文件,其中有一个“购买”按钮,单击该按钮会调用 javascript 函数“MyFunction()”。发生这种情况后,javascript 函数调用 Flask(Python 文件)中的 create_checkout_session() 函数,该函数将 session 结帐 ID 返回给 javascript 函数,该函数重定向到支付页面。出于某种原因,以下过程在本地主机上完美运行,但在我部署到 Heroku 时失败。由于某种原因,我在 Heroku 中收到错误 500。
html文件
<section class="section">
<div class="container">
<button class="btn btn-outline-info" onclick="myFunction()" id="stripePay">Purchase!</button>
</div>
</section>
<script>
function myFunction() {
//stripe
// Get Stripe publishable key
// Initialize Stripe.js
const stripe = Stripe('pk_test_zcqqggPiGsbFA49H0BE4Mxj200AyZDDWnN');
// new
// Event handler
// Get Checkout Session ID
fetch("/create-checkout-session")
.then((result) => { return result.json(); })
.then((data) => {
console.log(data);
// Redirect to Stripe Checkout
return stripe.redirectToCheckout(data)
})
};
</script>
Python文件
@app.route("/create-checkout-session")
def create_checkout_session():
domain_url = "http://localhost:5000/"
stripe.api_key = stripe_keys["secret_key"]
# Create new Checkout Session for the order
# Other optional params include:
# [billing_address_collection] - to display billing address details on the page
# [customer] - if you have an existing Stripe Customer ID
# [payment_intent_data] - capture the payment later
# [customer_email] - prefill the email input in the form
# For full details see https://stripe.com/docs/api/checkout/sessions/create
# ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + "success?session_id={CHECKOUT_SESSION_ID}",
cancel_url=domain_url + "cancelled",
payment_method_types=["card"],
mode="payment",
line_items=[
{
"name": "T-shirt",
"quantity": 1,
"currency": "usd",
"amount": "2000",
}
]
)
return jsonify({"sessionId": checkout_session["id"]})
编辑:
最佳答案
从日志截图来看,我猜这是因为您的应用程序的处理时间太长了。查看服务时间为383ms
service=383ms
但是如果连接超过 300 毫秒,Heroku 会超时 (link) .这就是为什么您的应用程序可以在本地运行但不能在 Heroku 上运行的原因。换句话说,您必须在超时开始之前返回一些响应。
你可以试试这些方法:
- 在 Procfile 中添加一个
--timeout 400
选项。例如:web:gunicorn app:app --timeout 400
- 尝试实现流式响应。例如,在 Flask 中,您可以使用此代码:https://flask.palletsprojects.com/en/1.1.x/patterns/streaming/ .对于第一个选项不起作用的用例,您可以找到类似的。
关于javascript - 在部署中实现 strip 支付时出错(Heroku),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64963107/