简体   繁体   English

在访问变量和设置 Stripe Connect (Flask) 时遇到问题

[英]Having Trouble Accessing Variables & Setting Up Stripe Connect (Flask)

I'm building a Flask marketplace app (using Stripe Collect payments then pay out ) where users can choose how much they want to pay (think fundraiser).我正在构建一个 Flask 市场应用程序(使用 Stripe Collect 付款然后付款),用户可以在其中选择他们想要支付的金额(想想筹款活动)。

I am having trouble moving necessary data around appropriately throughout the checkout process and could really use some help.在整个结账过程中,我无法适当地移动必要的数据,我真的可以使用一些帮助。

Once a user enters how much they'd like to donate, the donation amount and the owner of the campaign they'd like to donate to are sent to the below /pay route where they see a form to enter in their card details with a "Submit Payment" button.一旦用户输入他们想要捐赠的金额,他们想要捐赠的捐赠金额和活动的所有者将被发送到下面的/pay路线,在那里他们会看到一个表格,可以在他们的卡片详细信息中输入“提交付款”按钮。

@app.route('/pay', methods=['GET', 'POST'])
def pay():
    campaign = Campaign.query.get_or_404(request.args["campaign_id"])
    owner = User.query.get_or_404(campaign.user_id) #owner of the campaign
    donation_amount = request.args['amount_entered'] # EX: "1000"
    return render_template('payment_form.html', campaign=campaign, owner=owner, amount=donation_amount)

The file, payment_form.html , has a simple Stripe form like this:文件payment_form.html有一个简单的 Stripe 表单,如下所示:

<form method="post" id="payment-form" class="sr-payment-form">
    <div class="sr-form-row">
        <label for="card-element">Credit or debit card</label>
        <div style="width: 30em" id="card-element"></div>
    </div>
    <div>
        <span style="width: 30em; height: 2em; letter-spacing: 0em" id="card-errors" role="alert"></span>
    </div>
    <button id="card-button" style="width: 33em;">Submit Payment</button>
</form>

And whenever someone enters their card info and submits the payment, I have a JavaScript file that listens for it and processes the payment (this does not work yet).每当有人输入他们的卡信息并提交付款时,我都会有一个 JavaScript 文件来侦听它并处理付款(这还不起作用)。

var form = document.getElementById('payment-form');

form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  fetch("/pay_now", {
    method: "GET",
    headers: {
      "Content-Type": "application/json"
    },
  })
  .then(response => response.json())
  .then(data => {
      // not sure what to do here
  });
  stripe.confirmCardPayment(clientSecret, {
    payment_method: {
      card: card,
      billing_details: {
        name: 'Jenny Rosen' //placeholder (would like to replace)
      }
    }
  }).then(function(result) {
    if (result.error) {
      console.log(result.error.message);
    } else {
      if (result.paymentIntent.status === 'succeeded') {
    }
  });
});

This script fetches the below Flask API /pay_now and should return the clientSecret variable as well as other necessary data to complete the transaction.此脚本获取以下 Flask API /pay_now并应返回clientSecret变量以及完成交易所需的其他数据。

@app.route('/pay_now', methods=['GET','POST'])
def create_payment():
    intent = stripe.PaymentIntent.create(
        payment_method_types=['card'],
        amount="1000", #need to pass dollar amount here calculated in /pay route
        currency="usd",
        transfer_data={'destination': owner.stripe_id}, #need to pass owner from /pay route
        application_fee_amount="100")
    )
    client_secret = intent.client_secret
    return jsonify({"client_secret": client_secret})

So basically, my dilemma is that I have the amount of the donation and the campaign owner as variables in the /pay route.所以基本上,我的困境是我将捐赠金额和竞选所有者作为 /pay 路线中的变量。 But I need to access them when I create the stripe.PaymentIntent object when I call the /pay_now API from my JavaScript and then I need to pass the clientSecret variable back to my JavaScript file for confirmCardPayment() to actually complete the payment.但是,当我从 JavaScript 调用/pay_now API时,我需要在创建 stripe.PaymentIntent 对象时访问它们,然后我需要将clientSecret变量传递回我的 JavaScript 文件以进行confirmCardPayment()以实际完成付款。

I'm also open to different approaches if mine doesn't make sense.如果我的方法没有意义,我也愿意接受不同的方法。

I am new to Stripe & new to APIs in Flask.我是 Stripe 的新手,也是 Flask 中 API 的新手。 Any help or explanation here would be extremely helpful.这里的任何帮助或解释都会非常有帮助。 Thanks in advance!提前致谢!

You'd want to only POST to your /pay_now route, in the body of that POST you should include the amount your user intends to donate.您只想发布到您的/pay_now路由,在该 POST 的正文中,您应该包含您的用户打算捐赠的金额。 Then it's a simple case of including that amount when creating the PaymentIntent and returning the client secret to be confirmed on the client.然后是在创建 PaymentIntent 并返回要在客户端确认的客户端密钥时包含该金额的简单情况。

You might want to first do some checks on both the client and server whether the amount makes sense (eg if someone enters -1 it correctly gets rejected).您可能希望首先对客户端和服务器进行一些检查,金额是否合理(例如,如果有人输入 -1,则正确地被拒绝)。

The stripe.confirmCardPayment code should go in the then resolver of your fetch request, after the response has been parsed to JSON:在响应被解析为 JSON 之后, stripe.confirmCardPayment代码应该在你的fetch请求的then解析器中:

fetch("/pay_now", {
    method: "POST",
    body: JSON.stringify({
      amount: amount, // get this from the form
    }),
    headers: {
      "Content-Type": "application/json"
    },
  })
  .then(response => response.json())
  .then(data => {
    stripe.confirmCardPayment(data.clientSecret, {
      payment_method: {
        card: card,
        billing_details: {
          name: name, // get this from the form, like you did with the amount
        }
      }
    })
  .then(function(result) {
    if (result.error) {
      console.log(result.error.message);
    } else {
      if (result.paymentIntent.status === 'succeeded') {
        // display success message
      }
    }
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM