gpt4 book ai didi

javascript - 对 Stripe 的 API 请求失败(错误 : Not a valid URL)

转载 作者:行者123 更新时间:2023-12-04 00:51:39 26 4
gpt4 key购买 nike

我想在 Node 应用程序中使用 Stripe Prebuilt Checkout Page 构建一个简单的结帐页面。
我遵循 Stripe 文档中的所有必要步骤,但 API 请求似乎不起作用。
server.js -

const express = require("express");
const stripe = require("stripe")(
"<mySecretKey>"
);

const app = express();

app.get("/checkout-sucess", (req, res) => {
res.send("<h1>Success</h1>");
});

app.get("/checkout-cancel", (req, res) => {
res.send("<h1>Cancelled</h1>");
});

app.post("/create-checkout-session", async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "inr",
product_data: {
name: "Cewa",
},
unit_amount: 200,
},
quantity: 1,
},
],
mode: "payment",
success_url: "/checkout-success",
cancel_url: "/checkout-cancel",
});

res.json({ id: session.id });
});

app.listen(4242, () => {
console.log("Server is live on Port 4242!");
});
checkout.html -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Stripe API Test</title>
<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>
<body>
<button
type="button"
id="checkout-button"
style="
padding: 20px;
background-color: beige;
cursor: pointer;
outline: none;
"
>
Checkout
</button>
</body>

<script type="text/javascript">
var stripe = Stripe(
"<myPublishableAPIKey"
);
var checkoutButton = document.getElementById("checkout-button");
checkoutButton.addEventListener("click", function () {
fetch("http://localhost:4242/create-checkout-session", {
method: "POST",
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.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>
</html>
当我提出这个请求时,我在控制台中收到来自 checkout.html 的以下错误-
错误:不是有效的 URL
我不认为我错过了文档中的任何内容。知道出了什么问题吗?提前致谢。

最佳答案

您需要添加真正的成功和取消网址,请检查以下代码:

const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "inr",
product_data: {
name: "Cewa",
},
unit_amount: 200,
},
quantity: 1,
},
],
mode: "payment",
success_url: "http://sitename.com/checkout-success",
cancel_url: "http://sitename.com/checkout-cancel",
});

关于javascript - 对 Stripe 的 API 请求失败(错误 : Not a valid URL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65931950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com