【问题标题】:Getting payment amount from HTML to charge in Node.js file从 HTML 获取付款金额以在 Node.js 文件中收费
【发布时间】:2018-06-27 02:02:46
【问题描述】:

我已经到处寻找答案,但没有找到解决方案。我正在使用 Stripe 向用户收费,但是,付款不应该是硬编码的,因为定价会根据回答的各种问题而变化。我想要做的是获取确认页面(HTML)上给出的“总价”并将该金额收取给 Stripe(使用 Node)。

我目前正在进行令牌化,并且当金额被硬编码时收费成功,但我需要更改收费金额。有谁知道 Stripe (www.stripe.com) 是否可以做到这一点?

我的 app.js 文件(部分):

// charge route
app.post('/charge', (req, res) => {
  const amount = 2500; <-- needs to change to not be hardcoded

  stripe.customers.create({
    email: "random-email@gmail.com",
    source: req.body.mytoken
  })
  .then(customer =>  {
    stripe.charges.create({
    amount,
    description:'item desc',
    currency:'usd',
    customer:customer.id
  })})
  .then(charge => res.send('success'));
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

更新

我还想从输入表单中更新用户的电子邮件信息,而不是像目前在此行中那样对其进行硬编码:email: "random-email@gmail.com"

第二次更新

条纹形式:

<div class="" style="margin-top: 60px;">
  <h2 class="quote-info">Estimated total&#58; $<span id="new_text"></span> USD</h2>
</div>


   <!-- Payment form -->
   <form action="/charge" method="post" id="payment-form">
      <div class="form-row">
         <label for="card-element">
           Credit or debit card
         </label>
       <div id="card-element">
        <!-- a Stripe Element will be inserted here. -->
       </div>

       <!-- Used to display form errors -->
       <div id="card-errors"></div>
       </div>

        <button>Submit Payment</button>
   </form>

在 HTML 页面底部的脚本标签中找到的函数:

function stripeTokenHandler(token) {
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');

    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);

    form.appendChild(hiddenInput);
    var formData = JSON.stringify({
      mytoken: token.id
    });

    $.ajax({
      type: "POST",
      url: "/charge",
      data: formData,
      success: function(){alert("done")},
      dataType: "json",
      contentType: "application/json"
    });
    form.submit();
  }

【问题讨论】:

  • 你能在这里提供更多的上下文吗?在不知道您实际在做什么或尝试做什么的情况下,很难确切地知道如何提供答案。如果可以,请分享您的一些相关代码。
  • @jonnyAsmar 我已经用一些相关代码更新了我的问题。

标签: javascript html node.js stripe-payments


【解决方案1】:

您需要在 Express 中从表单中检索 POST 数据。


方法一(隐藏输入)

基于您当前实施的阻力最小的路径。

首先,您需要确保总金额从您的表单传递到后端:

function stripeTokenHandler(token) {
  var form = document.getElementById('payment-form');

  var token = document.createElement('input');
  token.setAttribute('type', 'hidden');
  token.setAttribute('name', 'stripeToken');
  token.setAttribute('value', token.id);

  var totalAmount = document.createElement('input');
  token.setAttribute('type', 'hidden');
  token.setAttribute('name', 'totalAmount');
  token.setAttribute('value', $('#new_text').innerHTML);
  // or, prefereably, grab this directly from the var you're using to update the #new_text span's value

  form.appendChild(token);
  form.appendChild(totalAmount);

  // You could also just use the variables here (i.e. token.id) instead of grabbing it from the inputs generated above
  var formData = JSON.stringify({
    mytoken: token.value,
    totalAmount: totalAmount.value
  });

  // You're not actually referencing the form here, so you don't technically need to append the inputs above.
  // I've only included them for consistency. You're setting the values to be submitted to /charge when you set
  // the variable formData above and then passing it via the data property of $.ajax below.
  $.ajax({
    type: "POST",
    url: "/charge",
    data: formData,
    success: function(){alert("done")},
    dataType: "json",
    contentType: "application/json"
  });
  form.submit();
}

那么你应该可以做到这一点:

app.post('/charge', (req, res) => {
  const amount = req.param('totalAmount');
  ...

方法2(命名路由参数)

在这种情况下,您不会向表单添加隐藏输入,而是将action 更新为您的表单,如下所示:

action="/charge/TOTAL_AMOUNT/EMAIL"

然后修改您的 Express 路由以引用此值,如下所示:

app.get('/charge/:totalAmount/:email', (req, res) => {
    const amount = req.params.totalAmount;
    const email = req.params.email;
    ...

Scotch.io also has a great explanation of handling POST parameters in Express.

【讨论】:

  • TOKENIZED_TOTAL 是从哪里来的?
  • 哎呀,对不起。我最初误解了你的情况。在一个地方而不是另一个地方编辑它。这只是如何使用在它下面创建的路线的一个例子。我已经进行了相应的编辑。
  • 好的,我只是专注于让付款总额先发挥作用。所以我启动了服务器 localhost:5000 并输入了 Stripe 提供的卡值。提交后,它会重新路由并显示“无法发布 /charge/TOTAL_AMOUNT。我对 node 尤其是 Stripe 还很陌生。
  • 要使用这样的路径,您需要更改在后端 (app.js) 处理它的方式。 TOTAL_AMOUNT 只是我放在那里的占位符。在这种情况下,它实际上应该是值(即/charge/2500)。但是,我认为您在这里阻力最小的路径是使用已发布的数据,因为您已经这样做了。既然您已经提供了用于从前端提交的代码,我将很快为您更新我的答案,并为您提供一些更具体的代码。
  • 太棒了!你是救生员。
【解决方案2】:

你需要做的是从你的前端到你的后端沟通,并告诉后端收取一定数量的条纹费用 + 一定的电子邮件。做到这一点的方法是从前端在 javascript 中向您的节点后端发出 POST 请求。以下是您需要做的:

  • 在您的服务器代码中设置一个 POST 端点以接收发布请求。在发布请求中,您将收到指示收费金额的数据和电子邮件,然后通过您之前硬编码的代码执行剥离收费。 This guide 展示和制作 POST 端点的示例。
  • 在您的前端,创建一个 javascript 方法,该方法在您单击表单上的提交按钮时运行。在该函数中,通过您在后端创建的 URL 向后端发出 post 请求

This stack overflow answer 给出了一个很好的快速示例,使用此方法将数据从前端发送到后端。

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 2020-04-21
    • 2021-10-01
    • 2018-12-08
    • 2017-11-11
    • 1970-01-01
    • 2017-07-28
    • 2013-06-25
    相关资源
    最近更新 更多