简体   繁体   English

Stripe Webhook 验证

[英]Stripe Webhook Validation

I keep getting this error:我不断收到此错误:

No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing

I believe it's something to do with the middleware that I'm using, but I'm not sure which one.我相信这与我使用的中间件有关,但我不确定是哪一个。 Here's my middlewares这是我的中间件

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "../views"));
app.use(
  favicon(path.join(__dirname, "../public/img/logo", "logo-bg-round.png"))
);
app.use(express.static("public"));
app.use(
  session({
    name: "oauth",
    secret: "PlincoOAUTH2",
    resave: true,
    saveUninitialized: true,
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.configure(socketio());
app.configure(express.rest());
app.use("/projects", new DashboardService());
app.on("connection", (conn) => app.channel("stream").join(conn));
app.publish(() => app.channel("stream"));
app.use("/auth", require("./routes/auth"));
app.use(cors());

Here's my route:这是我的路线:

const Stripe = require("stripe");
const stripe = Stripe(
  "sk_test_..."
);

// Stripe requires the raw body to construct the event
app.post(
  "/payments/webhook",
  bodyParser.raw({ type: "application/json" }),
  (req, res) => {
    const sig = req.headers["stripe-signature"];
    const webhookSecret = "whsec_...";
    let event;

    try {
      event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
    } catch (err) {
      // On error, log and return the error message
      console.log(`❌ Error message: ${err.message}`);
      return res.status(400).send(`Webhook Error: ${err.message}`);
    }

    // Successfully constructed event
    console.log("✅ Success:", event.id);

    // Return a response to acknowledge receipt of the event
    res.json({ received: true });
  }
);

I've tried many things and cannot find a solution, how do I fix this?我已经尝试了很多事情,但找不到解决方案,我该如何解决?

You're not getting the raw body the way you're doing it.你没有按照你的方式得到原始的身体。 You need to 'exclude' your webhook route from the express.json() body parser like is described here: https://github.com/stripe/stripe-node/blob/master/examples/webhook-signing/node-express/express.js您需要从 express.json() 正文解析器中“排除”您的 webhook 路由,如下所述: https : //github.com/stripe/stripe-node/blob/master/examples/webhook-signing/node-express /express.js

So instead of所以代替

app.use(express.json());

you need something like this:你需要这样的东西:

app.use((req, res, next) => {
  if (req.originalUrl === '/payments/webhook') {
    next();
  } else {
    express.json()(req, res, next);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM