我到处寻找答案,但还没有找到解决方案 . 我正在使用Stripe向用户收费,但是,付款不应该是硬编码的,因为价格会根据回答的最常见问题而变化 . 我想要做的是获取确认页面(HTML)上给出的“总价”并将该金额计入Stripe(使用Node) .
我目前正在进行令牌化工作,并且当金额被硬编码时收费成功,但我需要更改费用金额 . 有没有人知道Stripe(www.stripe.com)是否可以这样做?
my app.js file (portion):
// 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}`);
});
UPDATE
我还想从输入表单更新用户的电子邮件信息,而不是像目前在这行上那样进行硬编码: email: "random-email@gmail.com"
Second Update
Stripe form:
<div class="" style="margin-top: 60px;">
<h2 class="quote-info">Estimated total: $<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>
Function found at the bottom of HTML page in a script tag:
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();
}
2 回答
You need to retrieve the POST data from the form in Express.
方法1(隐藏输入)
首先,您需要确保将总金额从表单传递到后端:
然后你应该能够做到这一点:
方法2(命名为路径参数)
在这种情况下,您不会向表单添加隐藏的输入,而是将表单的
action
更新为:然后修改您的Express路由以引用此值likeo:
Scotch.io also has a great explanation of handling POST parameters in Express.
你需要做的是从你的前端到你的后端进行通信,并告诉后端对一定数量的电子邮件进行条带化收费 . 这样做的方法是在javascript中从前端向节点后端发出POST请求 . 这是你需要做的:
在服务器代码中设置POST endpoints 以接收发布请求 . 在帖子请求中,您将收到指示收费金额和电子邮件的数据,然后通过您之前硬编码的代码执行Strip Charge . This guide显示了制作POST endpoints 的示例 .
在前端,创建一个javascript方法,该方法在单击表单上的提交按钮时运行 . 在该功能中,通过您在后端创建的URL向后端发出发布请求
This stack overflow answer提供了一个使用此方法从前端向后端发送数据的快速示例 .