I am developing a React with Nodejs backend and I have implemented "stripe" in order to process payments. The problem appears when I need to get the URL which should redirect me to the Stripe payment form. I should get it from a json response, but it is empty, no matter what I send. I've even tried sending really simple data, but it still doesn't work. I've used it before without problems in this project, so I don't know what I am doing wrong here. Can anyone offer any help? Thank you!
This is the router file, which creats the session for the payment and which is also supposed to send the needed URL. I tested and the URL is correct, it is just a matter of sending it through res.json
router.post("/payment", async(req, res) => {
const course = await Courses.findByPk(req.body.items[0].id);
const storeItems = new Map([
[course.id, { priceInCents: course.price, name: course.title }],
])
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
mode: 'payment',
line_items: req.body.items.map(item => {
const storeItem = storeItems.get(item.id)
return {
price_data: {
currency: "usd",
product_data: {
name: storeItem.name,
},
unit_amount: storeItem.priceInCents,
},
quantity: item.quantity,
}
}),
success_url: 'http://localhost:3000/profile-page',
cancel_url: `http://localhost:3000/course-details/${course.id}`
})
res.json({ url: session.url });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
And this is where I should be getting the URL back, but I don't. Instead, when I console.log it, I get "undefined".
if (response.data.error) {
alert(response.data.error);
} else {
axios.post("http://localhost:3001/users_courses/payment", {
items: [
{ id: data.id, quantity: 1 },
],
}, {
headers: {
accessToken: localStorage.getItem("accessToken"),
},
}).then(res => {
if(res.ok) return res.json();
return res.json().then(json => Promise.reject(json));
}).then (( { url }) => {
window.location.href = url;
console.log(url " this is the url");
}).catch(e => {
console.error(e.error);
})
}
CodePudding user response:
I think it has to do with how you’re handling your axios
post, I think with a small change like I suggested below this should work for you.
axios
.post(
"http://localhost:3001/users_courses/payment",
{
items: [{ id: response.data.id, quantity: 1 }],
},
{
headers: {
accessToken: localStorage.getItem("accessToken"),
},
}
)
.then(({ data: { url } }) => {
window.location.replace(url);
console.log(url " this is the url");
})
.catch((e) => {
console.error(e.error);
});
Note that axios
is not like the fetch
API where you have to handle the transformation of the response body into the json object.