Jeremy P. Beasley
Jeremy P. Beasley

Reputation: 709

Stripe.js - Resolve Cannot read property 'stripeToken' of undefined

I'm building my first basic Express app using Stripe's Checkout. The app renders correctly but when I submit the form, I get an error on both stripeToken and stripeEmail. I'm not sure why it's not passing through. Any help?

My app:

const keyPublishable = process.env.PUBLISHABLE_KEY;
const keySecret = process.env.SECRET_KEY;

const app = require("express")();
const stripe = require("stripe")(keySecret);

app.set('view engine', 'ejs')

app.get("/", (req, res) =>
  res.render("index.ejs", {keyPublishable}));

app.post("/charge", (req, res) => {
  let amount = 500;

  stripe.customers.create({
     email: req.body.stripeEmail,
    source: req.body.stripeToken
  })
  .then(customer =>
    stripe.charges.create({
      amount,
      description: "Sample Charge",
         currency: "usd",
         customer: customer.id
    }))
  .then(charge => res.render("charge.ejs"));
});

app.listen(7000);

and my index.ejs

<form action="/charge" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_Gbu2akKhNgGjbKi4LPxOOWqc"
    data-amount="500"
    data-name="Ojoseyewear"
    data-description="Widget"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-locale="auto">
  </script>
</form>

Upvotes: 2

Views: 895

Answers (1)

Jeremy P. Beasley
Jeremy P. Beasley

Reputation: 709

The issue was that the Stripe docs example did not include bodyParser.

req.Body just returns an object from the form submission. Without bodyParser, there's no way to get those two strings.

Add this to app.js and you're golden:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

Upvotes: 3

Related Questions