我试图在我的react应用程序中设置Stripe Checkout,如果用户单击按钮,它将通过Stripe Checkout将他们引导到Stripe的托管结账页面。在前端,它需要会话ID,我应该从我的nodejs/express服务器获取该ID。我仍然是nodejs的新手,需要帮助正确设置它,这样我才能创建一个路由,发送会话ID的正确响应。此外,此设置适用于按月订阅
Server.js
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");
const stripe = require("stripe")("sk_test_**********************");
if (process.env.NODE_ENV !== "production") require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname, "client/build", "index.html"));
});
}
app.post("/charge", (req, res) => {
(async () => {
const session = await stripe.checkout.sessions.create({
payment_method_type: ["card"],
subscription_data: {
items: [
{
plan: "plan_***********"
}
]
},
success_url:
"https://example.com/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url: "https://example.com/cancel"
});
})();
});
app.listen(port, err => {
if (err) throw err;
console.log("Server running on port" + port);
});
字符串
Checkout.js
import React, { useState, useEffect } from "react";
const Checkout = ({ price }) => {
const [isProcessing, setProcessingTo] = useState(false);
const [checkoutError, setChecoutError] = useState();
let sessionId;
const stripe = Stripe("pk_test_*******************************");
useEffect(() => {
fetch("/charge", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({})
})
.then(function(r) {
return r.json();
})
.then(function(response) {
sessionId = response.id;
});
});
const handleClick = e => {
e.preventDefault();
stripe.redirectToCheckout({
sessionId: sessionId
});
};
return (
<div>
<button onClick={handleClick}>Buy</button>
</div>
);
};
export default Checkout;
型
2条答案
按热度按时间f1tvaqid1#
当您通过Stripe API创建会话对象时,需要将结果返回给前端。目前你没有返回任何东西。
字符串
u91tlkcl2#
您可以通过将其传递到success URL来获取 checkout 会话ID
字符串
然后你可以从你的url中选择它作为一个查询参数,并使用它来获得你想要的任何东西,例如,获得订阅…