I want to build a simple checkout page using the Stripe Prebuilt Checkout Page in a Node application.
I follow all the necessary steps in the Stripe docs but the API request doesn't seem to work.
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>
When I make this request, I get the following error in the console coming from checkout.html
-
Error: Not a valid URL
I don't think I've missed anything from the docs. Any idea what's going wrong? Thanks in advance.
question from:
https://stackoverflow.com/questions/65931950/api-request-to-stripe-fails-error-not-a-valid-url 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…