I tried integrating Stripe into my React app using the official doc at https://stripe.com/docs/recipes/elements-react. If you could go through this doc, you'll find out they're using a static value as amount (2000).
// server.js
const app = require("express")();
const stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7dc");
app.use(require("body-parser").text());
app.post("/charge", async (req, res) => {
try {
let {status} = await stripe.charges.create({
amount: 2000,
currency: "usd",
description: "An example charge",
source: req.body
});
res.json({status});
} catch (err) {
res.status(500).end();
}
});
The post
API from frontend using fetch is:
async submit(ev) {
let {token} = await this.props.stripe.createToken({name: "Name"});
let response = await fetch("/charge", {
method: "POST",
headers: {"Content-Type": "text/plain"},
body: token.id
});
if (response.ok) console.log("Purchase Complete!")
}
Here, they're sending the token ID and referencing it in the backend as source:req.body
.
Now I have tried to send amount from the frontend through the POST request as follows:
body:{
amount: 2000,
tokenId: token.Id
}
and then referencing it in backend as
...
amount: req.body.amount,
source: req.body.tokenid
...
It doesn't work. And consoling both returns undefined
I have tried many things like removing content-type header and pretty little things. Someone pointed out that I should change content-type to application/json and I've thought of setting
app.use(require("body-parser").text())
to app.use(require("body-parser").json())
but decided to consult you guys first.