Stripe.js - Resolve无法读取undefined的属性'stripeToken'

时间:2017-01-18 06:36:31

标签: javascript express stripe-payments

我正在使用Stripe的Checkout构建我的第一个基本Express应用程序。该应用正确呈现,但是当我提交表单时,我在stripeTokenstripeEmail上都收到了错误消息。我不确定为什么它没有通过。有什么帮助吗?

我的应用:

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);

和我的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>

1 个答案:

答案 0 :(得分:3)

问题是Stripe docs示例不包含bodyParser。

req.Body只返回表单提交中的对象。没有bodyParser,就无法获得这两个字符串。

将此添加到app.js,您就是黄金:

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