python - Flask中的Stripe Checkout流程如何携带userID这样的变量?

标签 python flask stripe-payments

我有一个简单的 flask 站点,它连接到 python 中的拨号脚本。它会调用您在主页上输入的电话号码,并连接到您的电话号码以及其他一些东西。我如何传递客户试图通过 Stripe Checkout 流程调用的电话号码?

目前,我在数据库中共享了客户的主页信息,它通过 URL ex site.com/subit/userID1234 通过各种路由传递。该网站有效,但我不确定如何通过 Stripe Checkout 流程传递这些变量。

我正在尝试从/stripe_purchase_page/到/webhook/

    #STRIPE
@app.route('/stripe_purchase_page/<uniqueID>')
def stripePurchasePage(uniqueID):
    render_template('stripe_redirect_test.html')


stripe_keys = {
    "secret_key": os.environ["STRIPE_SECRET_KEY"],
    "publishable_key": os.environ["STRIPE_PUBLISHABLE_KEY"],
    "endpoint_secret": os.environ["STRIPE_ENDPOINT_SECRET"]
}


stripe.api_key = stripe_keys["secret_key"]

# @app.route("/")
# def index():
#     return render_template("index.html")


@app.route("/config")
def get_publishable_key():
    # customer = request.form['customer']
    # print(customer)
    stripe_config = {"publicKey": stripe_keys["publishable_key"]}
    return jsonify(stripe_config)


@app.route("/create-checkout-session")
def create_checkout_session():
    domain_url = "http://localhost:5000/"
    stripe.api_key = stripe_keys["secret_key"]

    try:
        # 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] - lets capture the payment later
        # [customer_email] - lets you 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"]})
    except Exception as e:
        return jsonify(error=str(e)), 403


@app.route("/webhook", methods=['POST'])
def stripe_webhook():
    payload = request.get_data(as_text=True)
    sig_header = request.headers.get('Stripe-Signature')

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, stripe_keys["endpoint_secret"]
        )

    except ValueError as e:
        # Invalid payload
        return 'Invalid payload', 400
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        return 'Invalid signature', 400

    # Handle the checkout.session.completed event
    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']

        # Fulfill the purchase...
        handle_checkout_session(session)

    return 'Success', 200


def handle_checkout_session(session):
    print("Payment was successful.")
    # run some custom code here with the Unique ID

最佳答案

将您的变量添加到另一个答案中提到的元数据,然后在您的成功路由中访问 strip session 对象并将它们隔离在成功路由中。

checkout_session = stripe.checkout.Session.create(
        client_reference_id=token,
        success_url=domain_url + "success?session_id={CHECKOUT_SESSION_ID}",
        cancel_url=domain_url + "cancelled",
        payment_method_types=["card"],
        mode="payment",
        line_items=[
            {
                "name": "AICreated.Art - " + str(param) + " Credits",
                "quantity": 1,
                "currency": "usd",
                "amount": amt,
            }
        ],
        metadata={
             'user_id': 1234,
             'token': 'abcdf'
        }

在 webhook 之后命中的成功 route :

@app.route("/success")
def success():
   sessions = stripe.checkout.Session.list()
   print(sessions.data[00]) # tree view
   data = {'username': sessions.data[00].metadata.user_id, 'token': sessions.data[00].metadata.token}
   return render_template('home/success.html', data=data, title="Home")

关于python - Flask中的Stripe Checkout流程如何携带userID这样的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64405557/

相关文章:

python - 从 GCP 安装文档运行 "[CRITICAL] WORKER TIMEOUT"时,日志中的 "Hello Cloud Run with Python"

javascript - Flask WTForms SelectMultipleField 限制最大选择数

python - 无法理解Python的那行代码

ruby-on-rails - Stripe - 在测试模式下向客户添加无效卡?

api - 生成 API key 的最佳方法?

Python 2.7 - 帮助使用 API (HL7)

python - 在 Anaconda : "ImportError: No module named django.core.wsgi" 中的 Python 上使用 mod_wsgi 配置 Django 时出错

python - 在 matplotlib 中绘制 "real size"图形(滚动条而不是缩放)

python - 如何在 SQLITE3 上关闭和删除数据库后再次打开数据库

ios - 并非所有 Stripe 占位符同时在我的屏幕上可见