我想通过Stripe创建一个付款表单,其中包含用户的电子邮件地址和付款信息。然后,该信息通过Flask发送到我的服务器,如果用户的电子邮件地址符合我设置的特定条件,则我将处理付款。否则,我将取消付款。
从我的研究中,我发现了两种似乎可行的方法。尽管我都无法在其中形成一个完整的解决方案。
第一种方法是遵循本指南https://stripe.com/docs/payments/checkout/one-time并稍加修改。当用户单击我的“立即购买”按钮时,我将发布到以下API:
@app.route("/generate_session", methods=["POST"])
def generate_session():
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'name': 'T-shirt',
'description': 'Comfortable cotton t-shirt',
'images': ['https://example.com/t-shirt.png'],
'amount': 500,
'currency': 'gbp',
'quantity': 1,
}],
payment_intent_data={
'capture_method': 'manual',
},
success_url='http://localhost:5000/success',
cancel_url='http://localhost:5000/cancel',
)
return session["id"]
然后我使用以下会话ID执行条纹redirectCheckout
函数:
var stripe = Stripe('pk_test_lp7ZS0B23jNmorIoW6Wj0Rs2009E1xTCwS');
sessionId = "" // send POST and get response
stripe.redirectToCheckout({
sessionId: sessionId
}).then(function (result) {
});
由于我已将'capture_method'
定义为'manual'
,因此实际上不会提交付款。我需要做的是,一旦用户单击“付款”,便使用session_id POST到/ api / process_payment。这就是我正在努力的地方。
@app.route("/api/process_payment", methods=["POST])
def process_payment():
data = request.get_json()
session_id = data["session_id"]
session = stripe.checkout.Session.retrieve(session_id)
payment_intent = session["payment_intent"]
if session["customer_email"] == "abc@mail.com": # will perform a different check, just a trivial example
stripe.PaymentIntent.confirm(payment_intent,)
# verify payment
success = True
else:
stripe.PaymentIntent.cancel(payment_intent,)
success = False
return jsonify({"success": success})
这是我用来帮助该部分的文档:https://stripe.com/docs/api/checkout/sessions/retrieve,https://stripe.com/docs/api/payment_intents/confirm,https://stripe.com/docs/api/payment_intents/cancel。
第二种方法是使用Stripe Elements制作一个包含电子邮件和付款信息的表格。并且由于这已经在处理之前将信息发送到了我的服务器,因此在处理付款之前先检查电子邮件是很简单的。但是,我认为Stripe Elements绝对是一团糟,我想不惜一切代价避免使用如此糟糕的样板代码。我已经尝试过制作适合自己规格的表格,但距离我还很近。我找到了这个jsfiddle https://jsfiddle.net/ywain/foc0L56q/,但它似乎不完整,更改CSS似乎很痛苦。
理想情况下,我希望帮助您解决第一个选项,但是如果有人可以帮助我完成第二个选项,那也很好。
答案 0 :(得分:0)
我认为我已经解决了第一种方法,方法是将success_url设置为在自定义页面上将session_id
作为参数包含在内。然后,当该页面加载时,我通过Flask获取session_id并按以下方式检索信息
data = request.args
session_id = data["session_id"]
session = stripe.checkout.Session.retrieve(session_id)
payment_intent_id = session["payment_intent"]
payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id,)
customer_email = payment_intent["charges"]["data"][0]["billing_details"]["email"]
if customer_email == "abc@mail.com": # will perform a different check, just a trivial example
stripe.PaymentIntent.capture(payment_intent_id, )
# verify payment
success = True
else:
stripe.PaymentIntent.cancel(payment_intent_id, )
success = False
return f"{success}"
编辑:如前所述,这会暂时搁置资金,因此也许不是最好的主意。正在研究方法2。