1

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.

Mosh Feu
  • 24,625
  • 12
  • 74
  • 111
Cole
  • 439
  • 1
  • 4
  • 11

1 Answers1

3

If I understand you correctly, you want to post a json from client to express server. If so:

Client

fetch({
  method: 'POST',
  body: JSON.stringify({
    amount: 2000,
    tokenId: token.Id
  }),
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
});

Server

const app = express();
// if express >= 4
app.use(express.json());

app.post("/charge", async (req, res) => {
  console.log(req.body);
});

Any by the way tokenId !== tokenid (in req.body.tokenid)

Mosh Feu
  • 24,625
  • 12
  • 74
  • 111
  • What then happens to `app.use(require("body-parser").text());`? Do I need to change it to `app.use(require("body-parser").json());`? Or just remove the line entirely and use `app.use(express.json())`? – Cole May 30 '19 at 10:08
  • If you want to post json from the client you need to support it in your server (parse as json but not as text). And if you're using express > 4 you don't need `body-parser` (https://stackoverflow.com/a/49943829/863110). – Mosh Feu May 30 '19 at 10:23
  • @Cole thoughts? – Mosh Feu Jun 02 '19 at 08:06
  • :) Glad to hear. – Mosh Feu Jun 05 '19 at 10:05