【问题标题】:Node.js/Express 404 error on POST to '/webhook'POST 到“/webhook”时出现 Node.js/Express 404 错误
【发布时间】:2021-08-24 09:14:21
【问题描述】:

由于某种原因,我收到 404 错误,但仅在向“/webhook”发送发布请求时出现,但我不知道为什么。我的帖子的其余部分都很好,但我不断收到这条消息[404] POST http://localhost:3001/webhook [evt_1IzeQ1EUG2WFNVaczcOMJWgu]

端口 3001 是我的客户端,我的服务器在端口 8080(firebase 模拟器)上运行。知道我做错了什么吗?

index.js

require("dotenv").config();
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const { buffer } = require('micro');
const admin = require('firebase-admin');


const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);

const serviceAccount = require("./permissions.json");

const firebaseAdmin = !admin.apps.length ? admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
}, 'firebaseAdmin') : admin.firebaseAdmin();


// api


// app config
const app = express();

// middlewares
app.use(cors({origin: true}));
app.use(express.json());

// api routes
app.get("/", (request, response) => response.status(200).send("hello world"));

app.post("/create-checkout-session", async (request, response) => {
  const { cart, email} = request.body;

  const transformedItems = cart.map(item => ({
    description: item.description === '' ? 'no description' : item.description,
    quantity: 1,
    price_data: {
      currency: 'usd',
      unit_amount: item.price * 100,
      product_data: {
        name: item.title,
      },

    }
  }));
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    shipping_address_collection: {
      allowed_countries: ['US']
    },
    line_items: transformedItems,
    mode: 'payment',
    success_url: `${process.env.DOMAIN}/confirmation`,
    cancel_url: `${process.env.DOMAIN}/sorry`,
    metadata: {
      email
    }
  });
  response.status(200).json({ id: session.id});
});


const endpointSecret = process.env.STRIPE_SIGNING_SECRET;

const fulfillOrder = async (session) => {
  console.log('Fulfilling Booking', session);
  
  return firebaseAdmin
    .firestore()
    .collection('customers')
    .doc(session.metadata.email)
    .collection('orders')
    .doc(session.id).set({
      amount: session.amount_total / 100,
      timestamp: admin.firestore.FieldValue.serverTimestamp(),
    })
    .then(() => {
      console.log(`SUCCESS! Order #${session.id} has been added to the database!`);
    })
} 

app.post("/webhook", async (request, response) => {
  const requestBuffer = await buffer(request);
  const payload = requestBuffer.toString();
  const sig = request.headers("stripe-signature");

  let event;

  try {
    event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
  } catch (err) {
    console.log('ERROR!!!', err.message);
    return res.status(400).send(`Webhook error: ${err.message}`);
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object; 
    return fulfillOrder(session)
      .then(() => response.status(200))
      .catch((err) => response.status(400)
      .send(`Webhook error ${err.message}`));
  }
});


// listen command
exports.api = functions.https.onRequest(app, firebaseAdmin);

【问题讨论】:

  • 根据您的屏幕截图,3001 端口上没有运行任何服务?

标签: javascript node.js firebase express stripe-payments


【解决方案1】:

要在本地测试 Stripe webhook(即在 localhost 上),您需要将这些 webhook 事件转发到您的 localhost 端口。为此,您需要安装和配置Stripe CLI。安装后,您可以使用以下命令对其进行配置:

stripe login

stripe listen --forward-to localhost:5001/webhook

// To manually trigger events using CLI
stripe trigger payment_intent.created

因为如果您从仪表板触发事件,它们将无法到达您的本地主机。

端口号应与 Cloud Functions 模拟器相同,并且完整的 URL 应与您的函数运行的位置相匹配。在你的情况下,“http://localhost:5001/piers-laine/us-central1/api/webhook”

【讨论】:

  • 我已经这样做了,我收到了 2 条消息。 1) payment_intent.created 2) [404] POST localhost:3001/webhook 看来我的 payment_intent 有效,但我的数据都没有设置到我的 firestore 数据库
  • @DylanWilliamson 你能分享 Firebase Emulator 的截图吗?我想查看端口和日志。
  • 我已将屏幕截图添加到我的帖子中
  • @DylanWilliamson 你的函数模拟器在端口 5001 上运行。所以 webhook URL 应该是 http://localhost:5001/webhook
  • 我该怎么做?我不完全确定如何在相对路径上使用 url
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 2022-09-30
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
相关资源
最近更新 更多