#javascript #node.js #express #stripe-payments #fetch-api
Вопрос:
Я создал проект, в котором использовал api stripe, и он работал отлично, я использую те же ключи api в своем следующем проекте, но он продолжает выдавать мне ошибки, я решил несколько, но все равно ничего не происходит, когда я нажимаю кнопку «Получить мой план».
Это мое app.js:
const bodyParser = require("body-parser");
const path = require('path')
const app = express();
const env = require('dotenv').config({path: './.env'});
var Publishable_Key = process.env.STRIPE_PUBLISHABLE_KEY
var Secret_Key = process.env.STRIPE_SECRET_KEY
const stripe = require('stripe')(Secret_Key)
app.get("/", function (req, res) {
res.render('home.ejs');
});
app.get('/payment/success', async (req, res) => {
const session = await stripe.checkout.sessions.retrieve(req.query.session_id);
const customer = await stripe.customers.retrieve(session.customer);
res.render('success',{name:customer.name})
});
app.get("/payment/discount",(req,res)=>{
res.render('cancel',{publishablekey:Publishable_Key})
})
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
app.post('/payment', asyncMiddleware(async (req, res)=>{
const { product } = req.body;
const YOUR_DOMAIN = "http://localhost:5000";
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "usd",
product_data: {
name: product.name
},
unit_amount: product.amount * 100,
},
quantity: product.quantity,
},
],
mode: "payment",
success_url: `${YOUR_DOMAIN}/payment/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${YOUR_DOMAIN}/payment/discount`,
});
res.json({ id: session.id });
}))
app.use(function (err, req, res, next) {
// your error code
console.log(err);
})
app.get('/offer', (req, res) => {
res.render('offer',{publishablekey:Publishable_Key})
});
Это мое предложение.ejs
<span>Your plan is ready</span>
<form id="payment-form2">
<a > <button id="submit2">Get my plan</button></a>
</form>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var publishableKey = '<%=publishablekey%>'
var stripe = Stripe(publishableKey);
const elements = stripe.elements();
const card = elements.create('card');
const form2 = document.getElementById('payment-form2');
let submitted = false;
form2.addEventListener('submit', async (e) => {
e.preventDefault();
const {error: backendError, clientSecret} = await fetch("/payment", {
headers: {'Content-Type': 'application/json'},
method: "POST",
body: JSON.stringify({
"product": {
"name": "Your Personalised Plan",
"amount": 100,
"quantity": 1
}})
})
.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>
это ошибка, которую я получаю
TypeError: Cannot read property 'name' of undefined
at C:UserssinghDocumentswizdom-nodeapp.js:52:43
at C:UserssinghDocumentswizdom-nodeapp.js:39:21
at Layer.handle [as handle_request] (C:UserssinghDocumentswizdom-nodenode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UserssinghDocumentswizdom-nodenode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:UserssinghDocumentswizdom-nodenode_modulesexpresslibrouterroute.js:112:3)
at Layer.handle [as handle_request] (C:UserssinghDocumentswizdom-nodenode_modulesexpresslibrouterlayer.js:95:5)
at C:UserssinghDocumentswizdom-nodenode_modulesexpresslibrouterindex.js:281:22
at Function.process_params (C:UserssinghDocumentswizdom-nodenode_modulesexpresslibrouterindex.js:335:12)
at next (C:UserssinghDocumentswizdom-nodenode_modulesexpresslibrouterindex.js:275:10)
at serveStatic (C:UserssinghDocumentswizdom-nodenode_modulesserve-staticindex.js:75:16)
Пожалуйста, кто-нибудь может мне в этом помочь, это важно!!
Комментарии:
1. Если вы добавите
console.log(req.body);
вышеconst { product } = req.body;
, получите ли вы ожидаемый результат?
Ответ №1:
Ошибка заключается в том, что имя не определено, что следует из запроса POST. Является ли тело запроса на публикацию в формате app.js
, в котором его ожидают?