javascript - 通过条带结帐会话传递参数
问题描述
我有这个在我的我payments.ejs
的
<head>
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<div class="box">
<!-- <form action="/paymentsPage" method="POST"> -->
<div class="input-container">
<input type="text" name="code" id="code" required/>
<label>Code</label>
</div>
<button type="button" class="btn" id="checkout-button">submit</button>
<!-- </form> -->
</div>
<!-- a312b7a0338d -->
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_test_51J0C0JFtPC3YhhMO5SoK5wnP01gK8apNhjq6TD21T3VHH6a7vet3Cl4PplWk7mkTPtJQwJVpt6ILjJMsnKPQOwCV00RDCU0c9j");
var checkoutButton = document.getElementById("checkout-button");
checkoutButton.addEventListener("click", function () {
var code = document.getElementById("code").value
console.log(code)
fetch("/create-checkout-session", {
method: "POST",
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id, code: code });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
我想传递code
到后端。所以我尝试将它作为参数传递,stripe.redirectToCheckout({ sessionId: session.id, code: code })
但它没有用。我如何传递code
到后端
后端代码:
app.post('/create-checkout-session', async (req, res) => {
var userCode = req.body.code;
console.log("51: " + userCode)
var clientName = "gianluca"
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'cad',
product_data: {
name: "Invoice for " + clientName,
images: ['https://i.imgur.com/EHyR2nP.png'],
},
unit_amount: 2000,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/success.html`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
});
res.json({ id: session.id });
});
将参数传递到后端的步骤是什么?谢谢 :)
解决方案
当我这样做时它起作用了:
fetch("/create-checkout-session", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
code: code
}),
})
供任何查看此内容的人将来参考:)
推荐阅读
- python - python的正则表达式
- html - CSS slider doesn't scroll on mobile
- cloud-foundry - 如何在 PCF 中禁用“event_type”:“ContainerMetric”
- c# - Enterprise Architect 中图像的标记值
- android - error adding viewpager in fragment
- angularjs - 任何焦点
- c# - 代码阶段更新集合值
- vue.js - Vue JS v-model not working
- javascript - testing button class with enzyme
- vba - VBA How to make a msgbox to repeat only once for certain values