javascript - 从 HTML 获取付款金额以在 Node.js 文件中收费

标签 javascript html node.js stripe-payments

我已经到处寻找答案,但还没有找到解决方案。我正在使用 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: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b796a656f6466266e666a62674b6c666a626725686466" rel="noreferrer noopener nofollow">[email protected]</a>",
    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: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e5c4f404a4143034b434f47426e49434f4742004d4143" rel="noreferrer noopener nofollow">[email protected]</a>"

第二次更新

Stripe 形式:

<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();
  }

最佳答案

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


方法1(隐藏输入)

Path of least resistance based on your current implementation.

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

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.

关于javascript - 从 HTML 获取付款金额以在 Node.js 文件中收费,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48313835/

相关文章:

javascript - 从 ui-grid 中的可扩展行中删除列标题

node.js - 来自其他容器的 Docker mongo 镜像 'Connection refused'

node.js - http.createServer(app) 诉 http.Server(app)

javascript - 在 select2 jquery 插件中没有调用 initSelection

javascript - 使用 jQuery 和 AJAX 更新 SQL 时出现问题

javascript - 搜索有关速度/效率的 JSON 对象

html - 如何使YouTube自动播放功能可用于网站?

html - 使 parent 的高度达到绝对定位 child 的100%

iOS 浏览器不遵守 HTML5 音频预加载标签

node.js - 运行 yarn install 时,一个模块不提供另一个模块是什么意思?